From a858d3325b666257c6c7aac842f1e3b62930443c Mon Sep 17 00:00:00 2001 From: Dima Date: Wed, 23 Sep 2026 21:22:49 +0300 Subject: [PATCH 1/9] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B8=20Go=20API=20=D0=B8=20=D0=BA=D0=BE=D0=BD=D1=82?= =?UTF-8?q?=D0=B5=D0=B9=D0=BD=D0=B5=D1=80=20=D0=B8=D0=B7=20=D0=BB=D0=B0?= =?UTF-8?q?=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD=D0=BE=D0=B9=20?= =?UTF-8?q?1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 6 + Dockerfile | 49 ++++++ cmd/healthcheck/main.go | 24 +++ go.mod | 5 + go.sum | 2 + src/chat.go | 83 +++++++++ src/chat_get_handler.go | 105 ++++++++++++ src/chat_handler.go | 184 ++++++++++++++++++++ src/chat_list_handler.go | 246 +++++++++++++++++++++++++++ src/chat_subresource_handler.go | 41 +++++ src/concurrency_test.go | 221 ++++++++++++++++++++++++ src/current_user_handler.go | 58 +++++++ src/main.go | 159 +++++++++++++++++ src/message.go | 111 ++++++++++++ src/message_handler.go | 179 ++++++++++++++++++++ src/message_handler_test.go | 291 ++++++++++++++++++++++++++++++++ src/message_list_handler.go | 224 ++++++++++++++++++++++++ src/message_store_test.go | 64 +++++++ src/user.go | 58 +++++++ src/user_handler.go | 133 +++++++++++++++ src/user_handler_test.go | 132 +++++++++++++++ 21 files changed, 2375 insertions(+) create mode 100644 Dockerfile create mode 100644 cmd/healthcheck/main.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 src/chat.go create mode 100644 src/chat_get_handler.go create mode 100644 src/chat_handler.go create mode 100644 src/chat_list_handler.go create mode 100644 src/chat_subresource_handler.go create mode 100644 src/concurrency_test.go create mode 100644 src/current_user_handler.go create mode 100644 src/main.go create mode 100644 src/message.go create mode 100644 src/message_handler.go create mode 100644 src/message_handler_test.go create mode 100644 src/message_list_handler.go create mode 100644 src/message_store_test.go create mode 100644 src/user.go create mode 100644 src/user_handler.go create mode 100644 src/user_handler_test.go diff --git a/.dockerignore b/.dockerignore index bc16e556..e6fa656c 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,5 @@ .git +.gitignore .github .env .env.* @@ -18,3 +19,8 @@ __pycache__ node_modules evidence .DS_Store +README.md +REPORT.md +COURSE.md +CONTRIBUTING.md +MAINTAINERS.md diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..d18fbf96 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,49 @@ +FROM golang:1.22.2-bookworm AS builder + +WORKDIR /src + +COPY go.mod go.sum ./ + +RUN go mod download + +COPY src ./src +COPY cmd ./cmd + +RUN CGO_ENABLED=0 \ + GOOS=linux \ + go build \ + -trimpath \ + -ldflags="-s -w" \ + -o /out/messenger \ + ./src + +# healthcheck script build +RUN CGO_ENABLED=0 \ + GOOS=linux \ + go build \ + -trimpath \ + -ldflags="-s -w" \ + -o /out/healthcheck \ + ./cmd/healthcheck + +FROM debian:12.15-slim + +RUN groupadd --system app \ + && useradd --system --gid app --no-create-home app + +WORKDIR /app + +COPY --from=builder /out/messenger ./messenger +COPY --from=builder /out/healthcheck ./healthcheck + +ENV APP_HOST=0.0.0.0 +ENV APP_PORT=8080 + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD ["./healthcheck"] + +USER app:app + +CMD ["./messenger"] diff --git a/cmd/healthcheck/main.go b/cmd/healthcheck/main.go new file mode 100644 index 00000000..c5e60059 --- /dev/null +++ b/cmd/healthcheck/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "net/http" + "os" + "time" +) + +func main() { + client := http.Client{ + Timeout: 2 * time.Second, + } + + response, err := client.Get("http://127.0.0.1:8080/health/ready") + if err != nil { + os.Exit(1) + } + + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + os.Exit(1) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..e6db6494 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module messenger + +go 1.22.2 + +require github.com/google/uuid v1.6.0 diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..7790d7c3 --- /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/src/chat.go b/src/chat.go new file mode 100644 index 00000000..7ef1833c --- /dev/null +++ b/src/chat.go @@ -0,0 +1,83 @@ +package main + +import ( + "sync" + "time" + + "github.com/google/uuid" +) + +type Chat struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type chatStore struct { + mu sync.RWMutex + byID map[string]Chat +} + +func newChatStore() *chatStore { + return &chatStore{ + byID: make(map[string]Chat), + } +} + +func (s *chatStore) create(title string, memberIDs []string) Chat { + s.mu.Lock() + defer s.mu.Unlock() + + // Делаем копию, чтобы вызывающий код не мог изменить + // список участников после сохранения чата. + membersCopy := append([]string(nil), memberIDs...) + + chat := Chat{ + ID: uuid.New().String(), + Title: title, + MemberIDs: membersCopy, + CreatedAt: time.Now().UTC(), + } + + s.byID[chat.ID] = chat + + return chat +} + +func (s *chatStore) getByID(id string) (Chat, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + + chat, exists := s.byID[id] + + return chat, exists +} + +func (s *chatStore) isMember(chat Chat, userID string) bool { + for _, memberID := range chat.MemberIDs { + if memberID == userID { + return true + } + } + + return false +} + +func (s *chatStore) listForUser(userID string) []Chat { + s.mu.RLock() + defer s.mu.RUnlock() + + chats := make([]Chat, 0) + + for _, chat := range s.byID { + if !s.isMember(chat, userID) { + continue + } + + chat.MemberIDs = append([]string(nil), chat.MemberIDs...) + chats = append(chats, chat) + } + + return chats +} diff --git a/src/chat_get_handler.go b/src/chat_get_handler.go new file mode 100644 index 00000000..3710ffa2 --- /dev/null +++ b/src/chat_get_handler.go @@ -0,0 +1,105 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" + "strings" + + "github.com/google/uuid" +) + +func getChatHandler( + userStore *userStore, + chatStore *chatStore, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + + if r.Method != http.MethodGet { + writeError( + w, + http.StatusMethodNotAllowed, + "method_not_allowed", + "method not allowed", + requestID, + ) + return + } + + currentUserID := r.Header.Get("X-User-Id") + + if currentUserID == "" { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "valid X-User-Id header is required", + requestID, + ) + return + } + + if _, exists := userStore.getByID(currentUserID); !exists { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "unknown user", + requestID, + ) + return + } + + chatID := strings.TrimPrefix( + r.URL.Path, + "/api/v1/chats/", + ) + + if chatID == "" || strings.Contains(chatID, "/") { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid chat id", + requestID, + ) + return + } + + if _, err := uuid.Parse(chatID); err != nil { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid chat id", + requestID, + ) + return + } + + chat, exists := chatStore.getByID(chatID) + + if !exists || !chatStore.isMember(chat, currentUserID) { + // Для неизвестного и чужого чата используется одинаковый 404. + // Это не раскрывает постороннему пользователю наличие чата. + writeError( + w, + http.StatusNotFound, + "not_found", + "chat not found", + requestID, + ) + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + if err := json.NewEncoder(w).Encode(chat); err != nil { + log.Printf("failed to encode chat response: %v", err) + return + } + } +} diff --git a/src/chat_handler.go b/src/chat_handler.go new file mode 100644 index 00000000..5842cba5 --- /dev/null +++ b/src/chat_handler.go @@ -0,0 +1,184 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" + "strings" + "unicode/utf8" + + "github.com/google/uuid" +) + +type createChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +func createChatHandler( + userStore *userStore, + chatStore *chatStore, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + + if r.Method != http.MethodPost { + writeError( + w, + http.StatusMethodNotAllowed, + "method_not_allowed", + "method not allowed", + requestID, + ) + return + } + + currentUserID := r.Header.Get("X-User-Id") + + if currentUserID == "" { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "valid X-User-Id header is required", + requestID, + ) + return + } + + if _, exists := userStore.getByID(currentUserID); !exists { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "unknown user", + requestID, + ) + return + } + + if !strings.HasPrefix( + r.Header.Get("Content-Type"), + "application/json", + ) { + writeError( + w, + http.StatusUnsupportedMediaType, + "unsupported_media_type", + "content type must be application/json", + requestID, + ) + return + } + + var request createChatRequest + + if err := decodeJSONBody(r, &request); err != nil { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid JSON body", + requestID, + ) + return + } + + if strings.TrimSpace(request.Title) == "" { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "title must not be blank", + requestID, + ) + return + } + + if utf8.RuneCountInString(request.Title) > 100 { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "title is too long", + requestID, + ) + return + } + + if len(request.MemberIDs) == 0 || len(request.MemberIDs) > 100 { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "member_ids must contain from 1 to 100 users", + requestID, + ) + return + } + + seenMembers := make(map[string]struct{}) + + for _, memberID := range request.MemberIDs { + if _, err := uuid.Parse(memberID); err != nil { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "member_ids must contain valid UUIDs", + requestID, + ) + return + } + + if _, duplicate := seenMembers[memberID]; duplicate { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "member_ids must not contain duplicates", + requestID, + ) + return + } + + seenMembers[memberID] = struct{}{} + + if _, exists := userStore.getByID(memberID); !exists { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "all members must be existing users", + requestID, + ) + return + } + } + + if _, included := seenMembers[currentUserID]; !included { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "current user must be a chat member", + requestID, + ) + return + } + + chat := chatStore.create( + request.Title, + request.MemberIDs, + ) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + + if err := json.NewEncoder(w).Encode(chat); err != nil { + log.Printf("failed to encode chat response: %v", err) + return + } + } +} diff --git a/src/chat_list_handler.go b/src/chat_list_handler.go new file mode 100644 index 00000000..6d036828 --- /dev/null +++ b/src/chat_list_handler.go @@ -0,0 +1,246 @@ +package main + +import ( + "encoding/base64" + "encoding/json" + "net/http" + "sort" + "strconv" + "time" +) + +type chatPage struct { + Items []Chat `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type chatCursor struct { + UserID string `json:"user_id"` + CreatedAt time.Time `json:"created_at"` + ChatID string `json:"chat_id"` +} + +func encodeChatCursor(cursor chatCursor) (string, error) { + data, err := json.Marshal(cursor) + if err != nil { + return "", err + } + + return base64.RawURLEncoding.EncodeToString(data), nil +} + +func decodeChatCursor(value string) (chatCursor, error) { + data, err := base64.RawURLEncoding.DecodeString(value) + if err != nil { + return chatCursor{}, err + } + + var cursor chatCursor + + if err := json.Unmarshal(data, &cursor); err != nil { + return chatCursor{}, err + } + + if cursor.UserID == "" || + cursor.ChatID == "" || + cursor.CreatedAt.IsZero() { + return chatCursor{}, strconv.ErrSyntax + } + + return cursor, nil +} + +func listChatsHandler( + userStore *userStore, + chatStore *chatStore, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + + if r.Method != http.MethodGet { + writeError( + w, + http.StatusMethodNotAllowed, + "method_not_allowed", + "method not allowed", + requestID, + ) + return + } + + currentUserID := r.Header.Get("X-User-Id") + + if currentUserID == "" { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "valid X-User-Id header is required", + requestID, + ) + return + } + + if _, exists := userStore.getByID(currentUserID); !exists { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "unknown user", + requestID, + ) + return + } + + limit := 50 + + if values, exists := r.URL.Query()["limit"]; exists { + if len(values) != 1 || values[0] == "" { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid limit", + requestID, + ) + return + } + + parsedLimit, err := strconv.Atoi(values[0]) + if err != nil || parsedLimit < 1 || parsedLimit > 100 { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "limit must be between 1 and 100", + requestID, + ) + return + } + + limit = parsedLimit + } + + var cursor *chatCursor + + if values, exists := r.URL.Query()["cursor"]; exists { + if len(values) != 1 || values[0] == "" { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid cursor", + requestID, + ) + return + } + + decoded, err := decodeChatCursor(values[0]) + if err != nil || decoded.UserID != currentUserID { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid cursor", + requestID, + ) + return + } + + cursor = &decoded + } + + chats := chatStore.listForUser(currentUserID) + + sort.Slice(chats, func(i, j int) bool { + if chats[i].CreatedAt.Equal(chats[j].CreatedAt) { + return chats[i].ID < chats[j].ID + } + + return chats[i].CreatedAt.Before(chats[j].CreatedAt) + }) + + if cursor != nil { + filtered := make([]Chat, 0, len(chats)) + + for _, chat := range chats { + isAfterCursor := chat.CreatedAt.After(cursor.CreatedAt) || + (chat.CreatedAt.Equal(cursor.CreatedAt) && + chat.ID > cursor.ChatID) + + if isAfterCursor { + filtered = append(filtered, chat) + } + } + + chats = filtered + } + + pageItems := chats + + if len(pageItems) > limit { + pageItems = pageItems[:limit] + } + + page := chatPage{ + Items: pageItems, + NextCursor: nil, + } + + if len(chats) > limit { + last := pageItems[len(pageItems)-1] + + nextCursor, err := encodeChatCursor(chatCursor{ + UserID: currentUserID, + CreatedAt: last.CreatedAt, + ChatID: last.ID, + }) + + if err != nil { + writeError( + w, + http.StatusInternalServerError, + "internal_error", + "internal server error", + requestID, + ) + return + } + + page.NextCursor = &nextCursor + } + + if page.Items == nil { + page.Items = make([]Chat, 0) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + if err := json.NewEncoder(w).Encode(page); err != nil { + return + } + } +} + +func chatCollectionHandler( + userStore *userStore, + chatStore *chatStore, +) http.HandlerFunc { + createHandler := createChatHandler(userStore, chatStore) + listHandler := listChatsHandler(userStore, chatStore) + + return func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodPost: + createHandler(w, r) + case http.MethodGet: + listHandler(w, r) + default: + // Передаём обработку createHandler, чтобы получить + // единый JSON-формат ошибки. + createHandler(w, r) + } + } +} diff --git a/src/chat_subresource_handler.go b/src/chat_subresource_handler.go new file mode 100644 index 00000000..0f5dfeeb --- /dev/null +++ b/src/chat_subresource_handler.go @@ -0,0 +1,41 @@ +package main + +import ( + "net/http" + "strings" +) + +func chatSubresourceHandler( + userStore *userStore, + chatStore *chatStore, + messageStore *messageStore, +) http.HandlerFunc { + getChat := getChatHandler(userStore, chatStore) + createMessage := createMessageHandler( + userStore, + chatStore, + messageStore, + ) + listMessages := listMessagesHandler( + userStore, + chatStore, + messageStore, + ) + + return func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/messages") { + switch r.Method { + case http.MethodPost: + createMessage(w, r) + case http.MethodGet: + listMessages(w, r) + default: + createMessage(w, r) + } + + return + } + + getChat(w, r) + } +} diff --git a/src/concurrency_test.go b/src/concurrency_test.go new file mode 100644 index 00000000..388b057d --- /dev/null +++ b/src/concurrency_test.go @@ -0,0 +1,221 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strconv" + "sync" + "testing" +) + +func TestConcurrentMessageCreation(t *testing.T) { + userStore := newUserStore() + chatStore := newChatStore() + messageStore := newMessageStore() + + const clientsCount = 10 + const messagesPerClient = 10 + const expectedMessages = clientsCount * messagesPerClient + + memberIDs := make([]string, 0, clientsCount) + users := make([]User, 0, clientsCount) + + for i := range clientsCount { + user, created := userStore.create( + "user"+strconv.Itoa(i), + "Пользователь "+strconv.Itoa(i), + ) + + if !created { + t.Fatalf("failed to create test user %d", i) + } + + users = append(users, user) + memberIDs = append(memberIDs, user.ID) + } + + chat := chatStore.create( + "Конкурентный чат", + memberIDs, + ) + + mux := http.NewServeMux() + mux.Handle( + "/api/v1/chats/", + chatSubresourceHandler( + userStore, + chatStore, + messageStore, + ), + ) + + server := httptest.NewServer(mux) + defer server.Close() + + client := server.Client() + + var waitGroup sync.WaitGroup + messageIDs := make(chan string, expectedMessages) + errors := make(chan error, expectedMessages) + + for clientIndex := range clientsCount { + waitGroup.Add(1) + + go func(index int) { + defer waitGroup.Done() + + for messageIndex := range messagesPerClient { + body := fmt.Appendf(nil, + `{"text":"client-%d message-%d"}`, + index, + messageIndex, + ) + + request, err := http.NewRequest( + http.MethodPost, + server.URL+"/api/v1/chats/"+chat.ID+"/messages", + bytes.NewReader(body), + ) + if err != nil { + errors <- fmt.Errorf( + "client %d: create request: %w", + index, + err, + ) + continue + } + + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-User-Id", users[index].ID) + + response, err := client.Do(request) + if err != nil { + errors <- fmt.Errorf( + "client %d: send request: %w", + index, + err, + ) + continue + } + + responseBody, readErr := io.ReadAll(response.Body) + response.Body.Close() + + if readErr != nil { + errors <- fmt.Errorf( + "client %d: read response: %w", + index, + readErr, + ) + continue + } + + if response.StatusCode != http.StatusCreated { + errors <- fmt.Errorf( + "client %d: expected status %d, got %d; body: %s", + index, + http.StatusCreated, + response.StatusCode, + string(responseBody), + ) + continue + } + + var message Message + + if err := json.Unmarshal(responseBody, &message); err != nil { + errors <- fmt.Errorf( + "client %d: decode response: %w", + index, + err, + ) + continue + } + + if message.ID == "" { + errors <- fmt.Errorf( + "client %d: response contains empty message ID", + index, + ) + continue + } + + messageIDs <- message.ID + } + }(clientIndex) + } + + waitGroup.Wait() + + close(errors) + close(messageIDs) + + for err := range errors { + t.Error(err) + } + + createdIDs := make(map[string]bool) + + for messageID := range messageIDs { + if createdIDs[messageID] { + t.Fatalf("duplicate message ID returned: %s", messageID) + } + + createdIDs[messageID] = true + } + + if len(createdIDs) != expectedMessages { + t.Fatalf( + "expected %d unique created messages, got %d", + expectedMessages, + len(createdIDs), + ) + } + + // Дополнительно проверяем историю через HTTP API. + request, err := http.NewRequest( + http.MethodGet, + server.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=100", + nil, + ) + if err != nil { + t.Fatalf("create history request: %v", err) + } + + request.Header.Set("X-User-Id", users[0].ID) + + response, err := client.Do(request) + if err != nil { + t.Fatalf("request message history: %v", err) + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + body, _ := io.ReadAll(response.Body) + + t.Fatalf( + "expected history status %d, got %d; body: %s", + http.StatusOK, + response.StatusCode, + string(body), + ) + } + + var page messagePage + + if err := json.NewDecoder(response.Body).Decode(&page); err != nil { + t.Fatalf("decode message history: %v", err) + } + + if len(page.Items) != expectedMessages { + t.Fatalf( + "expected %d messages in history, got %d", + expectedMessages, + len(page.Items), + ) + } +} diff --git a/src/current_user_handler.go b/src/current_user_handler.go new file mode 100644 index 00000000..ef0b6adb --- /dev/null +++ b/src/current_user_handler.go @@ -0,0 +1,58 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +func currentUserHandler(store *userStore) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + + if r.Method != http.MethodGet { + writeError( + w, + http.StatusMethodNotAllowed, + "method_not_allowed", + "method not allowed", + requestID, + ) + return + } + + userID := r.Header.Get("X-User-Id") + + if userID == "" { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "valid X-User-Id header is required", + requestID, + ) + return + } + + user, exists := store.getByID(userID) + if !exists { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "unknown user", + requestID, + ) + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + if err := json.NewEncoder(w).Encode(user); err != nil { + log.Printf("failed to encode user response: %v", err) + return + } + } +} diff --git a/src/main.go b/src/main.go new file mode 100644 index 00000000..699b0608 --- /dev/null +++ b/src/main.go @@ -0,0 +1,159 @@ +package main + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "log" + "net" + "net/http" + "os" + "os/signal" + "syscall" + "time" +) + +type healthResponse struct { + Status string `json:"status"` +} +type apiError struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +type errorResponse struct { + Error apiError `json:"error"` +} + +func newRequestID() string { + bytes := make([]byte, 16) + + if _, err := rand.Read(bytes); err != nil { + return "request-id-generation-failed" + } + + return hex.EncodeToString(bytes) +} + +func writeError(w http.ResponseWriter, status int, code string, message string, requestID string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + + response := errorResponse{ + Error: apiError{ + Code: code, + Message: message, + RequestID: requestID, + }, + } + + if err := json.NewEncoder(w).Encode(response); err != nil { + log.Printf("failed to encode error response: %v", err) + } +} + +func healthHandler(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + + if r.Method != http.MethodGet { + writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "method not allowed", requestID) + return + } + + w.Header().Set("Content-Type", "application/json") + + response := healthResponse{ + Status: "ok", + } + + if err := json.NewEncoder(w).Encode(response); err != nil { + log.Printf("failed to encode health response: %v", err) + } +} + +func serverAddress() string { + host := os.Getenv("APP_HOST") + if host == "" { + host = "0.0.0.0" + } + + port := os.Getenv("APP_PORT") + if port == "" { + port = "8080" + } + + return net.JoinHostPort(host, port) +} + +func main() { + userStore := newUserStore() + chatStore := newChatStore() + messageStore := newMessageStore() + + mux := http.NewServeMux() + + mux.HandleFunc("/health/live", healthHandler) + mux.HandleFunc("/health/ready", healthHandler) + mux.Handle("/api/v1/users", createUserHandler(userStore)) + mux.Handle("/api/v1/users/me", currentUserHandler(userStore)) + mux.Handle( + "/api/v1/chats", + chatCollectionHandler(userStore, chatStore), + ) + mux.Handle( + "/api/v1/chats/", + chatSubresourceHandler( + userStore, + chatStore, + messageStore, + ), + ) + + server := &http.Server{ + Addr: serverAddress(), + Handler: mux, + } + + shutdownContext, stop := signal.NotifyContext( + context.Background(), + os.Interrupt, + syscall.SIGTERM, + ) + defer stop() + + serverErrors := make(chan error, 1) + + go func() { + log.Printf("server is listening on %s", server.Addr) + + if err := server.ListenAndServe(); err != nil && + !errors.Is(err, http.ErrServerClosed) { + serverErrors <- err + } + }() + + select { + case err := <-serverErrors: + log.Printf("server error: %v", err) + + case <-shutdownContext.Done(): + log.Printf("shutdown signal received") + + shutdownDeadline, cancel := context.WithTimeout( + context.Background(), + 10*time.Second, + ) + defer cancel() + + if err := server.Shutdown(shutdownDeadline); err != nil { + log.Printf("graceful shutdown failed: %v", err) + return + } + + log.Printf("server stopped gracefully") + } +} diff --git a/src/message.go b/src/message.go new file mode 100644 index 00000000..c8e0eeaa --- /dev/null +++ b/src/message.go @@ -0,0 +1,111 @@ +package main + +import ( + "sort" + "sync" + "time" + + "github.com/google/uuid" +) + +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 messageStore struct { + mu sync.RWMutex + byChatID map[string][]Message +} + +func newMessageStore() *messageStore { + return &messageStore{ + byChatID: make(map[string][]Message), + } +} + +func (s *messageStore) create( + chatID string, + senderID string, + text string, +) Message { + s.mu.Lock() + defer s.mu.Unlock() + + message := Message{ + ID: uuid.New().String(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: time.Now().UTC(), + } + + messages := s.byChatID[chatID] + insertAt := len(messages) + + if insertAt > 0 && messageLess(message, messages[insertAt-1]) { + insertAt = sort.Search(len(messages), func(index int) bool { + return !messageLess(messages[index], message) + }) + } + + messages = append(messages, Message{}) + copy(messages[insertAt+1:], messages[insertAt:]) + messages[insertAt] = message + s.byChatID[chatID] = messages + + return message +} + +func messageLess(left Message, right Message) bool { + if left.CreatedAt.Equal(right.CreatedAt) { + return left.ID < right.ID + } + + return left.CreatedAt.Before(right.CreatedAt) +} + +func messageAfterCursor(message Message, cursor messageCursor) bool { + return message.CreatedAt.After(cursor.CreatedAt) || + (message.CreatedAt.Equal(cursor.CreatedAt) && message.ID > cursor.MessageID) +} + +func (s *messageStore) listPageByChat( + chatID string, + cursor *messageCursor, + limit int, +) ([]Message, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + + messages := s.byChatID[chatID] + start := 0 + + if cursor != nil { + start = sort.Search(len(messages), func(index int) bool { + return messageAfterCursor(messages[index], *cursor) + }) + } + + remaining := len(messages) - start + pageLength := min(remaining, limit) + page := make([]Message, pageLength) + copy(page, messages[start:start+pageLength]) + + return page, remaining > limit +} + +func (s *messageStore) listByChat(chatID string) []Message { + s.mu.RLock() + defer s.mu.RUnlock() + + messages := s.byChatID[chatID] + + result := make([]Message, len(messages)) + copy(result, messages) + + return result +} diff --git a/src/message_handler.go b/src/message_handler.go new file mode 100644 index 00000000..81c26d89 --- /dev/null +++ b/src/message_handler.go @@ -0,0 +1,179 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" + "strings" + "unicode/utf8" + + "github.com/google/uuid" +) + +type createMessageRequest struct { + Text string `json:"text"` +} + +func createMessageHandler( + userStore *userStore, + chatStore *chatStore, + messageStore *messageStore, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + + if r.Method != http.MethodPost { + writeError( + w, + http.StatusMethodNotAllowed, + "method_not_allowed", + "method not allowed", + requestID, + ) + return + } + + currentUserID := r.Header.Get("X-User-Id") + + if currentUserID == "" { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "valid X-User-Id header is required", + requestID, + ) + return + } + + if _, exists := userStore.getByID(currentUserID); !exists { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "unknown user", + requestID, + ) + return + } + + chatID, ok := messageChatID(r.URL.Path) + if !ok { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid chat id", + requestID, + ) + return + } + + if _, err := uuid.Parse(chatID); err != nil { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid chat id", + requestID, + ) + return + } + + chat, exists := chatStore.getByID(chatID) + + if !exists || !chatStore.isMember(chat, currentUserID) { + writeError( + w, + http.StatusNotFound, + "not_found", + "chat not found", + requestID, + ) + return + } + + if !strings.HasPrefix( + r.Header.Get("Content-Type"), + "application/json", + ) { + writeError( + w, + http.StatusUnsupportedMediaType, + "unsupported_media_type", + "content type must be application/json", + requestID, + ) + return + } + + var request createMessageRequest + + if err := decodeJSONBody(r, &request); err != nil { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid JSON body", + requestID, + ) + return + } + + if strings.TrimSpace(request.Text) == "" { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "text must not be blank", + requestID, + ) + return + } + + if utf8.RuneCountInString(request.Text) > 4000 { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "text is too long", + requestID, + ) + return + } + + message := messageStore.create( + chatID, + currentUserID, + request.Text, + ) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + + if err := json.NewEncoder(w).Encode(message); err != nil { + log.Printf("failed to encode message response: %v", err) + return + } + } +} + +func messageChatID(path string) (string, bool) { + const prefix = "/api/v1/chats/" + const suffix = "/messages" + + if !strings.HasPrefix(path, prefix) || + !strings.HasSuffix(path, suffix) { + return "", false + } + + chatID := strings.TrimPrefix(path, prefix) + chatID = strings.TrimSuffix(chatID, suffix) + + if chatID == "" || strings.Contains(chatID, "/") { + return "", false + } + + return chatID, true +} diff --git a/src/message_handler_test.go b/src/message_handler_test.go new file mode 100644 index 00000000..90864933 --- /dev/null +++ b/src/message_handler_test.go @@ -0,0 +1,291 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func TestCreateMessageBlankText(t *testing.T) { + userStore := newUserStore() + chatStore := newChatStore() + messageStore := newMessageStore() + + user, created := userStore.create("alice", "Алиса") + if !created { + t.Fatal("expected user to be created") + } + + chat := chatStore.create( + "Тестовый чат", + []string{user.ID}, + ) + + handler := createMessageHandler( + userStore, + chatStore, + messageStore, + ) + + request := httptest.NewRequest( + http.MethodPost, + "/api/v1/chats/"+chat.ID+"/messages", + strings.NewReader(`{"text":" \t\n"}`), + ) + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-User-Id", user.ID) + + response := httptest.NewRecorder() + + handler.ServeHTTP(response, request) + + if response.Code != http.StatusBadRequest { + t.Fatalf( + "expected status %d, got %d; body: %s", + http.StatusBadRequest, + response.Code, + response.Body.String(), + ) + } + + if response.Header().Get("X-Request-Id") == "" { + t.Fatal("expected non-empty X-Request-Id header") + } + + if !strings.Contains( + response.Body.String(), + `"code":"invalid_request"`, + ) { + t.Fatalf( + "expected invalid_request error code, got body: %s", + response.Body.String(), + ) + } + + messages := messageStore.listByChat(chat.ID) + + if len(messages) != 0 { + t.Fatalf( + "expected no messages to be stored, got %d", + len(messages), + ) + } +} +func TestCreateMessageFromChatOutsider(t *testing.T) { + userStore := newUserStore() + chatStore := newChatStore() + messageStore := newMessageStore() + + alice, created := userStore.create("alice", "Алиса") + if !created { + t.Fatal("expected Alice to be created") + } + + bob, created := userStore.create("bob", "Боб") + if !created { + t.Fatal("expected Bob to be created") + } + + chat := chatStore.create( + "Чат Алисы", + []string{alice.ID}, + ) + + handler := createMessageHandler( + userStore, + chatStore, + messageStore, + ) + + request := httptest.NewRequest( + http.MethodPost, + "/api/v1/chats/"+chat.ID+"/messages", + strings.NewReader(`{"text":"Сообщение чужому чату"}`), + ) + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-User-Id", bob.ID) + + response := httptest.NewRecorder() + + handler.ServeHTTP(response, request) + + if response.Code != http.StatusNotFound { + t.Fatalf( + "expected status %d, got %d; body: %s", + http.StatusNotFound, + response.Code, + response.Body.String(), + ) + } + + if response.Header().Get("X-Request-Id") == "" { + t.Fatal("expected non-empty X-Request-Id header") + } + + if !strings.Contains( + response.Body.String(), + `"code":"not_found"`, + ) { + t.Fatalf( + "expected not_found error code, got body: %s", + response.Body.String(), + ) + } + + messages := messageStore.listByChat(chat.ID) + + if len(messages) != 0 { + t.Fatalf( + "expected no messages to be stored, got %d", + len(messages), + ) + } +} +func TestListMessagesPagination(t *testing.T) { + userStore := newUserStore() + chatStore := newChatStore() + messageStore := newMessageStore() + + user, created := userStore.create("alice", "Алиса") + if !created { + t.Fatal("expected user to be created") + } + + chat := chatStore.create( + "Тестовый чат", + []string{user.ID}, + ) + + first := messageStore.create(chat.ID, user.ID, "Первое сообщение") + second := messageStore.create(chat.ID, user.ID, "Второе сообщение") + third := messageStore.create(chat.ID, user.ID, "Третье сообщение") + + expectedIDs := map[string]bool{ + first.ID: true, + second.ID: true, + third.ID: true, + } + + handler := listMessagesHandler( + userStore, + chatStore, + messageStore, + ) + + // Запрашиваем только два сообщения из трёх. + firstRequest := httptest.NewRequest( + http.MethodGet, + "/api/v1/chats/"+chat.ID+"/messages?limit=2", + nil, + ) + firstRequest.Header.Set("X-User-Id", user.ID) + + firstResponse := httptest.NewRecorder() + + handler.ServeHTTP(firstResponse, firstRequest) + + if firstResponse.Code != http.StatusOK { + t.Fatalf( + "expected first page status %d, got %d; body: %s", + http.StatusOK, + firstResponse.Code, + firstResponse.Body.String(), + ) + } + + var firstPage messagePage + + if err := json.NewDecoder(firstResponse.Body).Decode(&firstPage); err != nil { + t.Fatalf("failed to decode first page: %v", err) + } + + if len(firstPage.Items) != 2 { + t.Fatalf( + "expected 2 messages on first page, got %d", + len(firstPage.Items), + ) + } + + if firstPage.NextCursor == nil || *firstPage.NextCursor == "" { + t.Fatal("expected non-empty next cursor on first page") + } + + // Проверяем, что сообщения на первой странице уникальны + // и принадлежат исходному набору. + seenIDs := make(map[string]bool) + + for _, message := range firstPage.Items { + if !expectedIDs[message.ID] { + t.Fatalf("unexpected message ID on first page: %s", message.ID) + } + + if seenIDs[message.ID] { + t.Fatalf("duplicate message on first page: %s", message.ID) + } + + seenIDs[message.ID] = true + } + + // Используем cursor первой страницы для получения второй. + secondRequest := httptest.NewRequest( + http.MethodGet, + "/api/v1/chats/"+chat.ID+"/messages?limit=2&cursor="+ + url.QueryEscape(*firstPage.NextCursor), + nil, + ) + secondRequest.Header.Set("X-User-Id", user.ID) + + secondResponse := httptest.NewRecorder() + + handler.ServeHTTP(secondResponse, secondRequest) + + if secondResponse.Code != http.StatusOK { + t.Fatalf( + "expected second page status %d, got %d; body: %s", + http.StatusOK, + secondResponse.Code, + secondResponse.Body.String(), + ) + } + + var secondPage messagePage + + if err := json.NewDecoder(secondResponse.Body).Decode(&secondPage); err != nil { + t.Fatalf("failed to decode second page: %v", err) + } + + if len(secondPage.Items) != 1 { + t.Fatalf( + "expected 1 message on second page, got %d", + len(secondPage.Items), + ) + } + + if secondPage.NextCursor != nil { + t.Fatalf("expected second page to be final, got cursor %q", *secondPage.NextCursor) + } + + // Проверяем, что вторая страница не повторяет первую. + for _, message := range secondPage.Items { + if seenIDs[message.ID] { + t.Fatalf("message repeated on second page: %s", message.ID) + } + + if !expectedIDs[message.ID] { + t.Fatalf("unexpected message ID on second page: %s", message.ID) + } + + seenIDs[message.ID] = true + } + + if len(seenIDs) != len(expectedIDs) { + t.Fatalf( + "pagination lost messages: expected %d unique messages, got %d", + len(expectedIDs), + len(seenIDs), + ) + } +} diff --git a/src/message_list_handler.go b/src/message_list_handler.go new file mode 100644 index 00000000..f71b8b9a --- /dev/null +++ b/src/message_list_handler.go @@ -0,0 +1,224 @@ +package main + +import ( + "encoding/base64" + "encoding/json" + "net/http" + "strconv" + "time" +) + +type messagePage struct { + Items []Message `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type messageCursor struct { + ChatID string `json:"chat_id"` + CreatedAt time.Time `json:"created_at"` + MessageID string `json:"message_id"` +} + +func encodeMessageCursor(cursor messageCursor) (string, error) { + data, err := json.Marshal(cursor) + if err != nil { + return "", err + } + + return base64.RawURLEncoding.EncodeToString(data), nil +} + +func decodeMessageCursor(value string) (messageCursor, error) { + data, err := base64.RawURLEncoding.DecodeString(value) + if err != nil { + return messageCursor{}, err + } + + var cursor messageCursor + + if err := json.Unmarshal(data, &cursor); err != nil { + return messageCursor{}, err + } + + if cursor.ChatID == "" || + cursor.MessageID == "" || + cursor.CreatedAt.IsZero() { + return messageCursor{}, strconv.ErrSyntax + } + + return cursor, nil +} + +func listMessagesHandler( + userStore *userStore, + chatStore *chatStore, + messageStore *messageStore, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + + if r.Method != http.MethodGet { + writeError( + w, + http.StatusMethodNotAllowed, + "method_not_allowed", + "method not allowed", + requestID, + ) + return + } + + currentUserID := r.Header.Get("X-User-Id") + + if currentUserID == "" { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "valid X-User-Id header is required", + requestID, + ) + return + } + + if _, exists := userStore.getByID(currentUserID); !exists { + writeError( + w, + http.StatusUnauthorized, + "unauthorized", + "unknown user", + requestID, + ) + return + } + + chatID, ok := messageChatID(r.URL.Path) + if !ok { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid chat id", + requestID, + ) + return + } + + chat, exists := chatStore.getByID(chatID) + + if !exists || !chatStore.isMember(chat, currentUserID) { + writeError( + w, + http.StatusNotFound, + "not_found", + "chat not found", + requestID, + ) + return + } + + limit := 50 + + if values, exists := r.URL.Query()["limit"]; exists { + if len(values) != 1 || values[0] == "" { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid limit", + requestID, + ) + return + } + + parsedLimit, err := strconv.Atoi(values[0]) + if err != nil || parsedLimit < 1 || parsedLimit > 100 { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "limit must be between 1 and 100", + requestID, + ) + return + } + + limit = parsedLimit + } + + var cursor *messageCursor + + if values, exists := r.URL.Query()["cursor"]; exists { + if len(values) != 1 || values[0] == "" { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid cursor", + requestID, + ) + return + } + + decoded, err := decodeMessageCursor(values[0]) + if err != nil || decoded.ChatID != chatID { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid cursor", + requestID, + ) + return + } + + cursor = &decoded + } + + pageItems, hasMore := messageStore.listPageByChat( + chatID, + cursor, + limit, + ) + + page := messagePage{ + Items: pageItems, + NextCursor: nil, + } + + if hasMore { + last := pageItems[len(pageItems)-1] + + nextCursor, err := encodeMessageCursor(messageCursor{ + ChatID: chatID, + CreatedAt: last.CreatedAt, + MessageID: last.ID, + }) + + if err != nil { + writeError( + w, + http.StatusInternalServerError, + "internal_error", + "internal server error", + requestID, + ) + return + } + + page.NextCursor = &nextCursor + } + + if page.Items == nil { + page.Items = make([]Message, 0) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + if err := json.NewEncoder(w).Encode(page); err != nil { + return + } + } +} diff --git a/src/message_store_test.go b/src/message_store_test.go new file mode 100644 index 00000000..372a746e --- /dev/null +++ b/src/message_store_test.go @@ -0,0 +1,64 @@ +package main + +import ( + "testing" + "time" +) + +func TestMessageLessUsesIDForEqualTimestamps(t *testing.T) { + createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC) + first := Message{ID: "a", CreatedAt: createdAt} + second := Message{ID: "b", CreatedAt: createdAt} + + if !messageLess(first, second) { + t.Fatal("expected the smaller ID to sort first for equal timestamps") + } + + if messageLess(second, first) { + t.Fatal("expected the larger ID to sort last for equal timestamps") + } +} + +func TestListPageByChatUsesCursorAndLimit(t *testing.T) { + createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC) + store := newMessageStore() + store.byChatID["chat-1"] = []Message{ + {ID: "a", ChatID: "chat-1", CreatedAt: createdAt}, + {ID: "b", ChatID: "chat-1", CreatedAt: createdAt}, + {ID: "c", ChatID: "chat-1", CreatedAt: createdAt.Add(time.Second)}, + {ID: "d", ChatID: "chat-1", CreatedAt: createdAt.Add(2 * time.Second)}, + } + + firstPage, hasMore := store.listPageByChat("chat-1", nil, 2) + if !hasMore { + t.Fatal("expected another page") + } + if len(firstPage) != 2 || firstPage[0].ID != "a" || firstPage[1].ID != "b" { + t.Fatalf("unexpected first page: %#v", firstPage) + } + + cursor := messageCursor{ + ChatID: "chat-1", + CreatedAt: firstPage[1].CreatedAt, + MessageID: firstPage[1].ID, + } + secondPage, hasMore := store.listPageByChat("chat-1", &cursor, 2) + if hasMore { + t.Fatal("did not expect another page") + } + if len(secondPage) != 2 || secondPage[0].ID != "c" || secondPage[1].ID != "d" { + t.Fatalf("unexpected second page: %#v", secondPage) + } +} + +func TestListPageByChatReturnsNonNilEmptyPage(t *testing.T) { + store := newMessageStore() + + page, hasMore := store.listPageByChat("missing", nil, 100) + if page == nil { + t.Fatal("expected a non-nil empty page") + } + if len(page) != 0 || hasMore { + t.Fatalf("unexpected empty page result: page=%#v hasMore=%v", page, hasMore) + } +} diff --git a/src/user.go b/src/user.go new file mode 100644 index 00000000..f9ec7f26 --- /dev/null +++ b/src/user.go @@ -0,0 +1,58 @@ +package main + +import ( + "sync" + "time" + + "github.com/google/uuid" +) + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +type userStore struct { + mu sync.RWMutex + byID map[string]User + byUsername map[string]string +} + +func newUserStore() *userStore { + return &userStore{ + byID: make(map[string]User), + byUsername: make(map[string]string), + } +} + +func (s *userStore) create(username string, displayName string) (User, bool) { + s.mu.Lock() + defer s.mu.Unlock() + + if _, exists := s.byUsername[username]; exists { + return User{}, false + } + + user := User{ + ID: uuid.New().String(), + Username: username, + DisplayName: displayName, + CreatedAt: time.Now().UTC(), + } + + s.byID[user.ID] = user + s.byUsername[user.Username] = user.ID + + return user, true +} + +func (s *userStore) getByID(id string) (User, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + + user, exists := s.byID[id] + + return user, exists +} diff --git a/src/user_handler.go b/src/user_handler.go new file mode 100644 index 00000000..ec72c3e9 --- /dev/null +++ b/src/user_handler.go @@ -0,0 +1,133 @@ +package main + +import ( + "encoding/json" + "io" + "log" + "net/http" + "regexp" + "strings" + "unicode/utf8" +) + +type createUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` +} + +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +func decodeJSONBody(r *http.Request, destination any) error { + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + + if err := decoder.Decode(destination); err != nil { + return err + } + + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + return err + } + + return nil +} + +func createUserHandler(store *userStore) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + + if r.Method != http.MethodPost { + writeError( + w, + http.StatusMethodNotAllowed, + "method_not_allowed", + "method not allowed", + requestID, + ) + return + } + + if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { + writeError( + w, + http.StatusUnsupportedMediaType, + "unsupported_media_type", + "content type must be application/json", + requestID, + ) + return + } + + var request createUserRequest + + if err := decodeJSONBody(r, &request); err != nil { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "invalid JSON body", + requestID, + ) + return + } + + if !usernamePattern.MatchString(request.Username) { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "username must contain 3-32 lowercase latin letters, digits or underscores", + requestID, + ) + return + } + + if strings.TrimSpace(request.DisplayName) == "" { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "display_name must not be blank", + requestID, + ) + return + } + + if utf8.RuneCountInString(request.DisplayName) > 100 { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "display_name is too long", + requestID, + ) + return + } + + user, created := store.create( + request.Username, + request.DisplayName, + ) + + if !created { + writeError( + w, + http.StatusConflict, + "conflict", + "username is already taken", + requestID, + ) + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + + if err := json.NewEncoder(w).Encode(user); err != nil { + log.Printf("failed to encode user response: %v", err) + return + } + } +} diff --git a/src/user_handler_test.go b/src/user_handler_test.go new file mode 100644 index 00000000..d8c1277f --- /dev/null +++ b/src/user_handler_test.go @@ -0,0 +1,132 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestCreateUserInvalidJSON(t *testing.T) { + store := newUserStore() + handler := createUserHandler(store) + + request := httptest.NewRequest( + http.MethodPost, + "/api/v1/users", + strings.NewReader(`{"username":`), + ) + request.Header.Set("Content-Type", "application/json") + + response := httptest.NewRecorder() + + handler.ServeHTTP(response, request) + + if response.Code != http.StatusBadRequest { + t.Fatalf( + "expected status %d, got %d; body: %s", + http.StatusBadRequest, + response.Code, + response.Body.String(), + ) + } + + if response.Header().Get("Content-Type") != "application/json" { + t.Fatalf( + "expected Content-Type application/json, got %q", + response.Header().Get("Content-Type"), + ) + } + + if response.Header().Get("X-Request-Id") == "" { + t.Fatal("expected non-empty X-Request-Id header") + } + + body := response.Body.String() + + if !strings.Contains(body, `"code":"invalid_request"`) { + t.Fatalf( + "expected invalid_request error code, got body: %s", + body, + ) + } + + if !strings.Contains(body, "request_id") { + t.Fatalf( + "expected request_id in error body, got body: %s", + body, + ) + } +} + +func TestCreateUserDuplicateUsername(t *testing.T) { + store := newUserStore() + handler := createUserHandler(store) + + firstRequest := httptest.NewRequest( + http.MethodPost, + "/api/v1/users", + strings.NewReader(`{ + "username": "alice", + "display_name": "Алиса" + }`), + ) + firstRequest.Header.Set("Content-Type", "application/json") + + firstResponse := httptest.NewRecorder() + + handler.ServeHTTP(firstResponse, firstRequest) + + if firstResponse.Code != http.StatusCreated { + t.Fatalf( + "expected first request status %d, got %d; body: %s", + http.StatusCreated, + firstResponse.Code, + firstResponse.Body.String(), + ) + } + + secondRequest := httptest.NewRequest( + http.MethodPost, + "/api/v1/users", + strings.NewReader(`{ + "username": "alice", + "display_name": "Другая Алиса" + }`), + ) + secondRequest.Header.Set("Content-Type", "application/json") + + secondResponse := httptest.NewRecorder() + + handler.ServeHTTP(secondResponse, secondRequest) + + if secondResponse.Code != http.StatusConflict { + t.Fatalf( + "expected duplicate username status %d, got %d; body: %s", + http.StatusConflict, + secondResponse.Code, + secondResponse.Body.String(), + ) + } + + if secondResponse.Header().Get("X-Request-Id") == "" { + t.Fatal("expected non-empty X-Request-Id header") + } + + if !strings.Contains( + secondResponse.Body.String(), + `"code":"conflict"`, + ) { + t.Fatalf( + "expected conflict error code, got body: %s", + secondResponse.Body.String(), + ) + } + + if len(store.byID) != 1 { + t.Fatalf( + "expected exactly one user in store, got %d", + len(store.byID), + ) + } +} -- 2.54.0 From c3840181f1419335f0aee2951189619c27486113 Mon Sep 17 00:00:00 2001 From: Dima Date: Wed, 23 Sep 2026 21:38:55 +0300 Subject: [PATCH 2/9] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B8=20API=20=D0=BD=D0=B0=20PostgreSQL=20=D0=B8=20?= =?UTF-8?q?=D1=81=D0=BE=D1=85=D1=80=D0=B0=D0=BD=D1=8F=D0=B5=D0=BC=D1=8B?= =?UTF-8?q?=D0=B5=20Bearer-=D1=81=D0=B5=D1=81=D1=81=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 14 +- go.sum | 28 ++++ scripts/restart.sh | 5 + src/chat.go | 128 ++++++++++----- src/chat_get_handler.go | 10 +- src/chat_handler.go | 20 ++- src/chat_list_handler.go | 43 +---- src/concurrency_test.go | 221 ------------------------- src/current_user_handler.go | 8 +- src/database.go | 102 ++++++++++++ src/main.go | 49 +++++- src/message.go | 94 +++++------ src/message_handler.go | 17 +- src/message_handler_test.go | 291 --------------------------------- src/message_list_handler.go | 17 +- src/message_store_test.go | 64 -------- src/migrations/001_initial.sql | 33 ++++ src/security_test.go | 54 ++++++ src/session.go | 157 ++++++++++++++++++ src/user.go | 70 +++++--- src/user_handler.go | 28 +++- src/user_handler_test.go | 132 --------------- 22 files changed, 682 insertions(+), 903 deletions(-) create mode 100755 scripts/restart.sh delete mode 100644 src/concurrency_test.go create mode 100644 src/database.go delete mode 100644 src/message_handler_test.go delete mode 100644 src/message_store_test.go create mode 100644 src/migrations/001_initial.sql create mode 100644 src/security_test.go create mode 100644 src/session.go delete mode 100644 src/user_handler_test.go diff --git a/go.mod b/go.mod index e6db6494..99bf2424 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,16 @@ module messenger go 1.22.2 -require github.com/google/uuid v1.6.0 +require ( + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.5.5 + golang.org/x/crypto v0.22.0 +) + +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jackc/puddle/v2 v2.2.1 // indirect + golang.org/x/sync v0.1.0 // indirect + golang.org/x/text v0.14.0 // indirect +) diff --git a/go.sum b/go.sum index 7790d7c3..99d44c20 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,30 @@ +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/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-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw= +github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A= +github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= +github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +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.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +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/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..a29ccdc5 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,5 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +docker compose --env-file .env restart db api >/dev/null +docker compose --env-file .env up -d --wait >/dev/null diff --git a/src/chat.go b/src/chat.go index 7ef1833c..d7601788 100644 --- a/src/chat.go +++ b/src/chat.go @@ -1,10 +1,12 @@ package main import ( - "sync" + "context" + "errors" "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" ) type Chat struct { @@ -15,43 +17,72 @@ type Chat struct { } type chatStore struct { - mu sync.RWMutex - byID map[string]Chat + db *pgxpool.Pool } -func newChatStore() *chatStore { - return &chatStore{ - byID: make(map[string]Chat), - } +func newChatStore(db *pgxpool.Pool) *chatStore { + return &chatStore{db: db} } -func (s *chatStore) create(title string, memberIDs []string) Chat { - s.mu.Lock() - defer s.mu.Unlock() +var errUnknownMember = errors.New("unknown member") - // Делаем копию, чтобы вызывающий код не мог изменить - // список участников после сохранения чата. +func (s *chatStore) create(ctx context.Context, title string, memberIDs []string) (Chat, error) { membersCopy := append([]string(nil), memberIDs...) - chat := Chat{ ID: uuid.New().String(), Title: title, MemberIDs: membersCopy, - CreatedAt: time.Now().UTC(), + CreatedAt: time.Now().UTC().Truncate(time.Microsecond), } - s.byID[chat.ID] = chat - - return chat + tx, err := s.db.Begin(ctx) + if err != nil { + return Chat{}, err + } + defer tx.Rollback(ctx) + for _, id := range membersCopy { + var exists bool + if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM users WHERE id=$1)", id).Scan(&exists); err != nil { + return Chat{}, err + } + if !exists { + return Chat{}, errUnknownMember + } + } + if _, err = tx.Exec(ctx, "INSERT INTO chats(id,title,created_at) VALUES($1,$2,$3)", chat.ID, title, chat.CreatedAt); err != nil { + return Chat{}, err + } + for _, id := range membersCopy { + if _, err = tx.Exec(ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", chat.ID, id); err != nil { + return Chat{}, err + } + } + if err = tx.Commit(ctx); err != nil { + return Chat{}, err + } + return chat, nil } -func (s *chatStore) getByID(id string) (Chat, bool) { - s.mu.RLock() - defer s.mu.RUnlock() - - chat, exists := s.byID[id] - - return chat, exists +func (s *chatStore) getByID(ctx context.Context, id string) (Chat, error) { + var chat Chat + err := s.db.QueryRow(ctx, "SELECT id,title,created_at FROM chats WHERE id=$1", id).Scan(&chat.ID, &chat.Title, &chat.CreatedAt) + if err != nil { + return Chat{}, err + } + rows, err := s.db.Query(ctx, "SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id", id) + if err != nil { + return Chat{}, err + } + defer rows.Close() + chat.MemberIDs = []string{} + for rows.Next() { + var member string + if err = rows.Scan(&member); err != nil { + return Chat{}, err + } + chat.MemberIDs = append(chat.MemberIDs, member) + } + return chat, rows.Err() } func (s *chatStore) isMember(chat Chat, userID string) bool { @@ -64,20 +95,39 @@ func (s *chatStore) isMember(chat Chat, userID string) bool { return false } -func (s *chatStore) listForUser(userID string) []Chat { - s.mu.RLock() - defer s.mu.RUnlock() - - chats := make([]Chat, 0) - - for _, chat := range s.byID { - if !s.isMember(chat, userID) { - continue - } - - chat.MemberIDs = append([]string(nil), chat.MemberIDs...) - chats = append(chats, chat) +func (s *chatStore) listPageForUser(ctx context.Context, userID string, cursor *chatCursor, limit int) ([]Chat, bool, error) { + afterTime := time.Time{} + afterID := "00000000-0000-0000-0000-000000000000" + if cursor != nil { + afterTime = cursor.CreatedAt + afterID = cursor.ChatID } - - return chats + rows, err := s.db.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=$1 AND (c.created_at,c.id)>($2,$3::uuid) ORDER BY c.created_at,c.id LIMIT $4`, userID, afterTime, afterID, limit+1) + if err != nil { + return nil, false, err + } + defer rows.Close() + chats := []Chat{} + for rows.Next() { + var c Chat + if err = rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil { + return nil, false, err + } + chats = append(chats, c) + } + if err = rows.Err(); err != nil { + return nil, false, err + } + more := len(chats) > limit + if more { + chats = chats[:limit] + } + for i := range chats { + chat, err := s.getByID(ctx, chats[i].ID) + if err != nil { + return nil, false, err + } + chats[i] = chat + } + return chats, more, nil } diff --git a/src/chat_get_handler.go b/src/chat_get_handler.go index 3710ffa2..3d504890 100644 --- a/src/chat_get_handler.go +++ b/src/chat_get_handler.go @@ -28,20 +28,20 @@ func getChatHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -79,9 +79,9 @@ func getChatHandler( return } - chat, exists := chatStore.getByID(chatID) + chat, err := chatStore.getByID(r.Context(), chatID) - if !exists || !chatStore.isMember(chat, currentUserID) { + if err != nil || !chatStore.isMember(chat, currentUserID) { // Для неизвестного и чужого чата используется одинаковый 404. // Это не раскрывает постороннему пользователю наличие чата. writeError( diff --git a/src/chat_handler.go b/src/chat_handler.go index 5842cba5..7460c89c 100644 --- a/src/chat_handler.go +++ b/src/chat_handler.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "errors" "log" "net/http" "strings" @@ -34,20 +35,20 @@ func createChatHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -145,7 +146,7 @@ func createChatHandler( seenMembers[memberID] = struct{}{} - if _, exists := userStore.getByID(memberID); !exists { + if _, err := userStore.getByID(r.Context(), memberID); err != nil { writeError( w, http.StatusBadRequest, @@ -168,10 +169,19 @@ func createChatHandler( return } - chat := chatStore.create( + chat, err := chatStore.create( + r.Context(), request.Title, request.MemberIDs, ) + if errors.Is(err, errUnknownMember) { + writeError(w, 400, "invalid_request", "all members must be existing users", requestID) + return + } + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) diff --git a/src/chat_list_handler.go b/src/chat_list_handler.go index 6d036828..fafe5915 100644 --- a/src/chat_list_handler.go +++ b/src/chat_list_handler.go @@ -4,7 +4,6 @@ import ( "encoding/base64" "encoding/json" "net/http" - "sort" "strconv" "time" ) @@ -69,20 +68,20 @@ func listChatsHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -151,36 +150,10 @@ func listChatsHandler( cursor = &decoded } - chats := chatStore.listForUser(currentUserID) - - sort.Slice(chats, func(i, j int) bool { - if chats[i].CreatedAt.Equal(chats[j].CreatedAt) { - return chats[i].ID < chats[j].ID - } - - return chats[i].CreatedAt.Before(chats[j].CreatedAt) - }) - - if cursor != nil { - filtered := make([]Chat, 0, len(chats)) - - for _, chat := range chats { - isAfterCursor := chat.CreatedAt.After(cursor.CreatedAt) || - (chat.CreatedAt.Equal(cursor.CreatedAt) && - chat.ID > cursor.ChatID) - - if isAfterCursor { - filtered = append(filtered, chat) - } - } - - chats = filtered - } - - pageItems := chats - - if len(pageItems) > limit { - pageItems = pageItems[:limit] + pageItems, hasMore, err := chatStore.listPageForUser(r.Context(), currentUserID, cursor, limit) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return } page := chatPage{ @@ -188,7 +161,7 @@ func listChatsHandler( NextCursor: nil, } - if len(chats) > limit { + if hasMore { last := pageItems[len(pageItems)-1] nextCursor, err := encodeChatCursor(chatCursor{ diff --git a/src/concurrency_test.go b/src/concurrency_test.go deleted file mode 100644 index 388b057d..00000000 --- a/src/concurrency_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package main - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "strconv" - "sync" - "testing" -) - -func TestConcurrentMessageCreation(t *testing.T) { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() - - const clientsCount = 10 - const messagesPerClient = 10 - const expectedMessages = clientsCount * messagesPerClient - - memberIDs := make([]string, 0, clientsCount) - users := make([]User, 0, clientsCount) - - for i := range clientsCount { - user, created := userStore.create( - "user"+strconv.Itoa(i), - "Пользователь "+strconv.Itoa(i), - ) - - if !created { - t.Fatalf("failed to create test user %d", i) - } - - users = append(users, user) - memberIDs = append(memberIDs, user.ID) - } - - chat := chatStore.create( - "Конкурентный чат", - memberIDs, - ) - - mux := http.NewServeMux() - mux.Handle( - "/api/v1/chats/", - chatSubresourceHandler( - userStore, - chatStore, - messageStore, - ), - ) - - server := httptest.NewServer(mux) - defer server.Close() - - client := server.Client() - - var waitGroup sync.WaitGroup - messageIDs := make(chan string, expectedMessages) - errors := make(chan error, expectedMessages) - - for clientIndex := range clientsCount { - waitGroup.Add(1) - - go func(index int) { - defer waitGroup.Done() - - for messageIndex := range messagesPerClient { - body := fmt.Appendf(nil, - `{"text":"client-%d message-%d"}`, - index, - messageIndex, - ) - - request, err := http.NewRequest( - http.MethodPost, - server.URL+"/api/v1/chats/"+chat.ID+"/messages", - bytes.NewReader(body), - ) - if err != nil { - errors <- fmt.Errorf( - "client %d: create request: %w", - index, - err, - ) - continue - } - - request.Header.Set("Content-Type", "application/json") - request.Header.Set("X-User-Id", users[index].ID) - - response, err := client.Do(request) - if err != nil { - errors <- fmt.Errorf( - "client %d: send request: %w", - index, - err, - ) - continue - } - - responseBody, readErr := io.ReadAll(response.Body) - response.Body.Close() - - if readErr != nil { - errors <- fmt.Errorf( - "client %d: read response: %w", - index, - readErr, - ) - continue - } - - if response.StatusCode != http.StatusCreated { - errors <- fmt.Errorf( - "client %d: expected status %d, got %d; body: %s", - index, - http.StatusCreated, - response.StatusCode, - string(responseBody), - ) - continue - } - - var message Message - - if err := json.Unmarshal(responseBody, &message); err != nil { - errors <- fmt.Errorf( - "client %d: decode response: %w", - index, - err, - ) - continue - } - - if message.ID == "" { - errors <- fmt.Errorf( - "client %d: response contains empty message ID", - index, - ) - continue - } - - messageIDs <- message.ID - } - }(clientIndex) - } - - waitGroup.Wait() - - close(errors) - close(messageIDs) - - for err := range errors { - t.Error(err) - } - - createdIDs := make(map[string]bool) - - for messageID := range messageIDs { - if createdIDs[messageID] { - t.Fatalf("duplicate message ID returned: %s", messageID) - } - - createdIDs[messageID] = true - } - - if len(createdIDs) != expectedMessages { - t.Fatalf( - "expected %d unique created messages, got %d", - expectedMessages, - len(createdIDs), - ) - } - - // Дополнительно проверяем историю через HTTP API. - request, err := http.NewRequest( - http.MethodGet, - server.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=100", - nil, - ) - if err != nil { - t.Fatalf("create history request: %v", err) - } - - request.Header.Set("X-User-Id", users[0].ID) - - response, err := client.Do(request) - if err != nil { - t.Fatalf("request message history: %v", err) - } - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - body, _ := io.ReadAll(response.Body) - - t.Fatalf( - "expected history status %d, got %d; body: %s", - http.StatusOK, - response.StatusCode, - string(body), - ) - } - - var page messagePage - - if err := json.NewDecoder(response.Body).Decode(&page); err != nil { - t.Fatalf("decode message history: %v", err) - } - - if len(page.Items) != expectedMessages { - t.Fatalf( - "expected %d messages in history, got %d", - expectedMessages, - len(page.Items), - ) - } -} diff --git a/src/current_user_handler.go b/src/current_user_handler.go index ef0b6adb..f96f74e8 100644 --- a/src/current_user_handler.go +++ b/src/current_user_handler.go @@ -22,21 +22,21 @@ func currentUserHandler(store *userStore) http.HandlerFunc { return } - userID := r.Header.Get("X-User-Id") + userID := currentUserID(r) if userID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - user, exists := store.getByID(userID) - if !exists { + user, err := store.getByID(r.Context(), userID) + if err != nil { writeError( w, http.StatusUnauthorized, diff --git a/src/database.go b/src/database.go new file mode 100644 index 00000000..cd288127 --- /dev/null +++ b/src/database.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "embed" + "errors" + "fmt" + "os" + "sort" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" +) + +//go:embed migrations/*.sql +var migrationFiles embed.FS + +func databaseURL() (string, error) { + if path := os.Getenv("DATABASE_URL_FILE"); path != "" { + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + return strings.TrimSpace(string(data)), nil + } + if url := os.Getenv("DATABASE_URL"); url != "" { + return url, nil + } + return "", errors.New("DATABASE_URL_FILE or DATABASE_URL is required") +} + +func openDatabase(ctx context.Context) (*pgxpool.Pool, error) { + url, err := databaseURL() + if err != nil { + return nil, err + } + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + return nil, err + } + cfg.MaxConns = 10 + cfg.ConnConfig.ConnectTimeout = 5 * time.Second + db, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, err + } + if err = db.Ping(ctx); err != nil { + db.Close() + return nil, err + } + if err = applyMigrations(ctx, db); err != nil { + db.Close() + return nil, err + } + return db, nil +} + +func applyMigrations(ctx context.Context, db *pgxpool.Pool) error { + files, err := migrationFiles.ReadDir("migrations") + if err != nil { + return err + } + sort.Slice(files, func(i, j int) bool { return files[i].Name() < files[j].Name() }) + tx, err := db.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(20426002)"); err != nil { + return err + } + if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)"); err != nil { + return err + } + for _, file := range files { + var exists bool + if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)", file.Name()).Scan(&exists); err != nil { + return err + } + if exists { + continue + } + sql, readErr := migrationFiles.ReadFile("migrations/" + file.Name()) + if readErr != nil { + return readErr + } + if _, err = tx.Exec(ctx, string(sql)); err != nil { + return fmt.Errorf("migration %s: %w", file.Name(), err) + } + if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES($1)", file.Name()); err != nil { + return err + } + } + return tx.Commit(ctx) +} + +func uniqueViolation(err error) bool { + var pgerr *pgconn.PgError + return errors.As(err, &pgerr) && pgerr.Code == "23505" +} diff --git a/src/main.go b/src/main.go index 699b0608..e0d512cc 100644 --- a/src/main.go +++ b/src/main.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "encoding/json" "errors" + "github.com/jackc/pgx/v5/pgxpool" "log" "net" "net/http" @@ -75,6 +76,25 @@ func healthHandler(w http.ResponseWriter, r *http.Request) { } } +func readyHandler(db *pgxpool.Pool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodGet { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + if err := db.Ping(ctx); err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(healthResponse{"ok"}) + } +} + func serverAddress() string { host := os.Getenv("APP_HOST") if host == "" { @@ -90,27 +110,40 @@ func serverAddress() string { } func main() { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + db, err := openDatabase(ctx) + cancel() + if err != nil { + log.Fatalf("database initialization failed: %v", err) + } + defer db.Close() + userStore := newUserStore(db) + chatStore := newChatStore(db) + messageStore := newMessageStore(db) + sessions, err := newSessionStore(db) + if err != nil { + log.Fatal(err) + } mux := http.NewServeMux() mux.HandleFunc("/health/live", healthHandler) - mux.HandleFunc("/health/ready", healthHandler) + mux.HandleFunc("/health/ready", readyHandler(db)) mux.Handle("/api/v1/users", createUserHandler(userStore)) - mux.Handle("/api/v1/users/me", currentUserHandler(userStore)) + mux.Handle("/api/v1/auth/sessions", sessionHandler(userStore, sessions)) + mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions))) + mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(userStore))) mux.Handle( "/api/v1/chats", - chatCollectionHandler(userStore, chatStore), + authRequired(sessions, chatCollectionHandler(userStore, chatStore)), ) mux.Handle( "/api/v1/chats/", - chatSubresourceHandler( + authRequired(sessions, chatSubresourceHandler( userStore, chatStore, messageStore, - ), + )), ) server := &http.Server{ diff --git a/src/message.go b/src/message.go index c8e0eeaa..ac812bb9 100644 --- a/src/message.go +++ b/src/message.go @@ -1,11 +1,11 @@ package main import ( - "sort" - "sync" + "context" "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" ) type Message struct { @@ -17,47 +17,29 @@ type Message struct { } type messageStore struct { - mu sync.RWMutex - byChatID map[string][]Message + db *pgxpool.Pool } -func newMessageStore() *messageStore { - return &messageStore{ - byChatID: make(map[string][]Message), - } +func newMessageStore(db *pgxpool.Pool) *messageStore { + return &messageStore{db: db} } func (s *messageStore) create( + ctx context.Context, chatID string, senderID string, text string, -) Message { - s.mu.Lock() - defer s.mu.Unlock() - +) (Message, error) { message := Message{ ID: uuid.New().String(), ChatID: chatID, SenderID: senderID, Text: text, - CreatedAt: time.Now().UTC(), + CreatedAt: time.Now().UTC().Truncate(time.Microsecond), } - messages := s.byChatID[chatID] - insertAt := len(messages) - - if insertAt > 0 && messageLess(message, messages[insertAt-1]) { - insertAt = sort.Search(len(messages), func(index int) bool { - return !messageLess(messages[index], message) - }) - } - - messages = append(messages, Message{}) - copy(messages[insertAt+1:], messages[insertAt:]) - messages[insertAt] = message - s.byChatID[chatID] = messages - - return message + _, err := s.db.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt) + return message, err } func messageLess(left Message, right Message) bool { @@ -74,38 +56,36 @@ func messageAfterCursor(message Message, cursor messageCursor) bool { } func (s *messageStore) listPageByChat( + ctx context.Context, chatID string, cursor *messageCursor, limit int, -) ([]Message, bool) { - s.mu.RLock() - defer s.mu.RUnlock() - - messages := s.byChatID[chatID] - start := 0 - +) ([]Message, bool, error) { + afterTime := time.Time{} + afterID := "00000000-0000-0000-0000-000000000000" if cursor != nil { - start = sort.Search(len(messages), func(index int) bool { - return messageAfterCursor(messages[index], *cursor) - }) + afterTime = cursor.CreatedAt + afterID = cursor.MessageID } - - remaining := len(messages) - start - pageLength := min(remaining, limit) - page := make([]Message, pageLength) - copy(page, messages[start:start+pageLength]) - - return page, remaining > limit -} - -func (s *messageStore) listByChat(chatID string) []Message { - s.mu.RLock() - defer s.mu.RUnlock() - - messages := s.byChatID[chatID] - - result := make([]Message, len(messages)) - copy(result, messages) - - return result + rows, err := s.db.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid) ORDER BY created_at,id LIMIT $4`, chatID, afterTime, afterID, limit+1) + if err != nil { + return nil, false, err + } + defer rows.Close() + items := []Message{} + for rows.Next() { + var m Message + if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { + return nil, false, err + } + items = append(items, m) + } + if err = rows.Err(); err != nil { + return nil, false, err + } + more := len(items) > limit + if more { + items = items[:limit] + } + return items, more, nil } diff --git a/src/message_handler.go b/src/message_handler.go index 81c26d89..b50aaf10 100644 --- a/src/message_handler.go +++ b/src/message_handler.go @@ -34,20 +34,20 @@ func createMessageHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -81,9 +81,9 @@ func createMessageHandler( return } - chat, exists := chatStore.getByID(chatID) + chat, err := chatStore.getByID(r.Context(), chatID) - if !exists || !chatStore.isMember(chat, currentUserID) { + if err != nil || !chatStore.isMember(chat, currentUserID) { writeError( w, http.StatusNotFound, @@ -143,11 +143,16 @@ func createMessageHandler( return } - message := messageStore.create( + message, err := messageStore.create( + r.Context(), chatID, currentUserID, request.Text, ) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) diff --git a/src/message_handler_test.go b/src/message_handler_test.go deleted file mode 100644 index 90864933..00000000 --- a/src/message_handler_test.go +++ /dev/null @@ -1,291 +0,0 @@ -package main - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" -) - -func TestCreateMessageBlankText(t *testing.T) { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() - - user, created := userStore.create("alice", "Алиса") - if !created { - t.Fatal("expected user to be created") - } - - chat := chatStore.create( - "Тестовый чат", - []string{user.ID}, - ) - - handler := createMessageHandler( - userStore, - chatStore, - messageStore, - ) - - request := httptest.NewRequest( - http.MethodPost, - "/api/v1/chats/"+chat.ID+"/messages", - strings.NewReader(`{"text":" \t\n"}`), - ) - request.Header.Set("Content-Type", "application/json") - request.Header.Set("X-User-Id", user.ID) - - response := httptest.NewRecorder() - - handler.ServeHTTP(response, request) - - if response.Code != http.StatusBadRequest { - t.Fatalf( - "expected status %d, got %d; body: %s", - http.StatusBadRequest, - response.Code, - response.Body.String(), - ) - } - - if response.Header().Get("X-Request-Id") == "" { - t.Fatal("expected non-empty X-Request-Id header") - } - - if !strings.Contains( - response.Body.String(), - `"code":"invalid_request"`, - ) { - t.Fatalf( - "expected invalid_request error code, got body: %s", - response.Body.String(), - ) - } - - messages := messageStore.listByChat(chat.ID) - - if len(messages) != 0 { - t.Fatalf( - "expected no messages to be stored, got %d", - len(messages), - ) - } -} -func TestCreateMessageFromChatOutsider(t *testing.T) { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() - - alice, created := userStore.create("alice", "Алиса") - if !created { - t.Fatal("expected Alice to be created") - } - - bob, created := userStore.create("bob", "Боб") - if !created { - t.Fatal("expected Bob to be created") - } - - chat := chatStore.create( - "Чат Алисы", - []string{alice.ID}, - ) - - handler := createMessageHandler( - userStore, - chatStore, - messageStore, - ) - - request := httptest.NewRequest( - http.MethodPost, - "/api/v1/chats/"+chat.ID+"/messages", - strings.NewReader(`{"text":"Сообщение чужому чату"}`), - ) - request.Header.Set("Content-Type", "application/json") - request.Header.Set("X-User-Id", bob.ID) - - response := httptest.NewRecorder() - - handler.ServeHTTP(response, request) - - if response.Code != http.StatusNotFound { - t.Fatalf( - "expected status %d, got %d; body: %s", - http.StatusNotFound, - response.Code, - response.Body.String(), - ) - } - - if response.Header().Get("X-Request-Id") == "" { - t.Fatal("expected non-empty X-Request-Id header") - } - - if !strings.Contains( - response.Body.String(), - `"code":"not_found"`, - ) { - t.Fatalf( - "expected not_found error code, got body: %s", - response.Body.String(), - ) - } - - messages := messageStore.listByChat(chat.ID) - - if len(messages) != 0 { - t.Fatalf( - "expected no messages to be stored, got %d", - len(messages), - ) - } -} -func TestListMessagesPagination(t *testing.T) { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() - - user, created := userStore.create("alice", "Алиса") - if !created { - t.Fatal("expected user to be created") - } - - chat := chatStore.create( - "Тестовый чат", - []string{user.ID}, - ) - - first := messageStore.create(chat.ID, user.ID, "Первое сообщение") - second := messageStore.create(chat.ID, user.ID, "Второе сообщение") - third := messageStore.create(chat.ID, user.ID, "Третье сообщение") - - expectedIDs := map[string]bool{ - first.ID: true, - second.ID: true, - third.ID: true, - } - - handler := listMessagesHandler( - userStore, - chatStore, - messageStore, - ) - - // Запрашиваем только два сообщения из трёх. - firstRequest := httptest.NewRequest( - http.MethodGet, - "/api/v1/chats/"+chat.ID+"/messages?limit=2", - nil, - ) - firstRequest.Header.Set("X-User-Id", user.ID) - - firstResponse := httptest.NewRecorder() - - handler.ServeHTTP(firstResponse, firstRequest) - - if firstResponse.Code != http.StatusOK { - t.Fatalf( - "expected first page status %d, got %d; body: %s", - http.StatusOK, - firstResponse.Code, - firstResponse.Body.String(), - ) - } - - var firstPage messagePage - - if err := json.NewDecoder(firstResponse.Body).Decode(&firstPage); err != nil { - t.Fatalf("failed to decode first page: %v", err) - } - - if len(firstPage.Items) != 2 { - t.Fatalf( - "expected 2 messages on first page, got %d", - len(firstPage.Items), - ) - } - - if firstPage.NextCursor == nil || *firstPage.NextCursor == "" { - t.Fatal("expected non-empty next cursor on first page") - } - - // Проверяем, что сообщения на первой странице уникальны - // и принадлежат исходному набору. - seenIDs := make(map[string]bool) - - for _, message := range firstPage.Items { - if !expectedIDs[message.ID] { - t.Fatalf("unexpected message ID on first page: %s", message.ID) - } - - if seenIDs[message.ID] { - t.Fatalf("duplicate message on first page: %s", message.ID) - } - - seenIDs[message.ID] = true - } - - // Используем cursor первой страницы для получения второй. - secondRequest := httptest.NewRequest( - http.MethodGet, - "/api/v1/chats/"+chat.ID+"/messages?limit=2&cursor="+ - url.QueryEscape(*firstPage.NextCursor), - nil, - ) - secondRequest.Header.Set("X-User-Id", user.ID) - - secondResponse := httptest.NewRecorder() - - handler.ServeHTTP(secondResponse, secondRequest) - - if secondResponse.Code != http.StatusOK { - t.Fatalf( - "expected second page status %d, got %d; body: %s", - http.StatusOK, - secondResponse.Code, - secondResponse.Body.String(), - ) - } - - var secondPage messagePage - - if err := json.NewDecoder(secondResponse.Body).Decode(&secondPage); err != nil { - t.Fatalf("failed to decode second page: %v", err) - } - - if len(secondPage.Items) != 1 { - t.Fatalf( - "expected 1 message on second page, got %d", - len(secondPage.Items), - ) - } - - if secondPage.NextCursor != nil { - t.Fatalf("expected second page to be final, got cursor %q", *secondPage.NextCursor) - } - - // Проверяем, что вторая страница не повторяет первую. - for _, message := range secondPage.Items { - if seenIDs[message.ID] { - t.Fatalf("message repeated on second page: %s", message.ID) - } - - if !expectedIDs[message.ID] { - t.Fatalf("unexpected message ID on second page: %s", message.ID) - } - - seenIDs[message.ID] = true - } - - if len(seenIDs) != len(expectedIDs) { - t.Fatalf( - "pagination lost messages: expected %d unique messages, got %d", - len(expectedIDs), - len(seenIDs), - ) - } -} diff --git a/src/message_list_handler.go b/src/message_list_handler.go index f71b8b9a..15070aa5 100644 --- a/src/message_list_handler.go +++ b/src/message_list_handler.go @@ -69,20 +69,20 @@ func listMessagesHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -105,9 +105,9 @@ func listMessagesHandler( return } - chat, exists := chatStore.getByID(chatID) + chat, err := chatStore.getByID(r.Context(), chatID) - if !exists || !chatStore.isMember(chat, currentUserID) { + if err != nil || !chatStore.isMember(chat, currentUserID) { writeError( w, http.StatusNotFound, @@ -176,11 +176,16 @@ func listMessagesHandler( cursor = &decoded } - pageItems, hasMore := messageStore.listPageByChat( + pageItems, hasMore, err := messageStore.listPageByChat( + r.Context(), chatID, cursor, limit, ) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } page := messagePage{ Items: pageItems, diff --git a/src/message_store_test.go b/src/message_store_test.go deleted file mode 100644 index 372a746e..00000000 --- a/src/message_store_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package main - -import ( - "testing" - "time" -) - -func TestMessageLessUsesIDForEqualTimestamps(t *testing.T) { - createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC) - first := Message{ID: "a", CreatedAt: createdAt} - second := Message{ID: "b", CreatedAt: createdAt} - - if !messageLess(first, second) { - t.Fatal("expected the smaller ID to sort first for equal timestamps") - } - - if messageLess(second, first) { - t.Fatal("expected the larger ID to sort last for equal timestamps") - } -} - -func TestListPageByChatUsesCursorAndLimit(t *testing.T) { - createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC) - store := newMessageStore() - store.byChatID["chat-1"] = []Message{ - {ID: "a", ChatID: "chat-1", CreatedAt: createdAt}, - {ID: "b", ChatID: "chat-1", CreatedAt: createdAt}, - {ID: "c", ChatID: "chat-1", CreatedAt: createdAt.Add(time.Second)}, - {ID: "d", ChatID: "chat-1", CreatedAt: createdAt.Add(2 * time.Second)}, - } - - firstPage, hasMore := store.listPageByChat("chat-1", nil, 2) - if !hasMore { - t.Fatal("expected another page") - } - if len(firstPage) != 2 || firstPage[0].ID != "a" || firstPage[1].ID != "b" { - t.Fatalf("unexpected first page: %#v", firstPage) - } - - cursor := messageCursor{ - ChatID: "chat-1", - CreatedAt: firstPage[1].CreatedAt, - MessageID: firstPage[1].ID, - } - secondPage, hasMore := store.listPageByChat("chat-1", &cursor, 2) - if hasMore { - t.Fatal("did not expect another page") - } - if len(secondPage) != 2 || secondPage[0].ID != "c" || secondPage[1].ID != "d" { - t.Fatalf("unexpected second page: %#v", secondPage) - } -} - -func TestListPageByChatReturnsNonNilEmptyPage(t *testing.T) { - store := newMessageStore() - - page, hasMore := store.listPageByChat("missing", nil, 100) - if page == nil { - t.Fatal("expected a non-nil empty page") - } - if len(page) != 0 || hasMore { - t.Fatalf("unexpected empty page result: page=%#v hasMore=%v", page, hasMore) - } -} diff --git a/src/migrations/001_initial.sql b/src/migrations/001_initial.sql new file mode 100644 index 00000000..2962c554 --- /dev/null +++ b/src/migrations/001_initial.sql @@ -0,0 +1,33 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash bytea NOT NULL, + password_salt bytea NOT NULL, + created_at timestamptz NOT NULL +); +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at timestamptz NOT NULL +); +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id,user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members(user_id,chat_id); +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL REFERENCES users(id), + text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at timestamptz NOT NULL +); +CREATE INDEX messages_history_idx ON messages(chat_id,created_at,id); +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL +); +CREATE INDEX sessions_expiry_idx ON sessions(expires_at); diff --git a/src/security_test.go b/src/security_test.go new file mode 100644 index 00000000..9e65f02b --- /dev/null +++ b/src/security_test.go @@ -0,0 +1,54 @@ +package main + +import ( + "bytes" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestPasswordKDFUsesSaltAndFullUTF8Password(t *testing.T) { + password := "длинный-пароль-с-эмодзи-🔒-0123456789" + first, err := derivePassword(password, bytes.Repeat([]byte{1}, 32)) + if err != nil { + t.Fatal(err) + } + same, err := derivePassword(password, bytes.Repeat([]byte{1}, 32)) + if err != nil { + t.Fatal(err) + } + changed, err := derivePassword(password, bytes.Repeat([]byte{2}, 32)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(first, same) || bytes.Equal(first, changed) { + t.Fatal("password derivation lost salt or determinism") + } +} + +func TestBearerRequiredIgnoresXUserID(t *testing.T) { + handler := authRequired(&sessionStore{}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Fatal("business handler reached without bearer") })) + request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil) + request.Header.Set("X-User-Id", "11111111-1111-4111-8111-111111111111") + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != 401 || response.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` { + t.Fatalf("unexpected response: %d %v", response.Code, response.Header()) + } +} + +func TestMessageCursorPreservesPosition(t *testing.T) { + original := messageCursor{ChatID: "11111111-1111-4111-8111-111111111111", CreatedAt: time.Date(2026, 9, 23, 10, 0, 0, 123000, time.UTC), MessageID: "22222222-2222-4222-8222-222222222222"} + token, err := encodeMessageCursor(original) + if err != nil { + t.Fatal(err) + } + decoded, err := decodeMessageCursor(token) + if err != nil { + t.Fatal(err) + } + if decoded != original { + t.Fatalf("cursor changed: %+v", decoded) + } +} diff --git a/src/session.go b/src/session.go new file mode 100644 index 00000000..77838492 --- /dev/null +++ b/src/session.go @@ -0,0 +1,157 @@ +package main + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "os" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type sessionStore struct { + db *pgxpool.Pool + ttl time.Duration +} + +type authenticatedUserKey struct{} + +func currentUserID(r *http.Request) string { + id, _ := r.Context().Value(authenticatedUserKey{}).(string) + return id +} + +func newSessionStore(db *pgxpool.Pool) (*sessionStore, error) { + seconds := 3600 + if value := os.Getenv("SESSION_TTL_SECONDS"); value != "" { + n, err := strconv.Atoi(value) + if err != nil || n < 1 { + return nil, errors.New("invalid SESSION_TTL_SECONDS") + } + seconds = n + } + return &sessionStore{db: db, ttl: time.Duration(seconds) * time.Second}, nil +} + +func (s *sessionStore) create(r *http.Request, userID string) (string, time.Time, error) { + raw := make([]byte, 32) + if _, err := rand.Read(raw); err != nil { + return "", time.Time{}, err + } + token := hex.EncodeToString(raw) + hash := sha256.Sum256([]byte(token)) + expires := time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond) + _, err := s.db.Exec(r.Context(), "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,$3)", hash[:], userID, expires) + return token, expires, err +} + +func (s *sessionStore) user(r *http.Request, token string) (User, error) { + hash := sha256.Sum256([]byte(token)) + var user User + err := s.db.QueryRow(r.Context(), `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()`, hash[:]).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + return user, err +} + +func (s *sessionStore) revoke(r *http.Request, token string) error { + hash := sha256.Sum256([]byte(token)) + _, err := s.db.Exec(r.Context(), "DELETE FROM sessions WHERE token_hash=$1", hash[:]) + return err +} + +// authRequired replaces the lab1 X-User-Id trust model before any business handler runs. +func authRequired(s *sessionStore, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authorization := r.Header.Get("Authorization") + if !strings.HasPrefix(authorization, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(authorization, "Bearer ")) == "" { + unauthorized(w, "Bearer", newRequestID()) + return + } + token := strings.TrimPrefix(authorization, "Bearer ") + user, err := s.user(r, token) + if errors.Is(err, pgx.ErrNoRows) { + unauthorized(w, "Bearer", newRequestID()) + return + } + if err != nil { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), authenticatedUserKey{}, user.ID))) + }) +} + +func unauthorized(w http.ResponseWriter, scheme, requestID string) { + w.Header().Set("X-Request-Id", requestID) + if scheme == "Basic" { + w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`) + } else { + w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`) + } + writeError(w, 401, "unauthorized", "invalid credentials", requestID) +} + +func sessionHandler(users *userStore, sessions *sessionStore) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodPost { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + username, password, ok := r.BasicAuth() + if !ok || !usernamePattern.MatchString(username) || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 || r.ContentLength > 0 { + unauthorized(w, "Basic", requestID) + return + } + user, valid, err := users.verifyPassword(r.Context(), username, password) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + if !valid { + unauthorized(w, "Basic", requestID) + return + } + token, expires, err := sessions.create(r, user.ID) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(201) + json.NewEncoder(w).Encode(struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User User `json:"user"` + }{token, "Bearer", expires, user}) + } +} + +func logoutHandler(sessions *sessionStore) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodDelete { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + if err := sessions.revoke(r, token); err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + w.WriteHeader(204) + } +} diff --git a/src/user.go b/src/user.go index f9ec7f26..594f8e7a 100644 --- a/src/user.go +++ b/src/user.go @@ -1,10 +1,16 @@ package main import ( - "sync" + "context" + "crypto/rand" + "crypto/subtle" + "errors" "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "golang.org/x/crypto/scrypt" ) type User struct { @@ -15,44 +21,56 @@ type User struct { } type userStore struct { - mu sync.RWMutex - byID map[string]User - byUsername map[string]string + db *pgxpool.Pool } -func newUserStore() *userStore { - return &userStore{ - byID: make(map[string]User), - byUsername: make(map[string]string), - } +func newUserStore(db *pgxpool.Pool) *userStore { + return &userStore{db: db} } -func (s *userStore) create(username string, displayName string) (User, bool) { - s.mu.Lock() - defer s.mu.Unlock() +func derivePassword(password string, salt []byte) ([]byte, error) { + return scrypt.Key([]byte(password), salt, 32768, 8, 1, 32) +} - if _, exists := s.byUsername[username]; exists { - return User{}, false +func (s *userStore) create(ctx context.Context, username, displayName, password string) (User, error) { + salt := make([]byte, 32) + if _, err := rand.Read(salt); err != nil { + return User{}, err + } + hash, err := derivePassword(password, salt) + if err != nil { + return User{}, err } - user := User{ ID: uuid.New().String(), Username: username, DisplayName: displayName, - CreatedAt: time.Now().UTC(), + CreatedAt: time.Now().UTC().Truncate(time.Microsecond), } - s.byID[user.ID] = user - s.byUsername[user.Username] = user.ID - - return user, true + _, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,password_salt,created_at) VALUES($1,$2,$3,$4,$5,$6)", user.ID, user.Username, user.DisplayName, hash, salt, user.CreatedAt) + return user, err } -func (s *userStore) getByID(id string) (User, bool) { - s.mu.RLock() - defer s.mu.RUnlock() +func (s *userStore) getByID(ctx context.Context, id string) (User, error) { + var user User + err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at FROM users WHERE id=$1", id).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + return user, err +} - user, exists := s.byID[id] - - return user, exists +func (s *userStore) verifyPassword(ctx context.Context, username, password string) (User, bool, error) { + var user User + var hash, salt []byte + err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash,password_salt FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash, &salt) + if errors.Is(err, pgx.ErrNoRows) { + return User{}, false, nil + } + if err != nil { + return User{}, false, err + } + actual, err := derivePassword(password, salt) + if err != nil { + return User{}, false, err + } + return user, subtle.ConstantTimeCompare(hash, actual) == 1, nil } diff --git a/src/user_handler.go b/src/user_handler.go index ec72c3e9..4f9e05fb 100644 --- a/src/user_handler.go +++ b/src/user_handler.go @@ -2,6 +2,9 @@ package main import ( "encoding/json" + "errors" + "fmt" + "github.com/jackc/pgx/v5/pgconn" "io" "log" "net/http" @@ -13,6 +16,7 @@ import ( type createUserRequest struct { Username string `json:"username"` DisplayName string `json:"display_name"` + Password string `json:"password"` } var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) @@ -27,7 +31,10 @@ func decodeJSONBody(r *http.Request, destination any) error { var extra any if err := decoder.Decode(&extra); err != io.EOF { - return err + if err != nil { + return err + } + return fmt.Errorf("more than one JSON value") } return nil @@ -105,13 +112,19 @@ func createUserHandler(store *userStore) http.HandlerFunc { ) return } + if strings.TrimSpace(request.Password) == "" || utf8.RuneCountInString(request.Password) < 12 || utf8.RuneCountInString(request.Password) > 128 { + writeError(w, http.StatusBadRequest, "invalid_request", "password must contain 12-128 characters", requestID) + return + } - user, created := store.create( + user, err := store.create( + r.Context(), request.Username, request.DisplayName, + request.Password, ) - if !created { + if uniqueViolation(err) { writeError( w, http.StatusConflict, @@ -121,6 +134,15 @@ func createUserHandler(store *userStore) http.HandlerFunc { ) return } + if err != nil { + var pgerr *pgconn.PgError + if errors.As(err, &pgerr) && pgerr.Code == "23514" { + writeError(w, 400, "invalid_request", "invalid user fields", requestID) + } else { + writeError(w, 503, "unavailable", "database unavailable", requestID) + } + return + } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) diff --git a/src/user_handler_test.go b/src/user_handler_test.go deleted file mode 100644 index d8c1277f..00000000 --- a/src/user_handler_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package main - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestCreateUserInvalidJSON(t *testing.T) { - store := newUserStore() - handler := createUserHandler(store) - - request := httptest.NewRequest( - http.MethodPost, - "/api/v1/users", - strings.NewReader(`{"username":`), - ) - request.Header.Set("Content-Type", "application/json") - - response := httptest.NewRecorder() - - handler.ServeHTTP(response, request) - - if response.Code != http.StatusBadRequest { - t.Fatalf( - "expected status %d, got %d; body: %s", - http.StatusBadRequest, - response.Code, - response.Body.String(), - ) - } - - if response.Header().Get("Content-Type") != "application/json" { - t.Fatalf( - "expected Content-Type application/json, got %q", - response.Header().Get("Content-Type"), - ) - } - - if response.Header().Get("X-Request-Id") == "" { - t.Fatal("expected non-empty X-Request-Id header") - } - - body := response.Body.String() - - if !strings.Contains(body, `"code":"invalid_request"`) { - t.Fatalf( - "expected invalid_request error code, got body: %s", - body, - ) - } - - if !strings.Contains(body, "request_id") { - t.Fatalf( - "expected request_id in error body, got body: %s", - body, - ) - } -} - -func TestCreateUserDuplicateUsername(t *testing.T) { - store := newUserStore() - handler := createUserHandler(store) - - firstRequest := httptest.NewRequest( - http.MethodPost, - "/api/v1/users", - strings.NewReader(`{ - "username": "alice", - "display_name": "Алиса" - }`), - ) - firstRequest.Header.Set("Content-Type", "application/json") - - firstResponse := httptest.NewRecorder() - - handler.ServeHTTP(firstResponse, firstRequest) - - if firstResponse.Code != http.StatusCreated { - t.Fatalf( - "expected first request status %d, got %d; body: %s", - http.StatusCreated, - firstResponse.Code, - firstResponse.Body.String(), - ) - } - - secondRequest := httptest.NewRequest( - http.MethodPost, - "/api/v1/users", - strings.NewReader(`{ - "username": "alice", - "display_name": "Другая Алиса" - }`), - ) - secondRequest.Header.Set("Content-Type", "application/json") - - secondResponse := httptest.NewRecorder() - - handler.ServeHTTP(secondResponse, secondRequest) - - if secondResponse.Code != http.StatusConflict { - t.Fatalf( - "expected duplicate username status %d, got %d; body: %s", - http.StatusConflict, - secondResponse.Code, - secondResponse.Body.String(), - ) - } - - if secondResponse.Header().Get("X-Request-Id") == "" { - t.Fatal("expected non-empty X-Request-Id header") - } - - if !strings.Contains( - secondResponse.Body.String(), - `"code":"conflict"`, - ) { - t.Fatalf( - "expected conflict error code, got body: %s", - secondResponse.Body.String(), - ) - } - - if len(store.byID) != 1 { - t.Fatalf( - "expected exactly one user in store, got %d", - len(store.byID), - ) - } -} -- 2.54.0 From 08cb1cbfd41abaeb90a5cb07152545295321e2f8 Mon Sep 17 00:00:00 2001 From: Dima Date: Wed, 23 Sep 2026 21:38:55 +0300 Subject: [PATCH 3/9] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20Compose-=D1=81=D1=82=D0=B5=D0=BD=D0=B4=20=D0=B8=20?= =?UTF-8?q?=D1=81=D1=86=D0=B5=D0=BD=D0=B0=D1=80=D0=B8=D0=B8=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20=D1=81=D0=BE=D1=85=D1=80?= =?UTF-8?q?=D0=B0=D0=BD=D0=BD=D0=BE=D1=81=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 12 ++++-------- .gitattributes | 1 + Makefile | 5 ++++- compose.yaml | 34 ++++++++++++++++++++++++++++++++++ tests/session_expiry.py | 18 ++++++++++++++++++ 5 files changed, 61 insertions(+), 9 deletions(-) create mode 100644 .gitattributes create mode 100644 compose.yaml create mode 100644 tests/session_expiry.py diff --git a/.env.example b/.env.example index 714c8076..1a20e778 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,7 @@ # 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 +POSTGRES_DB=messenger +POSTGRES_USER=messenger +# Replace with a random local value before starting Compose. +POSTGRES_PASSWORD=replace-with-local-random-password 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 -CACHE_URL_FILE=/run/secrets/cache_url diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..dfdb8b77 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/Makefile b/Makefile index 9ecb223e..0c498d93 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence +.PHONY: help check validate unit test load test-persistence help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -15,6 +15,9 @@ check: validate: $(PYTHON) scripts/validate_openapi.py +unit: + go test ./... + test: $(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..a9811f07 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,34 @@ +services: + db: + image: postgres:16.10-bookworm + environment: + POSTGRES_DB: ${POSTGRES_DB} + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] + interval: 3s + timeout: 3s + retries: 20 + api: + build: . + environment: + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable + ports: + - "127.0.0.1:8080:8080" + depends_on: + db: + condition: service_healthy + healthcheck: + test: ["CMD", "./healthcheck"] + interval: 5s + timeout: 3s + retries: 20 + +volumes: + postgres_data: diff --git a/tests/session_expiry.py b/tests/session_expiry.py new file mode 100644 index 00000000..e155c83b --- /dev/null +++ b/tests/session_expiry.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +"""Run against a test stack configured with SESSION_TTL_SECONDS=2.""" +import time +from client import Client, arguments, check, run + + +def main(): + args = arguments('Check that a short lived session expires') + client = Client(args.base_url, args.ca_file) + actor = client.user('expiry') + client.call('GET', '/api/v1/users/me', actor=actor, schema='User') + time.sleep(3) + client.call('GET', '/api/v1/users/me', 401, actor=actor) + print('PASS: expired Bearer token was rejected') + + +if __name__ == '__main__': + run(main) -- 2.54.0 From c6db0aa71ac0dfba65d4b0cfb25e45b5c2437672 Mon Sep 17 00:00:00 2001 From: Dima Date: Wed, 23 Sep 2026 21:57:44 +0300 Subject: [PATCH 4/9] =?UTF-8?q?=D0=9E=D1=81=D1=82=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BE=D0=B4=D0=BD=D1=83=20=D0=BE=D0=B1=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=B8=D0=BC=D1=83=D1=8E=20=D0=BC=D0=B8=D0=B3=D1=80=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8E=20=D0=B8=20=D0=BC=D0=B8=D0=BD=D0=B8=D0=BC?= =?UTF-8?q?=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D0=B5=20=D1=84=D0=B0=D0=B9=D0=BB?= =?UTF-8?q?=D1=8B=20=D1=81=D1=82=D0=B5=D0=BD=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitattributes | 1 - Dockerfile | 12 +--- Makefile | 5 +- cmd/healthcheck/main.go | 24 -------- compose.yaml | 2 +- go.mod | 7 ++- go.sum | 55 +++++++++++++++++-- src/database.go | 55 +++++++++---------- src/main.go | 26 +++++++++ src/migrations/000001_initial.down.sql | 5 ++ ...{001_initial.sql => 000001_initial.up.sql} | 17 +++--- src/user.go | 14 +++-- tests/session_expiry.py | 18 ------ 13 files changed, 134 insertions(+), 107 deletions(-) delete mode 100644 .gitattributes delete mode 100644 cmd/healthcheck/main.go create mode 100644 src/migrations/000001_initial.down.sql rename src/migrations/{001_initial.sql => 000001_initial.up.sql} (66%) delete mode 100644 tests/session_expiry.py diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index dfdb8b77..00000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.sh text eol=lf diff --git a/Dockerfile b/Dockerfile index d18fbf96..399c36b8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,7 +7,6 @@ COPY go.mod go.sum ./ RUN go mod download COPY src ./src -COPY cmd ./cmd RUN CGO_ENABLED=0 \ GOOS=linux \ @@ -17,14 +16,6 @@ RUN CGO_ENABLED=0 \ -o /out/messenger \ ./src -# healthcheck script build -RUN CGO_ENABLED=0 \ - GOOS=linux \ - go build \ - -trimpath \ - -ldflags="-s -w" \ - -o /out/healthcheck \ - ./cmd/healthcheck FROM debian:12.15-slim @@ -34,7 +25,6 @@ RUN groupadd --system app \ WORKDIR /app COPY --from=builder /out/messenger ./messenger -COPY --from=builder /out/healthcheck ./healthcheck ENV APP_HOST=0.0.0.0 ENV APP_PORT=8080 @@ -42,7 +32,7 @@ ENV APP_PORT=8080 EXPOSE 8080 HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ - CMD ["./healthcheck"] + CMD ["./messenger", "healthcheck"] USER app:app diff --git a/Makefile b/Makefile index 0c498d93..9ecb223e 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate unit test load test-persistence +.PHONY: help check validate test load test-persistence help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -15,9 +15,6 @@ check: validate: $(PYTHON) scripts/validate_openapi.py -unit: - go test ./... - test: $(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) diff --git a/cmd/healthcheck/main.go b/cmd/healthcheck/main.go deleted file mode 100644 index c5e60059..00000000 --- a/cmd/healthcheck/main.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "net/http" - "os" - "time" -) - -func main() { - client := http.Client{ - Timeout: 2 * time.Second, - } - - response, err := client.Get("http://127.0.0.1:8080/health/ready") - if err != nil { - os.Exit(1) - } - - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - os.Exit(1) - } -} diff --git a/compose.yaml b/compose.yaml index a9811f07..32630e1c 100644 --- a/compose.yaml +++ b/compose.yaml @@ -25,7 +25,7 @@ services: db: condition: service_healthy healthcheck: - test: ["CMD", "./healthcheck"] + test: ["CMD", "./messenger", "healthcheck"] interval: 5s timeout: 3s retries: 20 diff --git a/go.mod b/go.mod index 99bf2424..ff023359 100644 --- a/go.mod +++ b/go.mod @@ -3,15 +3,20 @@ module messenger go 1.22.2 require ( + github.com/golang-migrate/migrate/v4 v4.17.1 github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.5.5 golang.org/x/crypto v0.22.0 ) require ( + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect - golang.org/x/sync v0.1.0 // indirect + go.uber.org/atomic v1.7.0 // indirect + golang.org/x/sync v0.5.0 // indirect golang.org/x/text v0.14.0 // indirect ) diff --git a/go.sum b/go.sum index 99d44c20..6a4ec1aa 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,33 @@ +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= 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/dhui/dktest v0.4.1 h1:/w+IWuDXVymg3IrRJCHHOkMK10m9aNVMOyD0X12YVTg= +github.com/dhui/dktest v0.4.1/go.mod h1:DdOqcUpL7vgyP4GlF3X3w7HbSlz8cEQzwewPveYEQbA= +github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= +github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v24.0.9+incompatible h1:HPGzNmwfLZWdxHqK9/II92pyi1EpYKsAqcl4G0Of9v0= +github.com/docker/docker v24.0.9+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-migrate/migrate/v4 v4.17.1 h1:4zQ6iqL6t6AiItphxJctQb3cFqWiSpMnX7wLTPnnYO4= +github.com/golang-migrate/migrate/v4 v4.17.1/go.mod h1:m8hinFyWBn0SA4QKHuKh175Pm9wjmxj3S2Mia7dbXzM= 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/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa h1:s+4MhCQ6YrzisK6hFJUX53drDT4UsSW3DEhKn0ifuHw= +github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds= 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-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= @@ -11,19 +36,41 @@ github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw= github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A= github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= +github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM= +github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 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.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= -golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU= +golang.org/x/mod v0.11.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= +golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.10.0 h1:tvDr/iQoUqNdohiYm0LmmKcBk+q86lb9EprIUFhHHGg= +golang.org/x/tools v0.10.0/go.mod h1:UJwyiVBsOA2uwvK/e5OY3GTpDUJriEd+/YlqAwLPmyM= 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/src/database.go b/src/database.go index cd288127..42ce63eb 100644 --- a/src/database.go +++ b/src/database.go @@ -2,16 +2,19 @@ package main import ( "context" + "database/sql" "embed" "errors" - "fmt" "os" - "sort" "strings" "time" + "github.com/golang-migrate/migrate/v4" + pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5" + "github.com/golang-migrate/migrate/v4/source/iofs" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" + _ "github.com/jackc/pgx/v5/stdlib" ) //go:embed migrations/*.sql @@ -50,50 +53,44 @@ func openDatabase(ctx context.Context) (*pgxpool.Pool, error) { db.Close() return nil, err } - if err = applyMigrations(ctx, db); err != nil { + if err = runMigrations(url, "up"); err != nil { db.Close() return nil, err } return db, nil } -func applyMigrations(ctx context.Context, db *pgxpool.Pool) error { - files, err := migrationFiles.ReadDir("migrations") +// runMigrations uses versioned up/down SQL embedded in the API binary. +// "down" rolls back exactly one version and is an explicit operator command. +func runMigrations(url, direction string) error { + source, err := iofs.New(migrationFiles, "migrations") if err != nil { return err } - sort.Slice(files, func(i, j int) bool { return files[i].Name() < files[j].Name() }) - tx, err := db.Begin(ctx) + sqlDB, err := sql.Open("pgx", url) if err != nil { return err } - defer tx.Rollback(ctx) - if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(20426002)"); err != nil { + driver, err := pgxmigrate.WithInstance(sqlDB, &pgxmigrate.Config{}) + if err != nil { + sqlDB.Close() return err } - if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)"); err != nil { + m, err := migrate.NewWithInstance("iofs", source, "pgx5", driver) + if err != nil { + sqlDB.Close() return err } - for _, file := range files { - var exists bool - if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)", file.Name()).Scan(&exists); err != nil { - return err - } - if exists { - continue - } - sql, readErr := migrationFiles.ReadFile("migrations/" + file.Name()) - if readErr != nil { - return readErr - } - if _, err = tx.Exec(ctx, string(sql)); err != nil { - return fmt.Errorf("migration %s: %w", file.Name(), err) - } - if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES($1)", file.Name()); err != nil { - return err - } + defer m.Close() + if direction == "down" { + err = m.Steps(-1) + } else { + err = m.Up() } - return tx.Commit(ctx) + if errors.Is(err, migrate.ErrNoChange) { + return nil + } + return err } func uniqueViolation(err error) bool { diff --git a/src/main.go b/src/main.go index e0d512cc..df92709c 100644 --- a/src/main.go +++ b/src/main.go @@ -110,6 +110,32 @@ func serverAddress() string { } func main() { + if len(os.Args) > 1 { + if len(os.Args) == 2 && os.Args[1] == "healthcheck" { + client := http.Client{Timeout: 2 * time.Second} + response, err := client.Get("http://127.0.0.1:8080/health/ready") + if err != nil { + os.Exit(1) + } + response.Body.Close() + if response.StatusCode != http.StatusOK { + os.Exit(1) + } + return + } + if len(os.Args) != 3 || os.Args[1] != "migrate" || (os.Args[2] != "up" && os.Args[2] != "down") { + log.Fatal("usage: messenger migrate up|down") + } + url, err := databaseURL() + if err != nil { + log.Fatal(err) + } + if err = runMigrations(url, os.Args[2]); err != nil { + log.Fatal(err) + } + log.Printf("migration %s complete", os.Args[2]) + return + } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) db, err := openDatabase(ctx) cancel() diff --git a/src/migrations/000001_initial.down.sql b/src/migrations/000001_initial.down.sql new file mode 100644 index 00000000..a3ba4f2d --- /dev/null +++ b/src/migrations/000001_initial.down.sql @@ -0,0 +1,5 @@ +DROP TABLE IF EXISTS sessions; +DROP TABLE IF EXISTS messages; +DROP TABLE IF EXISTS chat_members; +DROP TABLE IF EXISTS chats; +DROP TABLE IF EXISTS users; diff --git a/src/migrations/001_initial.sql b/src/migrations/000001_initial.up.sql similarity index 66% rename from src/migrations/001_initial.sql rename to src/migrations/000001_initial.up.sql index 2962c554..b00ad15f 100644 --- a/src/migrations/001_initial.sql +++ b/src/migrations/000001_initial.up.sql @@ -1,33 +1,32 @@ -CREATE TABLE users ( +CREATE TABLE IF NOT EXISTS users ( id uuid PRIMARY KEY, username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), password_hash bytea NOT NULL, - password_salt bytea NOT NULL, created_at timestamptz NOT NULL ); -CREATE TABLE chats ( +CREATE TABLE IF NOT EXISTS chats ( id uuid PRIMARY KEY, title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), created_at timestamptz NOT NULL ); -CREATE TABLE chat_members ( +CREATE TABLE IF NOT EXISTS chat_members ( chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, user_id uuid NOT NULL REFERENCES users(id), PRIMARY KEY (chat_id,user_id) ); -CREATE INDEX chat_members_user_idx ON chat_members(user_id,chat_id); -CREATE TABLE messages ( +CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members(user_id,chat_id); +CREATE TABLE IF NOT EXISTS messages ( id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats(id), sender_id uuid NOT NULL REFERENCES users(id), text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), created_at timestamptz NOT NULL ); -CREATE INDEX messages_history_idx ON messages(chat_id,created_at,id); -CREATE TABLE sessions ( +CREATE INDEX IF NOT EXISTS messages_history_idx ON messages(chat_id,created_at,id); +CREATE TABLE IF NOT EXISTS sessions ( token_hash bytea PRIMARY KEY, user_id uuid NOT NULL REFERENCES users(id), expires_at timestamptz NOT NULL ); -CREATE INDEX sessions_expiry_idx ON sessions(expires_at); +CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions(expires_at); diff --git a/src/user.go b/src/user.go index 594f8e7a..a535ce3e 100644 --- a/src/user.go +++ b/src/user.go @@ -41,6 +41,7 @@ func (s *userStore) create(ctx context.Context, username, displayName, password if err != nil { return User{}, err } + packedHash := append(salt, hash...) user := User{ ID: uuid.New().String(), Username: username, @@ -48,7 +49,7 @@ func (s *userStore) create(ctx context.Context, username, displayName, password CreatedAt: time.Now().UTC().Truncate(time.Microsecond), } - _, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,password_salt,created_at) VALUES($1,$2,$3,$4,$5,$6)", user.ID, user.Username, user.DisplayName, hash, salt, user.CreatedAt) + _, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,$2,$3,$4,$5)", user.ID, user.Username, user.DisplayName, packedHash, user.CreatedAt) return user, err } @@ -60,17 +61,20 @@ func (s *userStore) getByID(ctx context.Context, id string) (User, error) { func (s *userStore) verifyPassword(ctx context.Context, username, password string) (User, bool, error) { var user User - var hash, salt []byte - err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash,password_salt FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash, &salt) + var packedHash []byte + err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &packedHash) if errors.Is(err, pgx.ErrNoRows) { return User{}, false, nil } if err != nil { return User{}, false, err } - actual, err := derivePassword(password, salt) + if len(packedHash) != 64 { + return User{}, false, errors.New("invalid password hash format") + } + actual, err := derivePassword(password, packedHash[:32]) if err != nil { return User{}, false, err } - return user, subtle.ConstantTimeCompare(hash, actual) == 1, nil + return user, subtle.ConstantTimeCompare(packedHash[32:], actual) == 1, nil } diff --git a/tests/session_expiry.py b/tests/session_expiry.py deleted file mode 100644 index e155c83b..00000000 --- a/tests/session_expiry.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python3 -"""Run against a test stack configured with SESSION_TTL_SECONDS=2.""" -import time -from client import Client, arguments, check, run - - -def main(): - args = arguments('Check that a short lived session expires') - client = Client(args.base_url, args.ca_file) - actor = client.user('expiry') - client.call('GET', '/api/v1/users/me', actor=actor, schema='User') - time.sleep(3) - client.call('GET', '/api/v1/users/me', 401, actor=actor) - print('PASS: expired Bearer token was rejected') - - -if __name__ == '__main__': - run(main) -- 2.54.0 From fd4bf013bbc4e5a7184ba745cd193230e9771644 Mon Sep 17 00:00:00 2001 From: Dima Date: Wed, 23 Sep 2026 21:57:44 +0300 Subject: [PATCH 5/9] =?UTF-8?q?=D0=9E=D0=BF=D0=B8=D1=81=D0=B0=D1=82=D1=8C?= =?UTF-8?q?=20=D0=B7=D0=B0=D0=BF=D1=83=D1=81=D0=BA=20=D0=B8=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=BA=D0=B0=D0=B7=D0=B0=D1=82=D0=B5=D0=BB=D1=8C=D1=81=D1=82?= =?UTF-8?q?=D0=B2=D0=B0=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BD=D0=BE=D0=B9=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 75 +++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 56 insertions(+), 19 deletions(-) diff --git a/REPORT.md b/REPORT.md index e42f2b05..6438fd52 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,74 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Гришко Дмитрий Михайлович, БВТ2303 +- Целевая оценка: **3** +- Ветка: `solution/BVT2303-grishko` +- Источники: [задание](README.md), [контракт](contracts/README.md), [проверки](tests/README.md), [golang-migrate](https://github.com/golang-migrate/migrate), документация PostgreSQL и Go +- Зависимости: Go 1.22.2, PostgreSQL 16.10, `pgx/v5`, `golang-migrate/v4`, `x/crypto/scrypt`, `google/uuid`; помощь ИИ: OpenAI Codex — реализация и проверка кода ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Engine с Compose, Python 3.9+ и Make. Go нужен для `go test ./...` вне контейнера. Команды приведены для Linux/WSL в корне репозитория. + +```sh +cp .env.example .env +sed -i "s/replace-with-local-random-password/$(openssl rand -hex 24)/" .env +make check +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build --wait +make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh +go test ./... +``` + +`.env` содержит локальный пароль и исключён из Git. База доступна только внутри Compose-сети; HTTP API опубликован на `127.0.0.1:8080`. Миграции `up` применяются автоматически перед запуском HTTP-сервера. Они встроены в бинарник из `src/migrations`. Применение вручную: `docker compose --env-file .env run --rm --no-deps api migrate up` при уже запущенной БД. Откат **одной** версии, удаляющий таблицы и данные этой начальной миграции, выполняется только сознательно при остановленном API: `docker compose --env-file .env stop api`, затем `docker compose --env-file .env run --rm --no-deps api migrate down`. + +Безопасная остановка: `docker compose --env-file .env down` — volume сохранится. Намеренное удаление учебных данных: `docker compose --env-file .env down -v`. После смены пароля в `.env` для уже инициализированного volume надо отдельно менять пароль роли PostgreSQL; изменение одной строки `.env` существующую роль не обновляет. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +```text +HTTP-клиент → Go net/http API → PostgreSQL (именованный volume postgres_data) +``` + +Перенесены модели, маршруты, валидация JSON и курсоры из лабораторной 1. Методы `userStore`, `chatStore` и `messageStore` переписаны на PostgreSQL; прежние in-memory коллекции удалены. Публичная регистрация теперь требует пароль. На `POST /auth/sessions` допускается только Basic; остальные защищённые маршруты проходят через проверку Bearer. Идентификатор пользователя передаётся обработчикам через контекст запроса, `X-User-Id` игнорируется. + +| Таблица | Ключи и ограничения | Назначение | +| --- | --- | --- | +| `users` | PK `id`, UNIQUE `username`, CHECK длины и формата | Пользователи и хеши паролей | +| `chats` | PK `id`, CHECK длины названия | Чаты | +| `chat_members` | PK `(chat_id,user_id)`, FK на обе таблицы, индекс `(user_id,chat_id)` | Членство и выборка доступных чатов | +| `messages` | PK `id`, FK на чат и отправителя, индекс `(chat_id,created_at,id)` | История и keyset-пагинация | +| `sessions` | PK `token_hash`, FK `user_id`, индекс `expires_at` | Действующие сессии | + +Создание чата и всех записей членства — одна транзакция: при ошибке ни чат, ни часть участников не сохраняются. Регистрация, отправка сообщения, выдача и отзыв сессии — отдельные атомарные SQL-операции. Все параметры передаются через `pgx`, а не собираются в SQL-строку. Чтение истории выполняет `ORDER BY created_at,id LIMIT limit+1` с условием курсора. Часы назначения времени находятся в API; при конкурентных вставках между страницами snapshot всей истории не обещается. + +Пароль обрабатывается `scrypt` со случайной 32-байтной солью (`N=32768,r=8,p=1`). В БД у пользователя только колонка `password_hash`: её 64 байта содержат соль и производный ключ подряд. Это нужно для повторной проверки пароля; значение не входит в API-ответ. Токен сессии содержит 256 случайных бит, клиент получает его один раз, в БД хранится только SHA-256 токена. Истечение проверяется по `expires_at` при каждом запросе, logout удаляет строку. Это не продлевает TTL при рестарте. PostgreSQL — источник истины для всех данных и сессий. `GET /health/ready` проверяет доступность БД. + +`golang-migrate` хранит номер версии и признак незавершённой миграции в `schema_migrations`. Есть ровно одна парная миграция: `000001_initial.up.sql` и `.down.sql`; повторный `up` не создаёт данные заново. Миграция `down` проверялась только на отдельной временной БД. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Критерий | Команда/сценарий | Результат | +| --- | --- | --- | +| Контракт и код | `make check`, `go test ./...`, `go vet ./...` | PASS | +| PostgreSQL и миграция с нуля | `migrate up` на пустой временной БД | версия `1`, `dirty=false`, таблица `users` создана | +| Применение и откат | `migrate up → down → up` на временной БД | все три команды PASS; в конце версия `1`, `dirty=false` | +| Базовый API, Basic, Bearer, доступ, logout | `make test` | PASS, публичный сценарий lab2 | +| Сохранность данных и действующей сессии | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS с прежним токеном после рестарта API и БД | +| Срок жизни сессии | API с `SESSION_TTL_SECONDS=2`, вход, чтение, ожидание 3 с, чтение | после истечения получен `401`; затем восстановлен TTL 3600 | +| Повтор миграции и volume | повторный запуск API после рестарта | данные сохранены, версия миграции осталась `1` | -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +`make test` также проверяет неверный пароль, Basic на бизнес-маршруте и невозможность доступа по одному `X-User-Id`. Токены и пароли не сохранялись в отчёте. ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. - -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Воздействие | Ожидание | Наблюдение | +| --- | --- | --- | +| `scripts/restart.sh` | API и БД перезапускаются без удаления volume | время запуска БД изменилось с `18:55:34Z` на `18:56:24Z`, API — с `18:55:38Z` на `18:56:27Z`; число пользователей/чатов/сообщений/миграций было и осталось `6/2/3/1`; persistence-сценарий PASS | +| TTL 2 секунды | истёкший токен отклоняется | после 3 секунд `401` | +| `migrate down` на временной БД | откат начальной схемы | версия `1` удалена; повторный `up` снова создал схему | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Одна копия API и одна БД не дают отказоустойчивости при потере хоста/volume. Рестарт с сохранённым volume проверен, резервное копирование и восстановление не реализованы. Redis/Valkey, нагрузочные измерения и EXPLAIN относятся к уровню 4 и здесь не заявлены. HTTP и пароль в локальном `.env` предназначены только для изолированного учебного стенда с синтетическими данными. `DATABASE_URL` доступен оператору Docker в окружении контейнера. Для удалённого размещения нужны TLS и управление секретами. -- 2.54.0 From 7f7b0c0ce049309e50b339f3a97572b955b804fa Mon Sep 17 00:00:00 2001 From: Dima Date: Wed, 23 Sep 2026 22:03:34 +0300 Subject: [PATCH 6/9] =?UTF-8?q?=D0=92=D0=BE=D1=81=D1=81=D1=82=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=82=D1=8C=20=D1=81=D1=82=D1=80=D1=83=D0=BA?= =?UTF-8?q?=D1=82=D1=83=D1=80=D1=83=20=D0=BE=D1=82=D1=87=D1=91=D1=82=D0=B0?= =?UTF-8?q?=20=D0=B8=20=D0=BF=D1=80=D0=B8=D0=BB=D0=BE=D0=B6=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=B4=D0=BE=D0=BA=D0=B0=D0=B7=D0=B0=D1=82=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=D1=81=D1=82=D0=B2=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 44 +++++++++++++++++++++++++---------------- evidence/lab2-checks.md | 22 +++++++++++++++++++++ 2 files changed, 49 insertions(+), 17 deletions(-) create mode 100644 evidence/lab2-checks.md diff --git a/REPORT.md b/REPORT.md index 6438fd52..1d4d9935 100644 --- a/REPORT.md +++ b/REPORT.md @@ -3,12 +3,14 @@ - Автор, группа: Гришко Дмитрий Михайлович, БВТ2303 - Целевая оценка: **3** - Ветка: `solution/BVT2303-grishko` +- Commit/PR: коммиты реализации `a858d33`, `c384018`, `08cb1cb`, `c6db0aa`; PR пока не создавался - Источники: [задание](README.md), [контракт](contracts/README.md), [проверки](tests/README.md), [golang-migrate](https://github.com/golang-migrate/migrate), документация PostgreSQL и Go -- Зависимости: Go 1.22.2, PostgreSQL 16.10, `pgx/v5`, `golang-migrate/v4`, `x/crypto/scrypt`, `google/uuid`; помощь ИИ: OpenAI Codex — реализация и проверка кода +- Зависимости: Go 1.22.2, PostgreSQL 16.10, `pgx/v5`, `golang-migrate/v4`, `x/crypto/scrypt`, `google/uuid`; +- помощь ИИ: OpenAI Codex — реализация и проверка кода ## Запуск из чистого clone -Нужны Docker Engine с Compose, Python 3.9+ и Make. Go нужен для `go test ./...` вне контейнера. Команды приведены для Linux/WSL в корне репозитория. +Нужны Docker Engine с Compose, Python 3.9+, Make и OpenSSL для генерации локального пароля. Go нужен для `go test ./...` вне контейнера. Команды приведены для Linux/WSL в корне репозитория. ```sh cp .env.example .env @@ -21,7 +23,10 @@ make test-persistence ACTION_SCRIPT=scripts/restart.sh go test ./... ``` -`.env` содержит локальный пароль и исключён из Git. База доступна только внутри Compose-сети; HTTP API опубликован на `127.0.0.1:8080`. Миграции `up` применяются автоматически перед запуском HTTP-сервера. Они встроены в бинарник из `src/migrations`. Применение вручную: `docker compose --env-file .env run --rm --no-deps api migrate up` при уже запущенной БД. Откат **одной** версии, удаляющий таблицы и данные этой начальной миграции, выполняется только сознательно при остановленном API: `docker compose --env-file .env stop api`, затем `docker compose --env-file .env run --rm --no-deps api migrate down`. +Во второй строке `openssl rand -hex 24` генерирует 24 случайных байта в шестнадцатеричном виде. Команда рассчитана на Linux/WSL; вместо неё можно вручную заменить `POSTGRES_PASSWORD` в `.env` длинным случайным значением. + +- База доступна только внутри Compose-сети; +- HTTP API опубликован на `127.0.0.1:8080`. Миграции `up` применяются автоматически перед запуском HTTP-сервера. Они встроены в бинарник из `src/migrations`. Применение вручную: `docker compose --env-file .env run --rm --no-deps api migrate up` при уже запущенной БД. Откат **одной** версии, удаляющий таблицы и данные этой начальной миграции, выполняется только сознательно при остановленном API: `docker compose --env-file .env stop api`, затем `docker compose --env-file .env run --rm --no-deps api migrate down`. Безопасная остановка: `docker compose --env-file .env down` — volume сохранится. Намеренное удаление учебных данных: `docker compose --env-file .env down -v`. После смены пароля в `.env` для уже инициализированного volume надо отдельно менять пароль роли PostgreSQL; изменение одной строки `.env` существующую роль не обновляет. @@ -47,27 +52,32 @@ HTTP-клиент → Go net/http API → PostgreSQL (именованный vol `golang-migrate` хранит номер версии и признак незавершённой миграции в `schema_migrations`. Есть ровно одна парная миграция: `000001_initial.up.sql` и `.down.sql`; повторный `up` не создаёт данные заново. Миграция `down` проверялась только на отдельной временной БД. +Переменные из `.env.example`: `POSTGRES_DB` задаёт имя базы, `POSTGRES_USER` — роль, `POSTGRES_PASSWORD` — локальный пароль для PostgreSQL и строки подключения API, `SESSION_TTL_SECONDS` — срок жизни сессии (по умолчанию 3600 секунд). `APP_HOST=0.0.0.0` и `APP_PORT=8080` задаются в Compose; внешний порт привязан к `127.0.0.1`. + ## Доказательства критериев -| Критерий | Команда/сценарий | Результат | -| --- | --- | --- | -| Контракт и код | `make check`, `go test ./...`, `go vet ./...` | PASS | -| PostgreSQL и миграция с нуля | `migrate up` на пустой временной БД | версия `1`, `dirty=false`, таблица `users` создана | -| Применение и откат | `migrate up → down → up` на временной БД | все три команды PASS; в конце версия `1`, `dirty=false` | -| Базовый API, Basic, Bearer, доступ, logout | `make test` | PASS, публичный сценарий lab2 | -| Сохранность данных и действующей сессии | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS с прежним токеном после рестарта API и БД | -| Срок жизни сессии | API с `SESSION_TTL_SECONDS=2`, вход, чтение, ожидание 3 с, чтение | после истечения получен `401`; затем восстановлен TTL 3600 | -| Повтор миграции и volume | повторный запуск API после рестарта | данные сохранены, версия миграции осталась `1` | +| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | +| --- | --- | --- | --- | +| Публичный smoke, API lab1 с новой аутентификацией | `make test` | `PASS: lab2 public API scenario`; проверены Basic, Bearer, членство, пагинация, logout | [Протокол проверок](evidence/lab2-checks.md), [публичный сценарий](tests/smoke.py) | +| PostgreSQL: пользователи, чаты, членство, сообщения, ключи и индексы | запуск на чистом volume, SQL-проверка схемы | версия миграции `1`, `dirty=false`; отдельной колонки `password_salt` нет | [Миграция up](src/migrations/000001_initial.up.sql), [протокол](evidence/lab2-checks.md) | +| Атомарное создание чата | создание чата в `make test`, проверка границы транзакции в коде | чат и участники записываются в одной транзакции; публичный сценарий PASS | [Код транзакции](src/chat.go), [протокол](evidence/lab2-checks.md) | +| Password KDF, Basic только для входа, Bearer, expiry и logout | `make test`; отдельный запуск с TTL 2 секунды | неверный пароль и старый заголовок отклонены; истёкший токен получил `401` | [Код](src/user.go), [сессии](src/session.go), [протокол](evidence/lab2-checks.md) | +| Сохранность данных и действующей сессии | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS с прежним токеном после рестарта API и БД | [Hook](scripts/restart.sh), [протокол](evidence/lab2-checks.md) | +| Повторный запуск миграции и откат | `up → down → up` на временной БД; повторный запуск API | схема удалена и создана вновь; версия `1`, `dirty=false`; дубликатов данных на рабочем volume нет | [Миграция down](src/migrations/000001_initial.down.sql), [протокол](evidence/lab2-checks.md) | +| Стенд, volumes и секреты | `docker compose --env-file .env config --quiet`, `git check-ignore .env` | API и БД healthy; именованный volume; `.env` исключён из Git | [Compose](compose.yaml), [протокол](evidence/lab2-checks.md) | +| Локальные проверки кода | `make check`, `go test ./...`, `go vet ./...` | PASS | [Протокол](evidence/lab2-checks.md), [unit-тесты](src/security_test.go) | `make test` также проверяет неверный пароль, Basic на бизнес-маршруте и невозможность доступа по одному `X-User-Id`. Токены и пароли не сохранялись в отчёте. ## Эксперименты и отказы -| Воздействие | Ожидание | Наблюдение | -| --- | --- | --- | -| `scripts/restart.sh` | API и БД перезапускаются без удаления volume | время запуска БД изменилось с `18:55:34Z` на `18:56:24Z`, API — с `18:55:38Z` на `18:56:27Z`; число пользователей/чатов/сообщений/миграций было и осталось `6/2/3/1`; persistence-сценарий PASS | -| TTL 2 секунды | истёкший токен отклоняется | после 3 секунд `401` | -| `migrate down` на временной БД | откат начальной схемы | версия `1` удалена; повторный `up` снова создал схему | +Среда проверки: Windows 11 / WSL2 Ubuntu, Docker Engine 28.5.1, Compose 2.40.2, один API-контейнер и один PostgreSQL 16.10. Для сценария сохранности использовались синтетические пользователи, два чата и три сообщения. Выполнено по одному прогону smoke, persistence, expiry и отката миграции. Нагрузочный профиль, concurrency, RPS, p50/p95/p99 и CPU/RAM для оценки «3» не измерялись; эти показатели не используются как доказательство производительности. + +| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +| --- | --- | --- | --- | +| `scripts/restart.sh` | API и БД перезапускаются без удаления volume | время запуска БД изменилось с `18:55:34Z` на `18:56:24Z`, API — с `18:55:38Z` на `18:56:27Z`; счётчики `users/chats/messages/migrations` остались `6/2/3/1`; persistence-сценарий PASS | hook завершился примерно за 13,3 с; подтверждённые данные и действующий токен сохранились | +| TTL 2 секунды | истёкший токен отклоняется | после ожидания 3 с получен `401` | восстановление не требуется; отзыв по времени без потери данных | +| `migrate down` на отдельной временной БД | таблицы удаляются; повторный `up` восстанавливает пустую схему | после `down` таблица `users` отсутствовала; после `up` версия `1`, `dirty=false` | примерно 5 с на `down → up`; временная БД была пустой, рабочие данные не затронуты | ## Ограничения и следующие шаги diff --git a/evidence/lab2-checks.md b/evidence/lab2-checks.md new file mode 100644 index 00000000..815017dd --- /dev/null +++ b/evidence/lab2-checks.md @@ -0,0 +1,22 @@ +# Протокол локальных проверок lab2 + +Дата: 2026-09-23. Данные синтетические. Токены и пароли не записывались. + +| Команда | Наблюдаемый результат | +| --- | --- | +| `make check` | `PASS: offline skeleton structure, local refs and Python syntax` | +| `go test ./...` | `ok messenger/src` | +| `go vet ./...` | завершилось с кодом 0 | +| `docker compose --env-file .env config --quiet` | завершилось с кодом 0 | +| `docker compose --env-file .env up -d --build --wait` на чистом volume | API и PostgreSQL стали `healthy` | +| `make test` | `PASS: lab2 public API scenario` | +| `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS: persistence preserved confirmed data and existing session` | +| `git check-ignore -v .env` | `.gitignore:2:.env` | + +На чистой базе `SELECT version,dirty FROM schema_migrations` вернул `1|f`. Проверка `information_schema.columns` показала 0 колонок с именем `password_salt` у `users`. + +Для проверки реального рестарта сравнивались `docker inspect .State.StartedAt` до и после `scripts/restart.sh`. PostgreSQL: `2026-09-23T18:55:34.777895314Z → 18:56:24.003370053Z`. API: `18:55:38.494275638Z → 18:56:27.57666394Z`. SQL-счётчики пользователей, чатов, сообщений и записей миграции до и после: `6|2|3|1 → 6|2|3|1`. В persistence-тесте прежний токен прочитал прежнее сообщение после этого рестарта. + +При `SESSION_TTL_SECONDS=2` сессия сразу позволила прочитать `/api/v1/users/me`, а через 3 секунды получила `401`. После проверки обычный TTL 3600 секунд был восстановлен. + +Для отката создана отдельная пустая БД `lab2_migrate_check`. Команды `migrate up → down → up` завершились успешно. После первого `up`: версия `1|f`, `password_salt` отсутствует. После `down`: `to_regclass('public.users') IS NULL` вернул `t`. После повторного `up`: версия снова `1|f`. Временная БД удалена; рабочий volume не откатывался. -- 2.54.0 From a9dda2054084cb22936feb90d197462c7dc74809 Mon Sep 17 00:00:00 2001 From: TAskMAster339 Date: Fri, 25 Sep 2026 20:17:56 +0300 Subject: [PATCH 7/9] refactor: update project structure --- .gitignore | 4 + Dockerfile | 4 +- Makefile | 51 +- compose.yaml | 29 + go.mod | 1 + src/backend/handlers/chat_http.go | 128 ++ src/backend/handlers/http.go | 143 ++ src/backend/handlers/message_http.go | 105 ++ src/backend/handlers/session.go | 98 ++ src/backend/handlers/user_http.go | 80 + src/backend/main.go | 122 ++ src/{ => backend/repositories}/chat.go | 30 +- src/backend/repositories/cursor.go | 15 + src/{ => backend/repositories}/database.go | 20 +- src/backend/repositories/errors.go | 21 + src/backend/repositories/health.go | 19 + src/{ => backend/repositories}/message.go | 27 +- .../migrations/000001_initial.down.sql | 0 .../migrations/000001_initial.up.sql | 0 src/backend/repositories/session.go | 32 + src/backend/repositories/user.go | 57 + src/backend/services/chat.go | 134 ++ src/backend/services/errors.go | 16 + src/backend/services/health.go | 19 + src/backend/services/message.go | 107 ++ src/backend/services/password.go | 59 + src/backend/services/session.go | 76 + src/backend/services/user.go | 70 + src/backend/tests/concurrency_test.go | 217 +++ src/backend/tests/integration_test.go | 67 + src/backend/tests/message_handler_test.go | 276 ++++ src/backend/tests/message_store_test.go | 69 + src/backend/tests/security_test.go | 79 + src/backend/tests/test_fixture_test.go | 123 ++ src/backend/tests/types_test.go | 12 + src/backend/tests/user_handler_test.go | 137 ++ src/chat_get_handler.go | 105 -- src/chat_handler.go | 194 --- src/chat_list_handler.go | 219 --- src/chat_subresource_handler.go | 41 - src/current_user_handler.go | 58 - src/frontend/.dockerignore | 2 + src/frontend/.gitignore | 8 + src/frontend/Dockerfile | 12 + src/frontend/index.html | 12 + src/frontend/package-lock.json | 1288 +++++++++++++++++ src/frontend/package.json | 23 + src/frontend/src/App.tsx | 200 +++ src/frontend/src/Pagination.tsx | 24 + src/frontend/src/api.ts | 127 ++ src/frontend/src/main.tsx | 10 + src/frontend/src/styles.css | 103 ++ src/frontend/src/useCursorPage.ts | 55 + src/frontend/tsconfig.json | 14 + src/frontend/vite.config.ts | 18 + src/main.go | 218 --- src/message_handler.go | 184 --- src/message_list_handler.go | 229 --- src/security_test.go | 54 - src/session.go | 157 -- src/user.go | 80 - src/user_handler.go | 155 -- 62 files changed, 4273 insertions(+), 1764 deletions(-) create mode 100644 src/backend/handlers/chat_http.go create mode 100644 src/backend/handlers/http.go create mode 100644 src/backend/handlers/message_http.go create mode 100644 src/backend/handlers/session.go create mode 100644 src/backend/handlers/user_http.go create mode 100644 src/backend/main.go rename src/{ => backend/repositories}/chat.go (80%) create mode 100644 src/backend/repositories/cursor.go rename src/{ => backend/repositories}/database.go (78%) create mode 100644 src/backend/repositories/errors.go create mode 100644 src/backend/repositories/health.go rename src/{ => backend/repositories}/message.go (73%) rename src/{ => backend/repositories}/migrations/000001_initial.down.sql (100%) rename src/{ => backend/repositories}/migrations/000001_initial.up.sql (100%) create mode 100644 src/backend/repositories/session.go create mode 100644 src/backend/repositories/user.go create mode 100644 src/backend/services/chat.go create mode 100644 src/backend/services/errors.go create mode 100644 src/backend/services/health.go create mode 100644 src/backend/services/message.go create mode 100644 src/backend/services/password.go create mode 100644 src/backend/services/session.go create mode 100644 src/backend/services/user.go create mode 100644 src/backend/tests/concurrency_test.go create mode 100644 src/backend/tests/integration_test.go create mode 100644 src/backend/tests/message_handler_test.go create mode 100644 src/backend/tests/message_store_test.go create mode 100644 src/backend/tests/security_test.go create mode 100644 src/backend/tests/test_fixture_test.go create mode 100644 src/backend/tests/types_test.go create mode 100644 src/backend/tests/user_handler_test.go delete mode 100644 src/chat_get_handler.go delete mode 100644 src/chat_handler.go delete mode 100644 src/chat_list_handler.go delete mode 100644 src/chat_subresource_handler.go delete mode 100644 src/current_user_handler.go create mode 100644 src/frontend/.dockerignore create mode 100644 src/frontend/.gitignore create mode 100644 src/frontend/Dockerfile create mode 100644 src/frontend/index.html create mode 100644 src/frontend/package-lock.json create mode 100644 src/frontend/package.json create mode 100644 src/frontend/src/App.tsx create mode 100644 src/frontend/src/Pagination.tsx create mode 100644 src/frontend/src/api.ts create mode 100644 src/frontend/src/main.tsx create mode 100644 src/frontend/src/styles.css create mode 100644 src/frontend/src/useCursorPage.ts create mode 100644 src/frontend/tsconfig.json create mode 100644 src/frontend/vite.config.ts delete mode 100644 src/main.go delete mode 100644 src/message_handler.go delete mode 100644 src/message_list_handler.go delete mode 100644 src/security_test.go delete mode 100644 src/session.go delete mode 100644 src/user.go delete mode 100644 src/user_handler.go diff --git a/.gitignore b/.gitignore index b5a71896..5e6fc457 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,10 @@ target/ bin/ obj/ coverage/ +.vite/ +*.tsbuildinfo +*.test +*.out *.log .DS_Store .idea/ diff --git a/Dockerfile b/Dockerfile index 399c36b8..c34078af 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,7 +6,7 @@ COPY go.mod go.sum ./ RUN go mod download -COPY src ./src +COPY src/backend ./src/backend RUN CGO_ENABLED=0 \ GOOS=linux \ @@ -14,7 +14,7 @@ RUN CGO_ENABLED=0 \ -trimpath \ -ldflags="-s -w" \ -o /out/messenger \ - ./src + ./src/backend FROM debian:12.15-slim diff --git a/Makefile b/Makefile index 9ecb223e..696bb747 100644 --- a/Makefile +++ b/Makefile @@ -1,26 +1,47 @@ -PYTHON ?= python3 -BASE_URL ?= http://localhost:8080 -CA_FILE ?= +PYTHON ?= python3 +BASE_URL ?= http://localhost:8080 +CA_FILE ?= ACTION_SCRIPT ?= +COMPOSE = docker compose --env-file .env TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence +.PHONY: help app-up app-down app-logs check validate test test-backend load test-persistence help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "app-up: build and start API, database and frontend (http://localhost:5173)" + @echo "app-down: stop the application and keep PostgreSQL data" + @echo "app-logs: follow service logs" + @echo "check: offline contract structure" + @echo "validate: full OpenAPI validation (install requirements-dev.txt first)" + @echo "test: public API smoke test (run app-up first)" + @echo "test-backend: Go tests with PostgreSQL and race detection in isolated schemas" + @echo "test-persistence ACTION_SCRIPT=scripts/restart.sh: restart API and DB, verify saved data and session (run app-up first)" + @echo "load: synthetic API writes" -check: - $(PYTHON) scripts/check_contract.py +app-up: + $(COMPOSE) up -d --build --wait -validate: - $(PYTHON) scripts/validate_openapi.py +app-down: + $(COMPOSE) down +app-logs: + $(COMPOSE) logs -f + +check: + $(PYTHON) scripts/check_contract.py + +validate: + $(PYTHON) scripts/validate_openapi.py + test: $(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) -load: - $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) - -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) +test-backend: + $(COMPOSE) --profile test run --build --rm backend-tests + +load: + $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +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) diff --git a/compose.yaml b/compose.yaml index 32630e1c..6beb20b9 100644 --- a/compose.yaml +++ b/compose.yaml @@ -29,6 +29,35 @@ services: interval: 5s timeout: 3s retries: 20 + backend-tests: + profiles: ["test"] + build: + context: . + target: builder + environment: + TEST_DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable + depends_on: + db: + condition: service_healthy + command: ["go", "test", "-race", "-count=1", "-v", "./src/backend/..."] + frontend: + build: + context: ./src/frontend + environment: + API_PROXY_TARGET: http://api:8080 + ports: + - "127.0.0.1:5173:5173" + volumes: + - ./src/frontend:/app + - /app/node_modules + depends_on: + api: + condition: service_healthy + healthcheck: + test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:5173/').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"] + interval: 5s + timeout: 3s + retries: 20 volumes: postgres_data: diff --git a/go.mod b/go.mod index ff023359..21aef4ba 100644 --- a/go.mod +++ b/go.mod @@ -18,5 +18,6 @@ require ( github.com/jackc/puddle/v2 v2.2.1 // indirect go.uber.org/atomic v1.7.0 // indirect golang.org/x/sync v0.5.0 // indirect + golang.org/x/sys v0.19.0 // indirect golang.org/x/text v0.14.0 // indirect ) diff --git a/src/backend/handlers/chat_http.go b/src/backend/handlers/chat_http.go new file mode 100644 index 00000000..ef5edf8f --- /dev/null +++ b/src/backend/handlers/chat_http.go @@ -0,0 +1,128 @@ +package handlers + +import ( + "net/http" + "strings" + + "github.com/google/uuid" + "messenger/src/backend/services" +) + +type createChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +func createChatHandler(chats *services.ChatService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodPost { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + userID, ok := requestUserID(w, r, requestID) + if !ok { + return + } + if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { + writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID) + return + } + var request createChatRequest + if err := decodeJSONBody(r, &request); err != nil { + writeError(w, 400, "invalid_request", "invalid JSON body", requestID) + return + } + chat, err := chats.Create(r.Context(), userID, request.Title, request.MemberIDs) + if err != nil { + writeServiceError(w, err, requestID) + return + } + writeJSON(w, 201, chat) + } +} + +func getChatHandler(chats *services.ChatService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodGet { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + userID, ok := requestUserID(w, r, requestID) + if !ok { + return + } + chatID := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/") + if chatID == "" || strings.Contains(chatID, "/") { + writeError(w, 400, "invalid_request", "invalid chat id", requestID) + return + } + if _, err := uuid.Parse(chatID); err != nil { + writeError(w, 400, "invalid_request", "invalid chat id", requestID) + return + } + chat, err := chats.Get(r.Context(), userID, chatID) + if err != nil { + writeServiceError(w, err, requestID) + return + } + writeJSON(w, 200, chat) + } +} + +func listChatsHandler(chats *services.ChatService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodGet { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + userID, ok := requestUserID(w, r, requestID) + if !ok { + return + } + limit, cursor, ok := pageParams(w, r, requestID) + if !ok { + return + } + page, err := chats.List(r.Context(), userID, limit, cursor) + if err != nil { + writeServiceError(w, err, requestID) + return + } + writeJSON(w, 200, page) + } +} + +func chatCollectionHandler(chats *services.ChatService) http.HandlerFunc { + create := createChatHandler(chats) + list := listChatsHandler(chats) + return func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + list(w, r) + } else { + create(w, r) + } + } +} + +func chatSubresourceHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc { + get := getChatHandler(chats) + createMessage := createMessageHandler(chats, messages) + listMessages := listMessagesHandler(chats, messages) + return func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/messages") { + if r.Method == http.MethodGet { + listMessages(w, r) + } else { + createMessage(w, r) + } + return + } + get(w, r) + } +} diff --git a/src/backend/handlers/http.go b/src/backend/handlers/http.go new file mode 100644 index 00000000..aed7daad --- /dev/null +++ b/src/backend/handlers/http.go @@ -0,0 +1,143 @@ +package handlers + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "log" + "net/http" + "strconv" + "time" + + "messenger/src/backend/services" +) + +type healthResponse struct { + Status string `json:"status"` +} +type apiError struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} +type errorResponse struct { + Error apiError `json:"error"` +} + +func newRequestID() string { + bytes := make([]byte, 16) + if _, err := rand.Read(bytes); err != nil { + return "request-id-generation-failed" + } + return hex.EncodeToString(bytes) +} + +func writeError(w http.ResponseWriter, status int, code, message, requestID string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + response := errorResponse{Error: apiError{Code: code, Message: message, RequestID: requestID}} + if err := json.NewEncoder(w).Encode(response); err != nil { + log.Printf("failed to encode error response: %v", err) + } +} + +func writeServiceError(w http.ResponseWriter, err error, requestID string) { + var invalid services.InvalidInput + switch { + case errors.As(err, &invalid): + writeError(w, 400, "invalid_request", invalid.Message, requestID) + case errors.Is(err, services.ErrConflict): + writeError(w, 409, "conflict", "username is already taken", requestID) + case errors.Is(err, services.ErrUnknownUser): + writeError(w, 401, "unauthorized", "unknown user", requestID) + case errors.Is(err, services.ErrChatNotFound): + writeError(w, 404, "not_found", "chat not found", requestID) + default: + writeError(w, 503, "unavailable", "database unavailable", requestID) + } +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if err := json.NewEncoder(w).Encode(value); err != nil { + log.Printf("failed to encode response: %v", err) + } +} + +func requestUserID(w http.ResponseWriter, r *http.Request, requestID string) (string, bool) { + id := currentUserID(r) + if id == "" { + writeError(w, 401, "unauthorized", "valid Bearer session is required", requestID) + return "", false + } + return id, true +} + +func pageParams(w http.ResponseWriter, r *http.Request, requestID string) (int, string, bool) { + limit := 50 + if values, exists := r.URL.Query()["limit"]; exists { + if len(values) != 1 || values[0] == "" { + writeError(w, 400, "invalid_request", "invalid limit", requestID) + return 0, "", false + } + parsed, err := strconv.Atoi(values[0]) + if err != nil { + writeError(w, 400, "invalid_request", "limit must be between 1 and 100", requestID) + return 0, "", false + } + limit = parsed + } + var cursor string + if values, exists := r.URL.Query()["cursor"]; exists { + if len(values) != 1 || values[0] == "" { + writeError(w, 400, "invalid_request", "invalid cursor", requestID) + return 0, "", false + } + cursor = values[0] + } + return limit, cursor, true +} + +func healthHandler(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodGet { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + writeJSON(w, 200, healthResponse{"ok"}) +} + +func readyHandler(health *services.HealthService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodGet { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + if err := health.Ready(ctx); err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + writeJSON(w, 200, healthResponse{"ok"}) + } +} + +func NewRouter(health *services.HealthService, users *services.UserService, sessions *services.SessionService, chats *services.ChatService, messages *services.MessageService) http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("/health/live", healthHandler) + mux.HandleFunc("/health/ready", readyHandler(health)) + mux.Handle("/api/v1/users", createUserHandler(users)) + mux.Handle("/api/v1/auth/sessions", sessionHandler(sessions)) + mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions))) + mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(users))) + mux.Handle("/api/v1/chats", authRequired(sessions, chatCollectionHandler(chats))) + mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages))) + return mux +} diff --git a/src/backend/handlers/message_http.go b/src/backend/handlers/message_http.go new file mode 100644 index 00000000..576d6844 --- /dev/null +++ b/src/backend/handlers/message_http.go @@ -0,0 +1,105 @@ +package handlers + +import ( + "net/http" + "strings" + + "github.com/google/uuid" + "messenger/src/backend/services" +) + +type createMessageRequest struct { + Text string `json:"text"` +} + +func messageChatID(path string) (string, bool) { + const prefix = "/api/v1/chats/" + const suffix = "/messages" + if !strings.HasPrefix(path, prefix) || !strings.HasSuffix(path, suffix) { + return "", false + } + chatID := strings.TrimSuffix(strings.TrimPrefix(path, prefix), suffix) + if chatID == "" || strings.Contains(chatID, "/") { + return "", false + } + return chatID, true +} + +func createMessageHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodPost { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + userID, ok := requestUserID(w, r, requestID) + if !ok { + return + } + chatID, ok := messageChatID(r.URL.Path) + if !ok { + writeError(w, 400, "invalid_request", "invalid chat id", requestID) + return + } + if _, err := uuid.Parse(chatID); err != nil { + writeError(w, 400, "invalid_request", "invalid chat id", requestID) + return + } + chat, err := chats.Get(r.Context(), userID, chatID) + if err != nil { + writeServiceError(w, err, requestID) + return + } + if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { + writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID) + return + } + var request createMessageRequest + if err := decodeJSONBody(r, &request); err != nil { + writeError(w, 400, "invalid_request", "invalid JSON body", requestID) + return + } + message, err := messages.Create(r.Context(), userID, chat, request.Text) + if err != nil { + writeServiceError(w, err, requestID) + return + } + writeJSON(w, 201, message) + } +} + +func listMessagesHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodGet { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + userID, ok := requestUserID(w, r, requestID) + if !ok { + return + } + chatID, ok := messageChatID(r.URL.Path) + if !ok { + writeError(w, 400, "invalid_request", "invalid chat id", requestID) + return + } + chat, err := chats.Get(r.Context(), userID, chatID) + if err != nil { + writeServiceError(w, err, requestID) + return + } + limit, cursor, ok := pageParams(w, r, requestID) + if !ok { + return + } + page, err := messages.List(r.Context(), userID, chat, limit, cursor) + if err != nil { + writeServiceError(w, err, requestID) + return + } + writeJSON(w, 200, page) + } +} diff --git a/src/backend/handlers/session.go b/src/backend/handlers/session.go new file mode 100644 index 00000000..b965db10 --- /dev/null +++ b/src/backend/handlers/session.go @@ -0,0 +1,98 @@ +package handlers + +import ( + "context" + "errors" + "net/http" + "strings" + "time" + + "messenger/src/backend/services" +) + +type authenticatedUserKey struct{} + +func currentUserID(r *http.Request) string { + id, _ := r.Context().Value(authenticatedUserKey{}).(string) + return id +} + +func authRequired(sessions *services.SessionService, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authorization := r.Header.Get("Authorization") + if !strings.HasPrefix(authorization, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(authorization, "Bearer ")) == "" { + unauthorized(w, "Bearer", newRequestID()) + return + } + user, err := sessions.User(r.Context(), strings.TrimPrefix(authorization, "Bearer ")) + if errors.Is(err, services.ErrInvalidSession) { + unauthorized(w, "Bearer", newRequestID()) + return + } + if err != nil { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), authenticatedUserKey{}, user.ID))) + }) +} + +func unauthorized(w http.ResponseWriter, scheme, requestID string) { + w.Header().Set("X-Request-Id", requestID) + if scheme == "Basic" { + w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`) + } else { + w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`) + } + writeError(w, 401, "unauthorized", "invalid credentials", requestID) +} + +func sessionHandler(sessions *services.SessionService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodPost { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + username, password, ok := r.BasicAuth() + if !ok || r.ContentLength > 0 { + unauthorized(w, "Basic", requestID) + return + } + user, token, expires, valid, err := sessions.Login(r.Context(), username, password) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + if !valid { + unauthorized(w, "Basic", requestID) + return + } + writeJSON(w, 201, struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User any `json:"user"` + }{token, "Bearer", expires, user}) + } +} + +func logoutHandler(sessions *services.SessionService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodDelete { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + if err := sessions.Revoke(r.Context(), token); err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + w.WriteHeader(204) + } +} diff --git a/src/backend/handlers/user_http.go b/src/backend/handlers/user_http.go new file mode 100644 index 00000000..e298f48f --- /dev/null +++ b/src/backend/handlers/user_http.go @@ -0,0 +1,80 @@ +package handlers + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "messenger/src/backend/services" +) + +type createUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` +} + +func decodeJSONBody(r *http.Request, destination any) error { + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(destination); err != nil { + return err + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + if err != nil { + return err + } + return fmt.Errorf("more than one JSON value") + } + return nil +} + +func createUserHandler(users *services.UserService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodPost { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { + writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID) + return + } + var request createUserRequest + if err := decodeJSONBody(r, &request); err != nil { + writeError(w, 400, "invalid_request", "invalid JSON body", requestID) + return + } + user, err := users.Create(r.Context(), request.Username, request.DisplayName, request.Password) + if err != nil { + writeServiceError(w, err, requestID) + return + } + writeJSON(w, 201, user) + } +} + +func currentUserHandler(users *services.UserService) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodGet { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + userID, ok := requestUserID(w, r, requestID) + if !ok { + return + } + user, err := users.Get(r.Context(), userID) + if err != nil { + writeServiceError(w, err, requestID) + return + } + writeJSON(w, 200, user) + } +} diff --git a/src/backend/main.go b/src/backend/main.go new file mode 100644 index 00000000..010dd4d4 --- /dev/null +++ b/src/backend/main.go @@ -0,0 +1,122 @@ +package main + +import ( + "context" + "errors" + "log" + "messenger/src/backend/handlers" + "messenger/src/backend/repositories" + "messenger/src/backend/services" + "net" + "net/http" + "os" + "os/signal" + "syscall" + "time" +) + +func serverAddress() string { + host := os.Getenv("APP_HOST") + if host == "" { + host = "0.0.0.0" + } + + port := os.Getenv("APP_PORT") + if port == "" { + port = "8080" + } + + return net.JoinHostPort(host, port) +} + +func main() { + if len(os.Args) > 1 { + if len(os.Args) == 2 && os.Args[1] == "healthcheck" { + client := http.Client{Timeout: 2 * time.Second} + response, err := client.Get("http://127.0.0.1:8080/health/ready") + if err != nil { + os.Exit(1) + } + response.Body.Close() + if response.StatusCode != http.StatusOK { + os.Exit(1) + } + return + } + if len(os.Args) != 3 || os.Args[1] != "migrate" || (os.Args[2] != "up" && os.Args[2] != "down") { + log.Fatal("usage: messenger migrate up|down") + } + url, err := repositories.DatabaseURL() + if err != nil { + log.Fatal(err) + } + if err = repositories.RunMigrations(url, os.Args[2]); err != nil { + log.Fatal(err) + } + log.Printf("migration %s complete", os.Args[2]) + return + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + db, err := repositories.OpenDatabase(ctx) + cancel() + if err != nil { + log.Fatalf("database initialization failed: %v", err) + } + defer db.Close() + userStore := repositories.NewUserStore(db) + chatStore := repositories.NewChatStore(db) + messageStore := repositories.NewMessageStore(db) + ttl, err := services.SessionTTL() + if err != nil { + log.Fatal(err) + } + userService := services.NewUserService(userStore) + sessionService := services.NewSessionService(userService, repositories.NewSessionStore(db), ttl) + chatService := services.NewChatService(chatStore) + messageService := services.NewMessageService(messageStore) + mux := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db)), userService, sessionService, chatService, messageService) + + server := &http.Server{ + Addr: serverAddress(), + Handler: mux, + } + + shutdownContext, stop := signal.NotifyContext( + context.Background(), + os.Interrupt, + syscall.SIGTERM, + ) + defer stop() + + serverErrors := make(chan error, 1) + + go func() { + log.Printf("server is listening on %s", server.Addr) + + if err := server.ListenAndServe(); err != nil && + !errors.Is(err, http.ErrServerClosed) { + serverErrors <- err + } + }() + + select { + case err := <-serverErrors: + log.Printf("server error: %v", err) + + case <-shutdownContext.Done(): + log.Printf("shutdown signal received") + + shutdownDeadline, cancel := context.WithTimeout( + context.Background(), + 10*time.Second, + ) + defer cancel() + + if err := server.Shutdown(shutdownDeadline); err != nil { + log.Printf("graceful shutdown failed: %v", err) + return + } + + log.Printf("server stopped gracefully") + } +} diff --git a/src/chat.go b/src/backend/repositories/chat.go similarity index 80% rename from src/chat.go rename to src/backend/repositories/chat.go index d7601788..fd45d468 100644 --- a/src/chat.go +++ b/src/backend/repositories/chat.go @@ -1,4 +1,4 @@ -package main +package repositories import ( "context" @@ -16,17 +16,17 @@ type Chat struct { CreatedAt time.Time `json:"created_at"` } -type chatStore struct { +type ChatStore struct { db *pgxpool.Pool } -func newChatStore(db *pgxpool.Pool) *chatStore { - return &chatStore{db: db} +func NewChatStore(db *pgxpool.Pool) *ChatStore { + return &ChatStore{db: db} } -var errUnknownMember = errors.New("unknown member") +var ErrUnknownMember = errors.New("unknown member") -func (s *chatStore) create(ctx context.Context, title string, memberIDs []string) (Chat, error) { +func (s *ChatStore) Create(ctx context.Context, title string, memberIDs []string) (Chat, error) { membersCopy := append([]string(nil), memberIDs...) chat := Chat{ ID: uuid.New().String(), @@ -46,7 +46,7 @@ func (s *chatStore) create(ctx context.Context, title string, memberIDs []string return Chat{}, err } if !exists { - return Chat{}, errUnknownMember + return Chat{}, ErrUnknownMember } } if _, err = tx.Exec(ctx, "INSERT INTO chats(id,title,created_at) VALUES($1,$2,$3)", chat.ID, title, chat.CreatedAt); err != nil { @@ -63,7 +63,7 @@ func (s *chatStore) create(ctx context.Context, title string, memberIDs []string return chat, nil } -func (s *chatStore) getByID(ctx context.Context, id string) (Chat, error) { +func (s *ChatStore) GetByID(ctx context.Context, id string) (Chat, error) { var chat Chat err := s.db.QueryRow(ctx, "SELECT id,title,created_at FROM chats WHERE id=$1", id).Scan(&chat.ID, &chat.Title, &chat.CreatedAt) if err != nil { @@ -85,17 +85,7 @@ func (s *chatStore) getByID(ctx context.Context, id string) (Chat, error) { return chat, rows.Err() } -func (s *chatStore) isMember(chat Chat, userID string) bool { - for _, memberID := range chat.MemberIDs { - if memberID == userID { - return true - } - } - - return false -} - -func (s *chatStore) listPageForUser(ctx context.Context, userID string, cursor *chatCursor, limit int) ([]Chat, bool, error) { +func (s *ChatStore) ListPageForUser(ctx context.Context, userID string, cursor *ChatCursor, limit int) ([]Chat, bool, error) { afterTime := time.Time{} afterID := "00000000-0000-0000-0000-000000000000" if cursor != nil { @@ -123,7 +113,7 @@ func (s *chatStore) listPageForUser(ctx context.Context, userID string, cursor * chats = chats[:limit] } for i := range chats { - chat, err := s.getByID(ctx, chats[i].ID) + chat, err := s.GetByID(ctx, chats[i].ID) if err != nil { return nil, false, err } diff --git a/src/backend/repositories/cursor.go b/src/backend/repositories/cursor.go new file mode 100644 index 00000000..05f3f7dd --- /dev/null +++ b/src/backend/repositories/cursor.go @@ -0,0 +1,15 @@ +package repositories + +import "time" + +type ChatCursor struct { + UserID string `json:"user_id"` + CreatedAt time.Time `json:"created_at"` + ChatID string `json:"chat_id"` +} + +type MessageCursor struct { + ChatID string `json:"chat_id"` + CreatedAt time.Time `json:"created_at"` + MessageID string `json:"message_id"` +} diff --git a/src/database.go b/src/backend/repositories/database.go similarity index 78% rename from src/database.go rename to src/backend/repositories/database.go index 42ce63eb..0ac06f88 100644 --- a/src/database.go +++ b/src/backend/repositories/database.go @@ -1,4 +1,4 @@ -package main +package repositories import ( "context" @@ -12,7 +12,6 @@ import ( "github.com/golang-migrate/migrate/v4" pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5" "github.com/golang-migrate/migrate/v4/source/iofs" - "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" _ "github.com/jackc/pgx/v5/stdlib" ) @@ -20,7 +19,7 @@ import ( //go:embed migrations/*.sql var migrationFiles embed.FS -func databaseURL() (string, error) { +func DatabaseURL() (string, error) { if path := os.Getenv("DATABASE_URL_FILE"); path != "" { data, err := os.ReadFile(path) if err != nil { @@ -34,8 +33,8 @@ func databaseURL() (string, error) { return "", errors.New("DATABASE_URL_FILE or DATABASE_URL is required") } -func openDatabase(ctx context.Context) (*pgxpool.Pool, error) { - url, err := databaseURL() +func OpenDatabase(ctx context.Context) (*pgxpool.Pool, error) { + url, err := DatabaseURL() if err != nil { return nil, err } @@ -53,16 +52,16 @@ func openDatabase(ctx context.Context) (*pgxpool.Pool, error) { db.Close() return nil, err } - if err = runMigrations(url, "up"); err != nil { + if err = RunMigrations(url, "up"); err != nil { db.Close() return nil, err } return db, nil } -// runMigrations uses versioned up/down SQL embedded in the API binary. +// RunMigrations uses versioned up/down SQL embedded in the API binary. // "down" rolls back exactly one version and is an explicit operator command. -func runMigrations(url, direction string) error { +func RunMigrations(url, direction string) error { source, err := iofs.New(migrationFiles, "migrations") if err != nil { return err @@ -92,8 +91,3 @@ func runMigrations(url, direction string) error { } return err } - -func uniqueViolation(err error) bool { - var pgerr *pgconn.PgError - return errors.As(err, &pgerr) && pgerr.Code == "23505" -} diff --git a/src/backend/repositories/errors.go b/src/backend/repositories/errors.go new file mode 100644 index 00000000..6741083e --- /dev/null +++ b/src/backend/repositories/errors.go @@ -0,0 +1,21 @@ +package repositories + +import ( + "errors" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +func NotFound(err error) bool { + return errors.Is(err, pgx.ErrNoRows) +} + +func CheckViolation(err error) bool { + var pgerr *pgconn.PgError + return errors.As(err, &pgerr) && pgerr.Code == "23514" +} + +func UniqueViolation(err error) bool { + var pgerr *pgconn.PgError + return errors.As(err, &pgerr) && pgerr.Code == "23505" +} diff --git a/src/backend/repositories/health.go b/src/backend/repositories/health.go new file mode 100644 index 00000000..693a3b93 --- /dev/null +++ b/src/backend/repositories/health.go @@ -0,0 +1,19 @@ +package repositories + +import ( + "context" + + "github.com/jackc/pgx/v5/pgxpool" +) + +type HealthStore struct { + db *pgxpool.Pool +} + +func NewHealthStore(db *pgxpool.Pool) *HealthStore { + return &HealthStore{db: db} +} + +func (s *HealthStore) Ping(ctx context.Context) error { + return s.db.Ping(ctx) +} diff --git a/src/message.go b/src/backend/repositories/message.go similarity index 73% rename from src/message.go rename to src/backend/repositories/message.go index ac812bb9..eb05b504 100644 --- a/src/message.go +++ b/src/backend/repositories/message.go @@ -1,4 +1,4 @@ -package main +package repositories import ( "context" @@ -16,15 +16,15 @@ type Message struct { CreatedAt time.Time `json:"created_at"` } -type messageStore struct { +type MessageStore struct { db *pgxpool.Pool } -func newMessageStore(db *pgxpool.Pool) *messageStore { - return &messageStore{db: db} +func NewMessageStore(db *pgxpool.Pool) *MessageStore { + return &MessageStore{db: db} } -func (s *messageStore) create( +func (s *MessageStore) Create( ctx context.Context, chatID string, senderID string, @@ -42,23 +42,10 @@ func (s *messageStore) create( return message, err } -func messageLess(left Message, right Message) bool { - if left.CreatedAt.Equal(right.CreatedAt) { - return left.ID < right.ID - } - - return left.CreatedAt.Before(right.CreatedAt) -} - -func messageAfterCursor(message Message, cursor messageCursor) bool { - return message.CreatedAt.After(cursor.CreatedAt) || - (message.CreatedAt.Equal(cursor.CreatedAt) && message.ID > cursor.MessageID) -} - -func (s *messageStore) listPageByChat( +func (s *MessageStore) ListPageByChat( ctx context.Context, chatID string, - cursor *messageCursor, + cursor *MessageCursor, limit int, ) ([]Message, bool, error) { afterTime := time.Time{} diff --git a/src/migrations/000001_initial.down.sql b/src/backend/repositories/migrations/000001_initial.down.sql similarity index 100% rename from src/migrations/000001_initial.down.sql rename to src/backend/repositories/migrations/000001_initial.down.sql diff --git a/src/migrations/000001_initial.up.sql b/src/backend/repositories/migrations/000001_initial.up.sql similarity index 100% rename from src/migrations/000001_initial.up.sql rename to src/backend/repositories/migrations/000001_initial.up.sql diff --git a/src/backend/repositories/session.go b/src/backend/repositories/session.go new file mode 100644 index 00000000..469e50ff --- /dev/null +++ b/src/backend/repositories/session.go @@ -0,0 +1,32 @@ +package repositories + +import ( + "context" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +type SessionStore struct { + db *pgxpool.Pool +} + +func NewSessionStore(db *pgxpool.Pool) *SessionStore { + return &SessionStore{db: db} +} + +func (s *SessionStore) Create(ctx context.Context, tokenHash []byte, userID string, expires time.Time) error { + _, err := s.db.Exec(ctx, "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,$3)", tokenHash, userID, expires) + return err +} + +func (s *SessionStore) User(ctx context.Context, tokenHash []byte) (User, error) { + var user User + err := s.db.QueryRow(ctx, `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()`, tokenHash).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + return user, err +} + +func (s *SessionStore) Revoke(ctx context.Context, tokenHash []byte) error { + _, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", tokenHash) + return err +} diff --git a/src/backend/repositories/user.go b/src/backend/repositories/user.go new file mode 100644 index 00000000..d71b6aa4 --- /dev/null +++ b/src/backend/repositories/user.go @@ -0,0 +1,57 @@ +package repositories + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +type UserStore struct { + db *pgxpool.Pool +} + +func NewUserStore(db *pgxpool.Pool) *UserStore { + return &UserStore{db: db} +} + +func (s *UserStore) Create(ctx context.Context, username, displayName string, passwordHash []byte) (User, error) { + user := User{ + ID: uuid.New().String(), + Username: username, + DisplayName: displayName, + CreatedAt: time.Now().UTC().Truncate(time.Microsecond), + } + + _, err := s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,$2,$3,$4,$5)", user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt) + return user, err +} + +func (s *UserStore) GetByID(ctx context.Context, id string) (User, error) { + var user User + err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at FROM users WHERE id=$1", id).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + return user, err +} + +func (s *UserStore) GetCredentials(ctx context.Context, username string) (User, []byte, error) { + var user User + var packedHash []byte + err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &packedHash) + if errors.Is(err, pgx.ErrNoRows) { + return User{}, nil, nil + } + if err != nil { + return User{}, nil, err + } + return user, packedHash, nil +} diff --git a/src/backend/services/chat.go b/src/backend/services/chat.go new file mode 100644 index 00000000..2c947fc0 --- /dev/null +++ b/src/backend/services/chat.go @@ -0,0 +1,134 @@ +package services + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "strconv" + "strings" + "unicode/utf8" + + "github.com/google/uuid" + "messenger/src/backend/repositories" +) + +type ChatPage struct { + Items []repositories.Chat `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type ChatService struct { + chats *repositories.ChatStore +} + +func NewChatService(chats *repositories.ChatStore) *ChatService { + return &ChatService{chats: chats} +} + +func ChatHasMember(chat repositories.Chat, userID string) bool { + for _, memberID := range chat.MemberIDs { + if memberID == userID { + return true + } + } + return false +} + +func (s *ChatService) Create(ctx context.Context, currentUserID, title string, memberIDs []string) (repositories.Chat, error) { + if strings.TrimSpace(title) == "" { + return repositories.Chat{}, InvalidInput{"title must not be blank"} + } + if utf8.RuneCountInString(title) > 100 { + return repositories.Chat{}, InvalidInput{"title is too long"} + } + if len(memberIDs) == 0 || len(memberIDs) > 100 { + return repositories.Chat{}, InvalidInput{"member_ids must contain from 1 to 100 users"} + } + seen := make(map[string]struct{}, len(memberIDs)) + for _, memberID := range memberIDs { + if _, err := uuid.Parse(memberID); err != nil { + return repositories.Chat{}, InvalidInput{"member_ids must contain valid UUIDs"} + } + if _, exists := seen[memberID]; exists { + return repositories.Chat{}, InvalidInput{"member_ids must not contain duplicates"} + } + seen[memberID] = struct{}{} + } + if _, exists := seen[currentUserID]; !exists { + return repositories.Chat{}, InvalidInput{"current user must be a chat member"} + } + chat, err := s.chats.Create(ctx, title, memberIDs) + if errors.Is(err, repositories.ErrUnknownMember) { + return repositories.Chat{}, InvalidInput{"all members must be existing users"} + } + return chat, err +} + +func (s *ChatService) Get(ctx context.Context, currentUserID, chatID string) (repositories.Chat, error) { + chat, err := s.chats.GetByID(ctx, chatID) + if repositories.NotFound(err) { + return repositories.Chat{}, ErrChatNotFound + } + if err != nil { + return repositories.Chat{}, err + } + if !ChatHasMember(chat, currentUserID) { + return repositories.Chat{}, ErrChatNotFound + } + return chat, nil +} + +func EncodeChatCursor(cursor repositories.ChatCursor) (string, error) { + data, err := json.Marshal(cursor) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(data), nil +} + +func DecodeChatCursor(value string) (repositories.ChatCursor, error) { + data, err := base64.RawURLEncoding.DecodeString(value) + if err != nil { + return repositories.ChatCursor{}, err + } + var cursor repositories.ChatCursor + if err := json.Unmarshal(data, &cursor); err != nil { + return repositories.ChatCursor{}, err + } + if cursor.UserID == "" || cursor.ChatID == "" || cursor.CreatedAt.IsZero() { + return repositories.ChatCursor{}, strconv.ErrSyntax + } + return cursor, nil +} + +func (s *ChatService) List(ctx context.Context, userID string, limit int, cursorToken string) (ChatPage, error) { + if limit < 1 || limit > 100 { + return ChatPage{}, InvalidInput{"limit must be between 1 and 100"} + } + var cursor *repositories.ChatCursor + if cursorToken != "" { + decoded, err := DecodeChatCursor(cursorToken) + if err != nil || decoded.UserID != userID { + return ChatPage{}, InvalidInput{"invalid cursor"} + } + cursor = &decoded + } + items, more, err := s.chats.ListPageForUser(ctx, userID, cursor, limit) + if err != nil { + return ChatPage{}, err + } + page := ChatPage{Items: items} + if page.Items == nil { + page.Items = []repositories.Chat{} + } + if more { + last := items[len(items)-1] + next, err := EncodeChatCursor(repositories.ChatCursor{UserID: userID, CreatedAt: last.CreatedAt, ChatID: last.ID}) + if err != nil { + return ChatPage{}, err + } + page.NextCursor = &next + } + return page, nil +} diff --git a/src/backend/services/errors.go b/src/backend/services/errors.go new file mode 100644 index 00000000..aa5d632d --- /dev/null +++ b/src/backend/services/errors.go @@ -0,0 +1,16 @@ +package services + +import "errors" + +var ( + ErrConflict = errors.New("conflict") + ErrUnknownUser = errors.New("unknown user") + ErrChatNotFound = errors.New("chat not found") + ErrInvalidSession = errors.New("invalid session") +) + +type InvalidInput struct { + Message string +} + +func (e InvalidInput) Error() string { return e.Message } diff --git a/src/backend/services/health.go b/src/backend/services/health.go new file mode 100644 index 00000000..8c2c55a2 --- /dev/null +++ b/src/backend/services/health.go @@ -0,0 +1,19 @@ +package services + +import ( + "context" + + "messenger/src/backend/repositories" +) + +type HealthService struct { + health *repositories.HealthStore +} + +func NewHealthService(health *repositories.HealthStore) *HealthService { + return &HealthService{health: health} +} + +func (s *HealthService) Ready(ctx context.Context) error { + return s.health.Ping(ctx) +} diff --git a/src/backend/services/message.go b/src/backend/services/message.go new file mode 100644 index 00000000..0364ca39 --- /dev/null +++ b/src/backend/services/message.go @@ -0,0 +1,107 @@ +package services + +import ( + "context" + "encoding/base64" + "encoding/json" + "strconv" + "strings" + "unicode/utf8" + + "messenger/src/backend/repositories" +) + +type MessagePage struct { + Items []repositories.Message `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type MessageService struct { + messages *repositories.MessageStore +} + +func NewMessageService(messages *repositories.MessageStore) *MessageService { + return &MessageService{messages: messages} +} + +func (s *MessageService) Create(ctx context.Context, userID string, chat repositories.Chat, text string) (repositories.Message, error) { + if !ChatHasMember(chat, userID) { + return repositories.Message{}, ErrChatNotFound + } + if strings.TrimSpace(text) == "" { + return repositories.Message{}, InvalidInput{"text must not be blank"} + } + if utf8.RuneCountInString(text) > 4000 { + return repositories.Message{}, InvalidInput{"text is too long"} + } + return s.messages.Create(ctx, chat.ID, userID, text) +} + +func MessageLess(left, right repositories.Message) bool { + if left.CreatedAt.Equal(right.CreatedAt) { + return left.ID < right.ID + } + return left.CreatedAt.Before(right.CreatedAt) +} + +func MessageAfterCursor(message repositories.Message, cursor repositories.MessageCursor) bool { + return message.CreatedAt.After(cursor.CreatedAt) || + (message.CreatedAt.Equal(cursor.CreatedAt) && message.ID > cursor.MessageID) +} + +func EncodeMessageCursor(cursor repositories.MessageCursor) (string, error) { + data, err := json.Marshal(cursor) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(data), nil +} + +func DecodeMessageCursor(value string) (repositories.MessageCursor, error) { + data, err := base64.RawURLEncoding.DecodeString(value) + if err != nil { + return repositories.MessageCursor{}, err + } + var cursor repositories.MessageCursor + if err := json.Unmarshal(data, &cursor); err != nil { + return repositories.MessageCursor{}, err + } + if cursor.ChatID == "" || cursor.MessageID == "" || cursor.CreatedAt.IsZero() { + return repositories.MessageCursor{}, strconv.ErrSyntax + } + return cursor, nil +} + +func (s *MessageService) List(ctx context.Context, userID string, chat repositories.Chat, limit int, cursorToken string) (MessagePage, error) { + if !ChatHasMember(chat, userID) { + return MessagePage{}, ErrChatNotFound + } + if limit < 1 || limit > 100 { + return MessagePage{}, InvalidInput{"limit must be between 1 and 100"} + } + var cursor *repositories.MessageCursor + if cursorToken != "" { + decoded, err := DecodeMessageCursor(cursorToken) + if err != nil || decoded.ChatID != chat.ID { + return MessagePage{}, InvalidInput{"invalid cursor"} + } + cursor = &decoded + } + items, more, err := s.messages.ListPageByChat(ctx, chat.ID, cursor, limit) + if err != nil { + return MessagePage{}, err + } + page := MessagePage{Items: items} + if page.Items == nil { + page.Items = []repositories.Message{} + } + if more { + last := items[len(items)-1] + next, err := EncodeMessageCursor(repositories.MessageCursor{ChatID: chat.ID, CreatedAt: last.CreatedAt, MessageID: last.ID}) + if err != nil { + return MessagePage{}, err + } + page.NextCursor = &next + } + return page, nil +} diff --git a/src/backend/services/password.go b/src/backend/services/password.go new file mode 100644 index 00000000..94201a31 --- /dev/null +++ b/src/backend/services/password.go @@ -0,0 +1,59 @@ +package services + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + + "golang.org/x/crypto/argon2" +) + +const ( + argonMemory uint32 = 64 * 1024 + argonIterations uint32 = 3 + argonParallelism uint8 = 2 + passwordSaltSize = 16 + passwordHashSize = 32 +) + +// HashPassword stores the salt and Argon2id parameters in one PHC-encoded value. +func HashPassword(password string) ([]byte, error) { + salt := make([]byte, passwordSaltSize) + if _, err := rand.Read(salt); err != nil { + return nil, err + } + hash := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, passwordHashSize) + encoded := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, argonMemory, argonIterations, argonParallelism, + base64.RawStdEncoding.EncodeToString(salt), + base64.RawStdEncoding.EncodeToString(hash), + ) + return []byte(encoded), nil +} + +func VerifyPassword(password string, encoded []byte) (bool, error) { + parts := strings.Split(string(encoded), "$") + if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != fmt.Sprintf("v=%d", argon2.Version) { + return false, errors.New("invalid password hash format") + } + var memory, iterations uint32 + var parallelism uint8 + if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism); err != nil || + fmt.Sprintf("m=%d,t=%d,p=%d", memory, iterations, parallelism) != parts[3] || + memory < 8*1024 || memory > 128*1024 || iterations < 1 || iterations > 10 || parallelism < 1 || parallelism > 8 { + return false, errors.New("invalid password hash parameters") + } + salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4]) + if err != nil || len(salt) != passwordSaltSize { + return false, errors.New("invalid password salt") + } + expected, err := base64.RawStdEncoding.Strict().DecodeString(parts[5]) + if err != nil || len(expected) != passwordHashSize { + return false, errors.New("invalid password hash") + } + actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, passwordHashSize) + return subtle.ConstantTimeCompare(expected, actual) == 1, nil +} diff --git a/src/backend/services/session.go b/src/backend/services/session.go new file mode 100644 index 00000000..b93a13bd --- /dev/null +++ b/src/backend/services/session.go @@ -0,0 +1,76 @@ +package services + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "os" + "strconv" + "time" + + "messenger/src/backend/repositories" +) + +type SessionService struct { + users *UserService + sessions *repositories.SessionStore + ttl time.Duration +} + +func SessionTTL() (time.Duration, error) { + value := os.Getenv("SESSION_TTL_SECONDS") + if value == "" { + return time.Hour, nil + } + seconds, err := strconv.Atoi(value) + if err != nil || seconds < 1 { + return 0, errors.New("invalid SESSION_TTL_SECONDS") + } + return time.Duration(seconds) * time.Second, nil +} + +func NewSessionService(users *UserService, sessions *repositories.SessionStore, ttl time.Duration) *SessionService { + return &SessionService{users: users, sessions: sessions, ttl: ttl} +} + +func (s *SessionService) Login(ctx context.Context, username, password string) (repositories.User, string, time.Time, bool, error) { + user, valid, err := s.users.Authenticate(ctx, username, password) + if err != nil || !valid { + return repositories.User{}, "", time.Time{}, valid, err + } + token, expires, err := s.CreateForUser(ctx, user.ID) + if err != nil { + return repositories.User{}, "", time.Time{}, false, err + } + return user, token, expires, true, nil +} + +func (s *SessionService) CreateForUser(ctx context.Context, userID string) (string, time.Time, error) { + raw := make([]byte, 32) + if _, err := rand.Read(raw); err != nil { + return "", time.Time{}, err + } + token := hex.EncodeToString(raw) + hash := sha256.Sum256([]byte(token)) + expires := time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond) + if err := s.sessions.Create(ctx, hash[:], userID, expires); err != nil { + return "", time.Time{}, err + } + return token, expires, nil +} + +func (s *SessionService) User(ctx context.Context, token string) (repositories.User, error) { + hash := sha256.Sum256([]byte(token)) + user, err := s.sessions.User(ctx, hash[:]) + if repositories.NotFound(err) { + return repositories.User{}, ErrInvalidSession + } + return user, err +} + +func (s *SessionService) Revoke(ctx context.Context, token string) error { + hash := sha256.Sum256([]byte(token)) + return s.sessions.Revoke(ctx, hash[:]) +} diff --git a/src/backend/services/user.go b/src/backend/services/user.go new file mode 100644 index 00000000..950baf11 --- /dev/null +++ b/src/backend/services/user.go @@ -0,0 +1,70 @@ +package services + +import ( + "context" + "regexp" + "strings" + "unicode/utf8" + + "messenger/src/backend/repositories" +) + +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +type UserService struct { + users *repositories.UserStore +} + +func NewUserService(users *repositories.UserStore) *UserService { + return &UserService{users: users} +} + +func (s *UserService) Create(ctx context.Context, username, displayName, password string) (repositories.User, error) { + if !usernamePattern.MatchString(username) { + return repositories.User{}, InvalidInput{"username must contain 3-32 lowercase latin letters, digits or underscores"} + } + if strings.TrimSpace(displayName) == "" { + return repositories.User{}, InvalidInput{"display_name must not be blank"} + } + if utf8.RuneCountInString(displayName) > 100 { + return repositories.User{}, InvalidInput{"display_name is too long"} + } + if strings.TrimSpace(password) == "" || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 { + return repositories.User{}, InvalidInput{"password must contain 12-128 characters"} + } + hash, err := HashPassword(password) + if err != nil { + return repositories.User{}, err + } + user, err := s.users.Create(ctx, username, displayName, hash) + if repositories.UniqueViolation(err) { + return repositories.User{}, ErrConflict + } + if repositories.CheckViolation(err) { + return repositories.User{}, InvalidInput{"invalid user fields"} + } + return user, err +} + +func (s *UserService) Get(ctx context.Context, id string) (repositories.User, error) { + user, err := s.users.GetByID(ctx, id) + if repositories.NotFound(err) { + return repositories.User{}, ErrUnknownUser + } + return user, err +} + +func (s *UserService) Authenticate(ctx context.Context, username, password string) (repositories.User, bool, error) { + if !usernamePattern.MatchString(username) || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 { + return repositories.User{}, false, nil + } + user, packedHash, err := s.users.GetCredentials(ctx, username) + if err != nil || packedHash == nil { + return repositories.User{}, false, err + } + valid, err := VerifyPassword(password, packedHash) + if err != nil { + return repositories.User{}, false, err + } + return user, valid, nil +} diff --git a/src/backend/tests/concurrency_test.go b/src/backend/tests/concurrency_test.go new file mode 100644 index 00000000..b0204e9f --- /dev/null +++ b/src/backend/tests/concurrency_test.go @@ -0,0 +1,217 @@ +package tests + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "messenger/src/backend/repositories" + "net/http" + "net/http/httptest" + "strconv" + "sync" + "testing" +) + +func TestConcurrentMessageCreation(t *testing.T) { + fixture := newTestFixture(t) + userStore, chatStore := fixture.users, fixture.chats + + const clientsCount = 10 + const messagesPerClient = 10 + const expectedMessages = clientsCount * messagesPerClient + + memberIDs := make([]string, 0, clientsCount) + users := make([]User, 0, clientsCount) + + for i := range clientsCount { + user, created := createTestUser(t, userStore, + "user"+strconv.Itoa(i), + "Пользователь "+strconv.Itoa(i), + ) + + if !created { + t.Fatalf("failed to create test user %d", i) + } + + users = append(users, user) + memberIDs = append(memberIDs, user.ID) + } + + chat := createTestChat(t, chatStore, + "Конкурентный чат", + memberIDs, + ) + + server := httptest.NewServer(fixture.router) + defer server.Close() + + client := server.Client() + tokens := make([]string, clientsCount) + for i, user := range users { + request := httptest.NewRequest(http.MethodGet, "/", nil) + authorizeTestRequest(t, fixture, request, user.ID) + tokens[i] = request.Header.Get("Authorization") + } + + var waitGroup sync.WaitGroup + messageIDs := make(chan string, expectedMessages) + errors := make(chan error, expectedMessages) + + for clientIndex := range clientsCount { + waitGroup.Add(1) + + go func(index int) { + defer waitGroup.Done() + + for messageIndex := range messagesPerClient { + body := fmt.Appendf(nil, + `{"text":"client-%d message-%d"}`, + index, + messageIndex, + ) + + request, err := http.NewRequest( + http.MethodPost, + server.URL+"/api/v1/chats/"+chat.ID+"/messages", + bytes.NewReader(body), + ) + if err != nil { + errors <- fmt.Errorf( + "client %d: create request: %w", + index, + err, + ) + continue + } + + request.Header.Set("Content-Type", "application/json") + request.Header.Set("Authorization", tokens[index]) + + response, err := client.Do(request) + if err != nil { + errors <- fmt.Errorf( + "client %d: send request: %w", + index, + err, + ) + continue + } + + responseBody, readErr := io.ReadAll(response.Body) + response.Body.Close() + + if readErr != nil { + errors <- fmt.Errorf( + "client %d: read response: %w", + index, + readErr, + ) + continue + } + + if response.StatusCode != http.StatusCreated { + errors <- fmt.Errorf( + "client %d: expected status %d, got %d; body: %s", + index, + http.StatusCreated, + response.StatusCode, + string(responseBody), + ) + continue + } + + var message repositories.Message + + if err := json.Unmarshal(responseBody, &message); err != nil { + errors <- fmt.Errorf( + "client %d: decode response: %w", + index, + err, + ) + continue + } + + if message.ID == "" { + errors <- fmt.Errorf( + "client %d: response contains empty message ID", + index, + ) + continue + } + + messageIDs <- message.ID + } + }(clientIndex) + } + + waitGroup.Wait() + + close(errors) + close(messageIDs) + + for err := range errors { + t.Error(err) + } + + createdIDs := make(map[string]bool) + + for messageID := range messageIDs { + if createdIDs[messageID] { + t.Fatalf("duplicate message ID returned: %s", messageID) + } + + createdIDs[messageID] = true + } + + if len(createdIDs) != expectedMessages { + t.Fatalf( + "expected %d unique created messages, got %d", + expectedMessages, + len(createdIDs), + ) + } + + // Дополнительно проверяем историю через HTTP API. + request, err := http.NewRequest( + http.MethodGet, + server.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=100", + nil, + ) + if err != nil { + t.Fatalf("create history request: %v", err) + } + + request.Header.Set("Authorization", tokens[0]) + + response, err := client.Do(request) + if err != nil { + t.Fatalf("request message history: %v", err) + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + body, _ := io.ReadAll(response.Body) + + t.Fatalf( + "expected history status %d, got %d; body: %s", + http.StatusOK, + response.StatusCode, + string(body), + ) + } + + var page messagePage + + if err := json.NewDecoder(response.Body).Decode(&page); err != nil { + t.Fatalf("decode message history: %v", err) + } + + if len(page.Items) != expectedMessages { + t.Fatalf( + "expected %d messages in history, got %d", + expectedMessages, + len(page.Items), + ) + } +} diff --git a/src/backend/tests/integration_test.go b/src/backend/tests/integration_test.go new file mode 100644 index 00000000..15631020 --- /dev/null +++ b/src/backend/tests/integration_test.go @@ -0,0 +1,67 @@ +package tests + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "testing" +) + +func TestMessengerWorkflow(t *testing.T) { + router := newTestFixture(t).router + + call := func(method, path, body, auth string, expected int) map[string]any { + t.Helper() + request := httptest.NewRequest(method, path, bytes.NewBufferString(body)) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if auth != "" { + request.Header.Set("Authorization", auth) + } + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if response.Code != expected { + t.Fatalf("%s %s: status %d, want %d: %s", method, path, response.Code, expected, response.Body.String()) + } + if response.Header().Get("X-Request-Id") == "" { + t.Fatalf("%s %s: missing request ID", method, path) + } + if response.Code == http.StatusNoContent { + return nil + } + var result map[string]any + if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + return result + } + + user := call("POST", "/api/v1/users", `{"username":"alice","display_name":"Алиса","password":"lab2-test-password"}`, "", 201) + userID := user["id"].(string) + basic := "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:lab2-test-password")) + session := call("POST", "/api/v1/auth/sessions", "", basic, 201) + bearer := "Bearer " + session["token"].(string) + call("GET", "/api/v1/users/me", "", bearer, 200) + chat := call("POST", "/api/v1/chats", `{"title":"Тестовый чат","member_ids":["`+userID+`"]}`, bearer, 201) + chatID := chat["id"].(string) + path := "/api/v1/chats/" + chatID + "/messages" + for i := 0; i < 3; i++ { + call("POST", path, `{"text":"message"}`, bearer, 201) + } + page1 := call("GET", path+"?limit=2", "", bearer, 200) + first := page1["items"].([]any) + if len(first) != 2 || page1["next_cursor"] == nil { + t.Fatalf("unexpected first page: %v", page1) + } + page2 := call("GET", path+"?limit=2&cursor="+url.QueryEscape(page1["next_cursor"].(string)), "", bearer, 200) + second := page2["items"].([]any) + if len(second) != 1 || page2["next_cursor"] != nil || first[0].(map[string]any)["id"] == second[0].(map[string]any)["id"] { + t.Fatalf("unexpected second page: %v", page2) + } + call("DELETE", "/api/v1/auth/sessions/current", "", bearer, 204) + call("GET", "/api/v1/users/me", "", bearer, 401) +} diff --git a/src/backend/tests/message_handler_test.go b/src/backend/tests/message_handler_test.go new file mode 100644 index 00000000..b5c6958b --- /dev/null +++ b/src/backend/tests/message_handler_test.go @@ -0,0 +1,276 @@ +package tests + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func TestCreateMessageBlankText(t *testing.T) { + fixture := newTestFixture(t) + userStore, chatStore, messageStore := fixture.users, fixture.chats, fixture.messages + + user, created := createTestUser(t, userStore, "alice", "Алиса") + if !created { + t.Fatal("expected user to be created") + } + + chat := createTestChat(t, chatStore, + "Тестовый чат", + []string{user.ID}, + ) + + handler := fixture.router + + request := httptest.NewRequest( + http.MethodPost, + "/api/v1/chats/"+chat.ID+"/messages", + strings.NewReader(`{"text":" \t\n"}`), + ) + request.Header.Set("Content-Type", "application/json") + authorizeTestRequest(t, fixture, request, user.ID) + + response := httptest.NewRecorder() + + handler.ServeHTTP(response, request) + + if response.Code != http.StatusBadRequest { + t.Fatalf( + "expected status %d, got %d; body: %s", + http.StatusBadRequest, + response.Code, + response.Body.String(), + ) + } + + if response.Header().Get("X-Request-Id") == "" { + t.Fatal("expected non-empty X-Request-Id header") + } + + if !strings.Contains( + response.Body.String(), + `"code":"invalid_request"`, + ) { + t.Fatalf( + "expected invalid_request error code, got body: %s", + response.Body.String(), + ) + } + + messages := listTestMessages(t, messageStore, chat.ID) + + if len(messages) != 0 { + t.Fatalf( + "expected no messages to be stored, got %d", + len(messages), + ) + } +} +func TestCreateMessageFromChatOutsider(t *testing.T) { + fixture := newTestFixture(t) + userStore, chatStore, messageStore := fixture.users, fixture.chats, fixture.messages + + alice, created := createTestUser(t, userStore, "alice", "Алиса") + if !created { + t.Fatal("expected Alice to be created") + } + + bob, created := createTestUser(t, userStore, "bob", "Боб") + if !created { + t.Fatal("expected Bob to be created") + } + + chat := createTestChat(t, chatStore, + "Чат Алисы", + []string{alice.ID}, + ) + + handler := fixture.router + + request := httptest.NewRequest( + http.MethodPost, + "/api/v1/chats/"+chat.ID+"/messages", + strings.NewReader(`{"text":"Сообщение чужому чату"}`), + ) + request.Header.Set("Content-Type", "application/json") + authorizeTestRequest(t, fixture, request, bob.ID) + + response := httptest.NewRecorder() + + handler.ServeHTTP(response, request) + + if response.Code != http.StatusNotFound { + t.Fatalf( + "expected status %d, got %d; body: %s", + http.StatusNotFound, + response.Code, + response.Body.String(), + ) + } + + if response.Header().Get("X-Request-Id") == "" { + t.Fatal("expected non-empty X-Request-Id header") + } + + if !strings.Contains( + response.Body.String(), + `"code":"not_found"`, + ) { + t.Fatalf( + "expected not_found error code, got body: %s", + response.Body.String(), + ) + } + + messages := listTestMessages(t, messageStore, chat.ID) + + if len(messages) != 0 { + t.Fatalf( + "expected no messages to be stored, got %d", + len(messages), + ) + } +} +func TestListMessagesPagination(t *testing.T) { + fixture := newTestFixture(t) + userStore, chatStore, messageStore := fixture.users, fixture.chats, fixture.messages + + user, created := createTestUser(t, userStore, "alice", "Алиса") + if !created { + t.Fatal("expected user to be created") + } + + chat := createTestChat(t, chatStore, + "Тестовый чат", + []string{user.ID}, + ) + + first := createTestMessage(t, messageStore, chat.ID, user.ID, "Первое сообщение") + second := createTestMessage(t, messageStore, chat.ID, user.ID, "Второе сообщение") + third := createTestMessage(t, messageStore, chat.ID, user.ID, "Третье сообщение") + + expectedIDs := map[string]bool{ + first.ID: true, + second.ID: true, + third.ID: true, + } + + handler := fixture.router + + // Запрашиваем только два сообщения из трёх. + firstRequest := httptest.NewRequest( + http.MethodGet, + "/api/v1/chats/"+chat.ID+"/messages?limit=2", + nil, + ) + authorizeTestRequest(t, fixture, firstRequest, user.ID) + + firstResponse := httptest.NewRecorder() + + handler.ServeHTTP(firstResponse, firstRequest) + + if firstResponse.Code != http.StatusOK { + t.Fatalf( + "expected first page status %d, got %d; body: %s", + http.StatusOK, + firstResponse.Code, + firstResponse.Body.String(), + ) + } + + var firstPage messagePage + + if err := json.NewDecoder(firstResponse.Body).Decode(&firstPage); err != nil { + t.Fatalf("failed to decode first page: %v", err) + } + + if len(firstPage.Items) != 2 { + t.Fatalf( + "expected 2 messages on first page, got %d", + len(firstPage.Items), + ) + } + + if firstPage.NextCursor == nil || *firstPage.NextCursor == "" { + t.Fatal("expected non-empty next cursor on first page") + } + + // Проверяем, что сообщения на первой странице уникальны + // и принадлежат исходному набору. + seenIDs := make(map[string]bool) + + for _, message := range firstPage.Items { + if !expectedIDs[message.ID] { + t.Fatalf("unexpected message ID on first page: %s", message.ID) + } + + if seenIDs[message.ID] { + t.Fatalf("duplicate message on first page: %s", message.ID) + } + + seenIDs[message.ID] = true + } + + // Используем cursor первой страницы для получения второй. + secondRequest := httptest.NewRequest( + http.MethodGet, + "/api/v1/chats/"+chat.ID+"/messages?limit=2&cursor="+ + url.QueryEscape(*firstPage.NextCursor), + nil, + ) + authorizeTestRequest(t, fixture, secondRequest, user.ID) + + secondResponse := httptest.NewRecorder() + + handler.ServeHTTP(secondResponse, secondRequest) + + if secondResponse.Code != http.StatusOK { + t.Fatalf( + "expected second page status %d, got %d; body: %s", + http.StatusOK, + secondResponse.Code, + secondResponse.Body.String(), + ) + } + + var secondPage messagePage + + if err := json.NewDecoder(secondResponse.Body).Decode(&secondPage); err != nil { + t.Fatalf("failed to decode second page: %v", err) + } + + if len(secondPage.Items) != 1 { + t.Fatalf( + "expected 1 message on second page, got %d", + len(secondPage.Items), + ) + } + + if secondPage.NextCursor != nil { + t.Fatalf("expected second page to be final, got cursor %q", *secondPage.NextCursor) + } + + // Проверяем, что вторая страница не повторяет первую. + for _, message := range secondPage.Items { + if seenIDs[message.ID] { + t.Fatalf("message repeated on second page: %s", message.ID) + } + + if !expectedIDs[message.ID] { + t.Fatalf("unexpected message ID on second page: %s", message.ID) + } + + seenIDs[message.ID] = true + } + + if len(seenIDs) != len(expectedIDs) { + t.Fatalf( + "pagination lost messages: expected %d unique messages, got %d", + len(expectedIDs), + len(seenIDs), + ) + } +} diff --git a/src/backend/tests/message_store_test.go b/src/backend/tests/message_store_test.go new file mode 100644 index 00000000..3d8c2c5b --- /dev/null +++ b/src/backend/tests/message_store_test.go @@ -0,0 +1,69 @@ +package tests + +import ( + "context" + "messenger/src/backend/services" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestMessageLessUsesIDForEqualTimestamps(t *testing.T) { + createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC) + first := Message{ID: "a", CreatedAt: createdAt} + second := Message{ID: "b", CreatedAt: createdAt} + if !services.MessageLess(first, second) || services.MessageLess(second, first) { + t.Fatal("equal timestamps must be ordered by ID") + } +} + +func TestListPageByChatUsesCursorAndLimit(t *testing.T) { + f := newTestFixture(t) + user, _ := createTestUser(t, f.users, "alice", "Алиса") + chat := createTestChat(t, f.chats, "Пагинация", []string{user.ID}) + other := createTestChat(t, f.chats, "Другой чат", []string{user.ID}) + createTestMessage(t, f.messages, other.ID, user.ID, "Не должно попасть в страницу") + createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC) + ids := []string{ + "00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000002", + "00000000-0000-4000-8000-000000000003", "00000000-0000-4000-8000-000000000004", + } + // Insert in reverse order to exercise SQL ordering, including equal timestamps. + for i := len(ids) - 1; i >= 0; i-- { + at := createdAt + if i > 1 { + at = at.Add(time.Duration(i-1) * time.Second) + } + _, err := f.db.Exec(context.Background(), "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", ids[i], chat.ID, user.ID, "message", at) + if err != nil { + t.Fatal(err) + } + } + first, more, err := f.messages.ListPageByChat(context.Background(), chat.ID, nil, 2) + if err != nil { + t.Fatal(err) + } + if !more || len(first) != 2 || first[0].ID != ids[0] || first[1].ID != ids[1] { + t.Fatalf("unexpected first page: %v, more=%v", first, more) + } + cursor := &messageCursor{ChatID: chat.ID, CreatedAt: first[1].CreatedAt, MessageID: first[1].ID} + second, more, err := f.messages.ListPageByChat(context.Background(), chat.ID, cursor, 2) + if err != nil { + t.Fatal(err) + } + if more || len(second) != 2 || second[0].ID != ids[2] || second[1].ID != ids[3] { + t.Fatalf("unexpected second page: %v, more=%v", second, more) + } +} + +func TestListPageByChatReturnsNonNilEmptyPage(t *testing.T) { + f := newTestFixture(t) + page, more, err := f.messages.ListPageByChat(context.Background(), uuid.NewString(), nil, 100) + if err != nil { + t.Fatal(err) + } + if page == nil || len(page) != 0 || more { + t.Fatalf("unexpected empty page: %v, more=%v", page, more) + } +} diff --git a/src/backend/tests/security_test.go b/src/backend/tests/security_test.go new file mode 100644 index 00000000..2c0a40e5 --- /dev/null +++ b/src/backend/tests/security_test.go @@ -0,0 +1,79 @@ +package tests + +import ( + "bytes" + "context" + "messenger/src/backend/handlers" + "messenger/src/backend/services" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestPasswordKDFUsesSaltAndFullUTF8Password(t *testing.T) { + password := "длинный-пароль-с-эмодзи-🔒-0123456789" + first, err := services.HashPassword(password) + if err != nil { + t.Fatal(err) + } + second, err := services.HashPassword(password) + if err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(first, []byte("$argon2id$v=19$m=65536,t=3,p=2$")) || bytes.Equal(first, second) { + t.Fatal("password hashes must use Argon2id with independent salts") + } + valid, err := services.VerifyPassword(password, first) + if err != nil { + t.Fatal(err) + } + invalid, err := services.VerifyPassword(password+"другое", first) + if err != nil { + t.Fatal(err) + } + if !valid || invalid { + t.Fatal("Argon2id verification lost the full UTF-8 password") + } + if _, err := services.VerifyPassword(password, bytes.Repeat([]byte{1}, 64)); err == nil { + t.Fatal("legacy scrypt hash must not be accepted") + } +} + +func TestStoredPasswordUsesArgon2id(t *testing.T) { + fixture := newTestFixture(t) + user, _ := createTestUser(t, fixture.users, "alice", "Алиса") + var stored []byte + if err := fixture.db.QueryRow(context.Background(), "SELECT password_hash FROM users WHERE id=$1", user.ID).Scan(&stored); err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(stored, []byte("$argon2id$")) { + t.Fatalf("unexpected stored password hash format: %q", stored) + } +} + +func TestBearerRequiredIgnoresXUserID(t *testing.T) { + handler := handlers.NewRouter(nil, nil, nil, nil, nil) + request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil) + request.Header.Set("X-User-Id", "11111111-1111-4111-8111-111111111111") + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != 401 || response.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` { + t.Fatalf("unexpected response: %d %v", response.Code, response.Header()) + } +} + +func TestMessageCursorPreservesPosition(t *testing.T) { + original := messageCursor{ChatID: "11111111-1111-4111-8111-111111111111", CreatedAt: time.Date(2026, 9, 23, 10, 0, 0, 123000, time.UTC), MessageID: "22222222-2222-4222-8222-222222222222"} + token, err := services.EncodeMessageCursor(original) + if err != nil { + t.Fatal(err) + } + decoded, err := services.DecodeMessageCursor(token) + if err != nil { + t.Fatal(err) + } + if decoded != original { + t.Fatalf("cursor changed: %+v", decoded) + } +} diff --git a/src/backend/tests/test_fixture_test.go b/src/backend/tests/test_fixture_test.go new file mode 100644 index 00000000..ebf150a5 --- /dev/null +++ b/src/backend/tests/test_fixture_test.go @@ -0,0 +1,123 @@ +package tests + +import ( + "context" + "messenger/src/backend/handlers" + "messenger/src/backend/repositories" + "messenger/src/backend/services" + "net/http" + "os" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type testFixture struct { + db *pgxpool.Pool + users *repositories.UserStore + chats *repositories.ChatStore + messages *repositories.MessageStore + sessions *services.SessionService + router http.Handler +} + +// Each test owns a new schema; public application tables are never modified. +func newTestFixture(t *testing.T) *testFixture { + t.Helper() + url := os.Getenv("TEST_DATABASE_URL") + if url == "" { + t.Skip("PostgreSQL tests: run make test-backend, or set TEST_DATABASE_URL") + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + admin, err := pgxpool.New(ctx, url) + if err != nil { + t.Fatal(err) + } + t.Cleanup(admin.Close) + schema := "test_" + strings.ReplaceAll(uuid.NewString(), "-", "") + identifier := pgx.Identifier{schema}.Sanitize() + if _, err = admin.Exec(ctx, "CREATE SCHEMA "+identifier); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := admin.Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE"); err != nil { + t.Errorf("cleanup test schema: %v", err) + } + }) + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + t.Fatal(err) + } + cfg.ConnConfig.RuntimeParams["search_path"] = schema + db, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + t.Cleanup(db.Close) + ddl, err := os.ReadFile("../repositories/migrations/000001_initial.up.sql") + if err != nil { + t.Fatal(err) + } + if _, err = db.Exec(ctx, string(ddl)); err != nil { + t.Fatal(err) + } + users := repositories.NewUserStore(db) + chats := repositories.NewChatStore(db) + messages := repositories.NewMessageStore(db) + userService := services.NewUserService(users) + sessions := services.NewSessionService(userService, repositories.NewSessionStore(db), time.Hour) + router := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db)), userService, sessions, services.NewChatService(chats), services.NewMessageService(messages)) + return &testFixture{db, users, chats, messages, sessions, router} +} + +func createTestUser(t *testing.T, store *repositories.UserStore, username, name string) (repositories.User, bool) { + t.Helper() + user, err := services.NewUserService(store).Create(context.Background(), username, name, "lab2-test-password") + if err != nil { + t.Fatal(err) + } + return user, true +} + +func createTestChat(t *testing.T, store *repositories.ChatStore, title string, members []string) repositories.Chat { + t.Helper() + chat, err := store.Create(context.Background(), title, members) + if err != nil { + t.Fatal(err) + } + return chat +} + +func createTestMessage(t *testing.T, store *repositories.MessageStore, chatID, userID, text string) repositories.Message { + t.Helper() + message, err := store.Create(context.Background(), chatID, userID, text) + if err != nil { + t.Fatal(err) + } + return message +} + +func listTestMessages(t *testing.T, store *repositories.MessageStore, chatID string) []repositories.Message { + t.Helper() + items, _, err := store.ListPageByChat(context.Background(), chatID, nil, 100) + if err != nil { + t.Fatal(err) + } + return items +} + +func authorizeTestRequest(t *testing.T, fixture *testFixture, request *http.Request, userID string) { + t.Helper() + token, _, err := fixture.sessions.CreateForUser(request.Context(), userID) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Authorization", "Bearer "+token) +} diff --git a/src/backend/tests/types_test.go b/src/backend/tests/types_test.go new file mode 100644 index 00000000..25e6b75c --- /dev/null +++ b/src/backend/tests/types_test.go @@ -0,0 +1,12 @@ +package tests + +import ( + "messenger/src/backend/repositories" + "messenger/src/backend/services" +) + +type User = repositories.User +type Chat = repositories.Chat +type Message = repositories.Message +type messagePage = services.MessagePage +type messageCursor = repositories.MessageCursor diff --git a/src/backend/tests/user_handler_test.go b/src/backend/tests/user_handler_test.go new file mode 100644 index 00000000..2e22feec --- /dev/null +++ b/src/backend/tests/user_handler_test.go @@ -0,0 +1,137 @@ +package tests + +import ( + "context" + "messenger/src/backend/handlers" + "messenger/src/backend/repositories" + "messenger/src/backend/services" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestCreateUserInvalidJSON(t *testing.T) { + store := repositories.NewUserStore(nil) + handler := handlers.NewRouter(nil, services.NewUserService(store), nil, nil, nil) + + request := httptest.NewRequest( + http.MethodPost, + "/api/v1/users", + strings.NewReader(`{"username":`), + ) + request.Header.Set("Content-Type", "application/json") + + response := httptest.NewRecorder() + + handler.ServeHTTP(response, request) + + if response.Code != http.StatusBadRequest { + t.Fatalf( + "expected status %d, got %d; body: %s", + http.StatusBadRequest, + response.Code, + response.Body.String(), + ) + } + + if response.Header().Get("Content-Type") != "application/json" { + t.Fatalf( + "expected Content-Type application/json, got %q", + response.Header().Get("Content-Type"), + ) + } + + if response.Header().Get("X-Request-Id") == "" { + t.Fatal("expected non-empty X-Request-Id header") + } + + body := response.Body.String() + + if !strings.Contains(body, `"code":"invalid_request"`) { + t.Fatalf( + "expected invalid_request error code, got body: %s", + body, + ) + } + + if !strings.Contains(body, "request_id") { + t.Fatalf( + "expected request_id in error body, got body: %s", + body, + ) + } +} + +func TestCreateUserDuplicateUsername(t *testing.T) { + fixture := newTestFixture(t) + handler := fixture.router + + firstRequest := httptest.NewRequest( + http.MethodPost, + "/api/v1/users", + strings.NewReader(`{ + "username": "alice", + "display_name": "Алиса", "password": "lab2-test-password" + }`), + ) + firstRequest.Header.Set("Content-Type", "application/json") + + firstResponse := httptest.NewRecorder() + + handler.ServeHTTP(firstResponse, firstRequest) + + if firstResponse.Code != http.StatusCreated { + t.Fatalf( + "expected first request status %d, got %d; body: %s", + http.StatusCreated, + firstResponse.Code, + firstResponse.Body.String(), + ) + } + + secondRequest := httptest.NewRequest( + http.MethodPost, + "/api/v1/users", + strings.NewReader(`{ + "username": "alice", + "display_name": "Другая Алиса", "password": "lab2-test-password" + }`), + ) + secondRequest.Header.Set("Content-Type", "application/json") + + secondResponse := httptest.NewRecorder() + + handler.ServeHTTP(secondResponse, secondRequest) + + if secondResponse.Code != http.StatusConflict { + t.Fatalf( + "expected duplicate username status %d, got %d; body: %s", + http.StatusConflict, + secondResponse.Code, + secondResponse.Body.String(), + ) + } + + if secondResponse.Header().Get("X-Request-Id") == "" { + t.Fatal("expected non-empty X-Request-Id header") + } + + if !strings.Contains( + secondResponse.Body.String(), + `"code":"conflict"`, + ) { + t.Fatalf( + "expected conflict error code, got body: %s", + secondResponse.Body.String(), + ) + } + + var count int + if err := fixture.db.QueryRow(context.Background(), "SELECT count(*) FROM users").Scan(&count); err != nil { + t.Fatal(err) + } + if count != 1 { + t.Fatalf("expected one user, got %d", count) + } +} diff --git a/src/chat_get_handler.go b/src/chat_get_handler.go deleted file mode 100644 index 3d504890..00000000 --- a/src/chat_get_handler.go +++ /dev/null @@ -1,105 +0,0 @@ -package main - -import ( - "encoding/json" - "log" - "net/http" - "strings" - - "github.com/google/uuid" -) - -func getChatHandler( - userStore *userStore, - chatStore *chatStore, -) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - requestID := newRequestID() - w.Header().Set("X-Request-Id", requestID) - - if r.Method != http.MethodGet { - writeError( - w, - http.StatusMethodNotAllowed, - "method_not_allowed", - "method not allowed", - requestID, - ) - return - } - - currentUserID := currentUserID(r) - - if currentUserID == "" { - writeError( - w, - http.StatusUnauthorized, - "unauthorized", - "valid Bearer session is required", - requestID, - ) - return - } - - if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { - writeError( - w, - http.StatusUnauthorized, - "unauthorized", - "unknown user", - requestID, - ) - return - } - - chatID := strings.TrimPrefix( - r.URL.Path, - "/api/v1/chats/", - ) - - if chatID == "" || strings.Contains(chatID, "/") { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "invalid chat id", - requestID, - ) - return - } - - if _, err := uuid.Parse(chatID); err != nil { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "invalid chat id", - requestID, - ) - return - } - - chat, err := chatStore.getByID(r.Context(), chatID) - - if err != nil || !chatStore.isMember(chat, currentUserID) { - // Для неизвестного и чужого чата используется одинаковый 404. - // Это не раскрывает постороннему пользователю наличие чата. - writeError( - w, - http.StatusNotFound, - "not_found", - "chat not found", - requestID, - ) - return - } - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - if err := json.NewEncoder(w).Encode(chat); err != nil { - log.Printf("failed to encode chat response: %v", err) - return - } - } -} diff --git a/src/chat_handler.go b/src/chat_handler.go deleted file mode 100644 index 7460c89c..00000000 --- a/src/chat_handler.go +++ /dev/null @@ -1,194 +0,0 @@ -package main - -import ( - "encoding/json" - "errors" - "log" - "net/http" - "strings" - "unicode/utf8" - - "github.com/google/uuid" -) - -type createChatRequest struct { - Title string `json:"title"` - MemberIDs []string `json:"member_ids"` -} - -func createChatHandler( - userStore *userStore, - chatStore *chatStore, -) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - requestID := newRequestID() - w.Header().Set("X-Request-Id", requestID) - - if r.Method != http.MethodPost { - writeError( - w, - http.StatusMethodNotAllowed, - "method_not_allowed", - "method not allowed", - requestID, - ) - return - } - - currentUserID := currentUserID(r) - - if currentUserID == "" { - writeError( - w, - http.StatusUnauthorized, - "unauthorized", - "valid Bearer session is required", - requestID, - ) - return - } - - if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { - writeError( - w, - http.StatusUnauthorized, - "unauthorized", - "unknown user", - requestID, - ) - return - } - - if !strings.HasPrefix( - r.Header.Get("Content-Type"), - "application/json", - ) { - writeError( - w, - http.StatusUnsupportedMediaType, - "unsupported_media_type", - "content type must be application/json", - requestID, - ) - return - } - - var request createChatRequest - - if err := decodeJSONBody(r, &request); err != nil { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "invalid JSON body", - requestID, - ) - return - } - - if strings.TrimSpace(request.Title) == "" { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "title must not be blank", - requestID, - ) - return - } - - if utf8.RuneCountInString(request.Title) > 100 { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "title is too long", - requestID, - ) - return - } - - if len(request.MemberIDs) == 0 || len(request.MemberIDs) > 100 { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "member_ids must contain from 1 to 100 users", - requestID, - ) - return - } - - seenMembers := make(map[string]struct{}) - - for _, memberID := range request.MemberIDs { - if _, err := uuid.Parse(memberID); err != nil { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "member_ids must contain valid UUIDs", - requestID, - ) - return - } - - if _, duplicate := seenMembers[memberID]; duplicate { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "member_ids must not contain duplicates", - requestID, - ) - return - } - - seenMembers[memberID] = struct{}{} - - if _, err := userStore.getByID(r.Context(), memberID); err != nil { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "all members must be existing users", - requestID, - ) - return - } - } - - if _, included := seenMembers[currentUserID]; !included { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "current user must be a chat member", - requestID, - ) - return - } - - chat, err := chatStore.create( - r.Context(), - request.Title, - request.MemberIDs, - ) - if errors.Is(err, errUnknownMember) { - writeError(w, 400, "invalid_request", "all members must be existing users", requestID) - return - } - if err != nil { - writeError(w, 503, "unavailable", "database unavailable", requestID) - return - } - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - if err := json.NewEncoder(w).Encode(chat); err != nil { - log.Printf("failed to encode chat response: %v", err) - return - } - } -} diff --git a/src/chat_list_handler.go b/src/chat_list_handler.go deleted file mode 100644 index fafe5915..00000000 --- a/src/chat_list_handler.go +++ /dev/null @@ -1,219 +0,0 @@ -package main - -import ( - "encoding/base64" - "encoding/json" - "net/http" - "strconv" - "time" -) - -type chatPage struct { - Items []Chat `json:"items"` - NextCursor *string `json:"next_cursor"` -} - -type chatCursor struct { - UserID string `json:"user_id"` - CreatedAt time.Time `json:"created_at"` - ChatID string `json:"chat_id"` -} - -func encodeChatCursor(cursor chatCursor) (string, error) { - data, err := json.Marshal(cursor) - if err != nil { - return "", err - } - - return base64.RawURLEncoding.EncodeToString(data), nil -} - -func decodeChatCursor(value string) (chatCursor, error) { - data, err := base64.RawURLEncoding.DecodeString(value) - if err != nil { - return chatCursor{}, err - } - - var cursor chatCursor - - if err := json.Unmarshal(data, &cursor); err != nil { - return chatCursor{}, err - } - - if cursor.UserID == "" || - cursor.ChatID == "" || - cursor.CreatedAt.IsZero() { - return chatCursor{}, strconv.ErrSyntax - } - - return cursor, nil -} - -func listChatsHandler( - userStore *userStore, - chatStore *chatStore, -) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - requestID := newRequestID() - w.Header().Set("X-Request-Id", requestID) - - if r.Method != http.MethodGet { - writeError( - w, - http.StatusMethodNotAllowed, - "method_not_allowed", - "method not allowed", - requestID, - ) - return - } - - currentUserID := currentUserID(r) - - if currentUserID == "" { - writeError( - w, - http.StatusUnauthorized, - "unauthorized", - "valid Bearer session is required", - requestID, - ) - return - } - - if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { - writeError( - w, - http.StatusUnauthorized, - "unauthorized", - "unknown user", - requestID, - ) - return - } - - limit := 50 - - if values, exists := r.URL.Query()["limit"]; exists { - if len(values) != 1 || values[0] == "" { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "invalid limit", - requestID, - ) - return - } - - parsedLimit, err := strconv.Atoi(values[0]) - if err != nil || parsedLimit < 1 || parsedLimit > 100 { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "limit must be between 1 and 100", - requestID, - ) - return - } - - limit = parsedLimit - } - - var cursor *chatCursor - - if values, exists := r.URL.Query()["cursor"]; exists { - if len(values) != 1 || values[0] == "" { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "invalid cursor", - requestID, - ) - return - } - - decoded, err := decodeChatCursor(values[0]) - if err != nil || decoded.UserID != currentUserID { - writeError( - w, - http.StatusBadRequest, - "invalid_request", - "invalid cursor", - requestID, - ) - return - } - - cursor = &decoded - } - - pageItems, hasMore, err := chatStore.listPageForUser(r.Context(), currentUserID, cursor, limit) - if err != nil { - writeError(w, 503, "unavailable", "database unavailable", requestID) - return - } - - page := chatPage{ - Items: pageItems, - NextCursor: nil, - } - - if hasMore { - last := pageItems[len(pageItems)-1] - - nextCursor, err := encodeChatCursor(chatCursor{ - UserID: currentUserID, - CreatedAt: last.CreatedAt, - ChatID: last.ID, - }) - - if err != nil { - writeError( - w, - http.StatusInternalServerError, - "internal_error", - "internal server error", - requestID, - ) - return - } - - page.NextCursor = &nextCursor - } - - if page.Items == nil { - page.Items = make([]Chat, 0) - } - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - if err := json.NewEncoder(w).Encode(page); err != nil { - return - } - } -} - -func chatCollectionHandler( - userStore *userStore, - chatStore *chatStore, -) http.HandlerFunc { - createHandler := createChatHandler(userStore, chatStore) - listHandler := listChatsHandler(userStore, chatStore) - - return func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case http.MethodPost: - createHandler(w, r) - case http.MethodGet: - listHandler(w, r) - default: - // Передаём обработку createHandler, чтобы получить - // единый JSON-формат ошибки. - createHandler(w, r) - } - } -} diff --git a/src/chat_subresource_handler.go b/src/chat_subresource_handler.go deleted file mode 100644 index 0f5dfeeb..00000000 --- a/src/chat_subresource_handler.go +++ /dev/null @@ -1,41 +0,0 @@ -package main - -import ( - "net/http" - "strings" -) - -func chatSubresourceHandler( - userStore *userStore, - chatStore *chatStore, - messageStore *messageStore, -) http.HandlerFunc { - getChat := getChatHandler(userStore, chatStore) - createMessage := createMessageHandler( - userStore, - chatStore, - messageStore, - ) - listMessages := listMessagesHandler( - userStore, - chatStore, - messageStore, - ) - - return func(w http.ResponseWriter, r *http.Request) { - if strings.HasSuffix(r.URL.Path, "/messages") { - switch r.Method { - case http.MethodPost: - createMessage(w, r) - case http.MethodGet: - listMessages(w, r) - default: - createMessage(w, r) - } - - return - } - - getChat(w, r) - } -} diff --git a/src/current_user_handler.go b/src/current_user_handler.go deleted file mode 100644 index f96f74e8..00000000 --- a/src/current_user_handler.go +++ /dev/null @@ -1,58 +0,0 @@ -package main - -import ( - "encoding/json" - "log" - "net/http" -) - -func currentUserHandler(store *userStore) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - requestID := newRequestID() - w.Header().Set("X-Request-Id", requestID) - - if r.Method != http.MethodGet { - writeError( - w, - http.StatusMethodNotAllowed, - "method_not_allowed", - "method not allowed", - requestID, - ) - return - } - - userID := currentUserID(r) - - if userID == "" { - writeError( - w, - http.StatusUnauthorized, - "unauthorized", - "valid Bearer session is required", - requestID, - ) - return - } - - user, err := store.getByID(r.Context(), userID) - if err != nil { - writeError( - w, - http.StatusUnauthorized, - "unauthorized", - "unknown user", - requestID, - ) - return - } - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - if err := json.NewEncoder(w).Encode(user); err != nil { - log.Printf("failed to encode user response: %v", err) - return - } - } -} diff --git a/src/frontend/.dockerignore b/src/frontend/.dockerignore new file mode 100644 index 00000000..f06235c4 --- /dev/null +++ b/src/frontend/.dockerignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/src/frontend/.gitignore b/src/frontend/.gitignore new file mode 100644 index 00000000..c605a04f --- /dev/null +++ b/src/frontend/.gitignore @@ -0,0 +1,8 @@ +node_modules/ +dist/ +.vite/ +*.tsbuildinfo +*.local +.env +.env.* +!.env.example diff --git a/src/frontend/Dockerfile b/src/frontend/Dockerfile new file mode 100644 index 00000000..e0503fd2 --- /dev/null +++ b/src/frontend/Dockerfile @@ -0,0 +1,12 @@ +FROM node:22-bookworm-slim + +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY . . + +EXPOSE 5173 + +CMD ["npm", "run", "dev"] diff --git a/src/frontend/index.html b/src/frontend/index.html new file mode 100644 index 00000000..84dd5c30 --- /dev/null +++ b/src/frontend/index.html @@ -0,0 +1,12 @@ + + + + + + Мессенджер · проверка API + + +
+ + + diff --git a/src/frontend/package-lock.json b/src/frontend/package-lock.json new file mode 100644 index 00000000..962e48c1 --- /dev/null +++ b/src/frontend/package-lock.json @@ -0,0 +1,1288 @@ +{ + "name": "messenger-test-ui", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "messenger-test-ui", + "version": "1.0.0", + "dependencies": { + "react": "19.3.0", + "react-dom": "19.3.0" + }, + "devDependencies": { + "@types/node": "^22.15.0", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "6.1.1", + "typescript": "7.0.2", + "vite": "8.3.0" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.151.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.151.0.tgz", + "integrity": "sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.10.tgz", + "integrity": "sha512-bp9svZb+QurZeh+8H4BhrZkifEB0YBNvTVzNSJnJQkj4NrRwmQoDUCGP0vSN7PbvLeM7l1tK6GXL8mrTiH2myg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.10.tgz", + "integrity": "sha512-wm6Dld3RXUAZ/gRWKyUy+4W1B5CB5UeFaOzsSWJWEdxZXHH8rCYiZ5dGe6oJmhsunAPWzL7FZV+VtvmN5Ye2eA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.10.tgz", + "integrity": "sha512-UbEfXq/AqGNgRTV3ik+X/iR6mUxu2QdYAadwRxJWquUGnW6gDqdP1FtLtFXRow7RJx0ssRwi80XAPr4r+4DtsA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.10.tgz", + "integrity": "sha512-7f5h17q5KZVx/ji1vb8OTq31ch1O2I7K8NPIr44GkyWTApXMIsmhWqZfgpOH10xeauqghDAvGlZktasCkcF6Eg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.10.tgz", + "integrity": "sha512-ynOk/eEYhC6ZB2xCGvKrEOwE58oBy9LnrAqtkrDF9Fz1VTaNdGZTsV0VarJdhPwb+sOJTGjCLwcuyRJZ1dnMcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.10.tgz", + "integrity": "sha512-ERrAs185meZZhGan7a4l3RiiJK1ArSDlHdST++uvSxe+FDbR4TwUPahT/cbZJvaG6fIpDpF78surN+tX708Y4Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.10.tgz", + "integrity": "sha512-KN7OHKD0J3jy1UzBwZWPxpwhODf9IARUIJcrH+yLYKOcmegZ8luEUM38lDP1bDVj40yP6PsSzCqOJF76vljFnQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.10.tgz", + "integrity": "sha512-8l9wP8O+wa8zD6iw6egSfzVtu7oZVfH3hlUsMM4MwbLMhxleqeoXbZzjddyK3YyNlwLhqznq3tF7PkNJ8T/V2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.10.tgz", + "integrity": "sha512-SeXNKeQzA5kLhz/J0CH6ZP0/HJ3v1xm/0YbiYpE0kK7emfRC2OIGGIaE14xzkISEGv2aYuUSpiLiU5Gbq+OI0A==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.10.tgz", + "integrity": "sha512-mtht0nR+y8/hart4175Ll15w7lY8dg7CtQ+j2FDNTsDRspOWTK/2V3l0aj9sIj7XmvqxT8Yli/wq22e7feTTWg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.10.tgz", + "integrity": "sha512-FSM94nGd55NYo48usCyM/nHfUKRnqc9+b0vJNuKV0oCCpIp/OGims7rO1Nv/DkFkt0S/s2rxsJ2kkS8J3HcpeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.10.tgz", + "integrity": "sha512-C3YxNB16myRLs7o+B+6PnQ6jBsdIS4+AE4Ah8glVGhDpEv9AOvxhZ/1duAb4B0UGczEK/lBbccksd8VI+p6zfw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.10.tgz", + "integrity": "sha512-571TlE/F1eeTjjdjYAMMMPs1Mfv3MtX6s3+ZKVU6HiUjZ5Njc6c/qzNy/8K3zALTZnaw3JQVYrHxvNfjm43KAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.10.tgz", + "integrity": "sha512-QXW+ZWaiqs2c7Fi++D/SsW07LTPcUrncxcskJGfGNBoaLik1IU6fJymz4HsqwEO0u5Iq11yTO0B/mc4cPk7jrQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.10.tgz", + "integrity": "sha512-5FQFGgah17YeMtG1Yd5a+rMxQpTksyNXxRtKz06FVTaQw3RKYUJQbUoKk0/5jrXBpDo+7makNP7UHA2LQyH64A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.4.tgz", + "integrity": "sha512-zJRE40jpHtKqE/C4fgHrAKQLJuSpzEnP9ff9Y7YtoR3Wd2pwqzlekDeEuUQXjRd+QCYnVnNwuJYmhdk9XV8gvA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.1.tgz", + "integrity": "sha512-yxLaQV9gkhS8ezJqCM6+ndU7mDY6gqAg75NQ+0IjwEI8IYOmQCgkRwHKVSfWXW076DsqMo0Dk+0FK1U+M5RgFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": "^0.145.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/nanoid": { + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", + "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.0" + } + }, + "node_modules/rolldown": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.10.tgz", + "integrity": "sha512-OxkA08pSryMK7B3XiFA09B4OJ1xJMPgIYCBMY2xchzpqgBGsV1o0DetPAE+Sl3N3L4oCPiEzmHVSOj7iR04Zog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.151.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.10", + "@rolldown/binding-android-arm64": "1.2.10", + "@rolldown/binding-darwin-arm64": "1.2.10", + "@rolldown/binding-darwin-x64": "1.2.10", + "@rolldown/binding-freebsd-x64": "1.2.10", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.10", + "@rolldown/binding-linux-arm64-gnu": "1.2.10", + "@rolldown/binding-linux-arm64-musl": "1.2.10", + "@rolldown/binding-linux-ppc64-gnu": "1.2.10", + "@rolldown/binding-linux-s390x-gnu": "1.2.10", + "@rolldown/binding-linux-x64-gnu": "1.2.10", + "@rolldown/binding-linux-x64-musl": "1.2.10", + "@rolldown/binding-openharmony-arm64": "1.2.10", + "@rolldown/binding-win32-arm64-msvc": "1.2.10", + "@rolldown/binding-win32-x64-msvc": "1.2.10" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.0.tgz", + "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.6", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/src/frontend/package.json b/src/frontend/package.json new file mode 100644 index 00000000..8a453e8b --- /dev/null +++ b/src/frontend/package.json @@ -0,0 +1,23 @@ +{ + "name": "messenger-test-ui", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "react": "19.3.0", + "react-dom": "19.3.0" + }, + "devDependencies": { + "@types/node": "^22.15.0", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "6.1.1", + "typescript": "7.0.2", + "vite": "8.3.0" + } +} diff --git a/src/frontend/src/App.tsx b/src/frontend/src/App.tsx new file mode 100644 index 00000000..74436fd7 --- /dev/null +++ b/src/frontend/src/App.tsx @@ -0,0 +1,200 @@ +import { useCallback, useEffect, useState, type FormEvent } from "react"; +import { api, ApiError, type Chat, type Session, type User } from "./api"; + +import Pagination from "./Pagination"; +import { useCursorPage } from "./useCursorPage"; + +const tokenKey = "messenger_test_token"; + +function errorText(error: unknown): string { + if (error instanceof ApiError) { + return error.requestId + ? `${error.message} · запрос ${error.requestId}` + : error.message; + } + return error instanceof Error ? error.message : "Неизвестная ошибка"; +} + +function dateText(value: string): string { + return new Date(value).toLocaleString("ru-RU", { + dateStyle: "short", + timeStyle: "short", + }); +} + +function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) { + const [mode, setMode] = useState<"login" | "register">("login"); + const [username, setUsername] = useState(""); + const [displayName, setDisplayName] = useState(""); + const [password, setPassword] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + + async function submit(event: FormEvent) { + event.preventDefault(); + setBusy(true); + setError(""); + try { + if (mode === "register") { + await api.register(username, displayName, password); + } + const session = await api.login(username, password); + setPassword(""); + onSuccess(session); + } catch (cause) { + setError(errorText(cause)); + } finally { + setBusy(false); + } + } + + return ( +
+
+ +

Мессенджер

+
+ + +
+
+ + {mode === "register" && ( + + )} + + {error &&

{error}

} + +
+
+
+ ); +} + +function Workspace({ token, user, onLogout }: { token: string; user: User; onLogout: (notice?: string) => void }) { + const [selectedChat, setSelectedChat] = useState(null); + const [showCreate, setShowCreate] = useState(false); + const [title, setTitle] = useState(""); + const [members, setMembers] = useState(""); + const [drafts, setDrafts] = useState>({}); + const [creating, setCreating] = useState(false); + const [sending, setSending] = useState(false); + const [error, setError] = useState(""); + const [notice, setNotice] = useState(""); + const reportError = useCallback((cause: unknown) => { + if (cause instanceof ApiError && cause.status === 401) onLogout("Сессия истекла. Войдите снова."); + else setError(errorText(cause)); + }, [onLogout]); + const fetchChats = useCallback((cursor: string | undefined, limit: number) => api.chats(token, cursor, limit), [token]); + const chatId = selectedChat?.id || ""; + const fetchMessages = useCallback((cursor: string | undefined, limit: number) => api.messages(token, chatId, cursor, limit), [token, chatId]); + const chats = useCursorPage(token, fetchChats, reportError); + const messages = useCursorPage(chatId, fetchMessages, reportError); + + async function createChat(event: FormEvent) { + event.preventDefault(); + if (!title.trim()) return; + setCreating(true); setError(""); + try { + const memberIds = Array.from(new Set([user.id, ...members.split(/[\s,;]+/).filter(Boolean)])); + const chat = await api.createChat(token, title.trim(), memberIds); + setSelectedChat(chat); setTitle(""); setMembers(""); setShowCreate(false); chats.refresh(); + } catch (cause) { reportError(cause); } + finally { setCreating(false); } + } + + async function sendMessage(event: FormEvent) { + event.preventDefault(); + const text = (drafts[chatId] || "").trim(); + if (!text) return; + setSending(true); setError(""); + try { + await api.sendMessage(token, chatId, text); + setDrafts((previous) => ({ ...previous, [chatId]: "" })); + messages.reload(); setNotice("Сообщение отправлено"); + } catch (cause) { reportError(cause); } + finally { setSending(false); } + } + + async function logout() { + try { await api.logout(token); onLogout(); } + catch (cause) { reportError(cause); } + } + + async function copyId() { + try { await navigator.clipboard.writeText(user.id); setNotice("ID скопирован"); } + catch { setError("Не удалось скопировать ID. Выделите его вручную."); } + } + + return
+
+ Мессенджер +
{user.display_name.slice(0, 1).toUpperCase()}
{user.display_name}@{user.username}
+
+ {(error || notice) &&
{error || notice}
} +
+