Перенести Go API и контейнер из лабораторной 1

This commit is contained in:
Dima
2026-09-23 21:22:49 +03:00
parent 65003b6119
commit a858d3325b
21 changed files with 2375 additions and 0 deletions
+6
View File
@@ -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
+49
View File
@@ -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"]
+24
View File
@@ -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)
}
}
+5
View File
@@ -0,0 +1,5 @@
module messenger
go 1.22.2
require github.com/google/uuid v1.6.0
+2
View File
@@ -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=
+83
View File
@@ -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
}
+105
View File
@@ -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
}
}
}
+184
View File
@@ -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
}
}
}
+246
View File
@@ -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)
}
}
}
+41
View File
@@ -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)
}
}
+221
View File
@@ -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),
)
}
}
+58
View File
@@ -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
}
}
}
+159
View File
@@ -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")
}
}
+111
View File
@@ -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
}
+179
View File
@@ -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
}
+291
View File
@@ -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),
)
}
}
+224
View File
@@ -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
}
}
}
+64
View File
@@ -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)
}
}
+58
View File
@@ -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
}
+133
View File
@@ -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
}
}
}
+132
View File
@@ -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),
)
}
}