сделана пагинация чатов

This commit is contained in:
2026-10-06 22:05:51 +03:00
parent 4455850c6a
commit 10b5842be3
4 changed files with 421 additions and 28 deletions
+68
View File
@@ -153,3 +153,71 @@ type ChatPage struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}
const chatCursorVersion = "v1"
type ChatCursorData struct {
CreatedAt time.Time
ChatID string
UserID string
}
// EncodeChatCursor создаёт непрозрачную границу списка чатов.
// Версия позволяет в будущем изменить внутренний формат курсора.
func EncodeChatCursor(createdAt time.Time, chatID, userID string) string {
raw := fmt.Sprintf(
"%s|%s|%s|%s",
chatCursorVersion,
createdAt.UTC().Format(time.RFC3339Nano),
chatID,
userID,
)
// RawURLEncoding не использует символы +, / и завершающий =,
// поэтому курсор безопаснее передавать в query string.
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func DecodeChatCursor(
cursorStr string,
expectedUserID string,
) (*ChatCursorData, error) {
decoded, err := base64.RawURLEncoding.DecodeString(cursorStr)
if err != nil {
return nil, fmt.Errorf("invalid base64 chat cursor")
}
parts := strings.Split(string(decoded), "|")
if len(parts) != 4 {
return nil, fmt.Errorf("malformed chat cursor")
}
if parts[0] != chatCursorVersion {
return nil, fmt.Errorf("unsupported chat cursor version")
}
createdAt, err := time.Parse(time.RFC3339Nano, parts[1])
if err != nil {
return nil, fmt.Errorf("invalid chat cursor timestamp")
}
chatID := parts[2]
if _, err = uuid.Parse(chatID); err != nil {
return nil, fmt.Errorf("invalid chat cursor chat_id")
}
userID := parts[3]
if _, err = uuid.Parse(userID); err != nil {
return nil, fmt.Errorf("invalid chat cursor user_id")
}
if userID != expectedUserID {
return nil, fmt.Errorf("chat cursor belongs to another user")
}
return &ChatCursorData{
CreatedAt: createdAt,
ChatID: chatID,
UserID: userID,
}, nil
}
+71 -15
View File
@@ -12,8 +12,9 @@ import (
)
var (
ErrNotFound = fmt.Errorf("not found")
ErrConflict = fmt.Errorf("conflict")
ErrNotFound = fmt.Errorf("not found")
ErrConflict = fmt.Errorf("conflict")
ErrInvalidCursor = fmt.Errorf("invalid cursor")
)
type MemoryStore struct {
@@ -122,33 +123,88 @@ func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error)
return chat, nil
}
func (s *MemoryStore) GetChatsForUser(userID string, limit int) ([]domain.Chat, error) {
func (s *MemoryStore) GetChatsForUser(
userID string,
limit int,
cursorStr string,
) (domain.ChatPage, error) {
var cursorData *domain.ChatCursorData
if cursorStr != "" {
decodedCursor, err := domain.DecodeChatCursor(cursorStr, userID)
if err != nil {
return domain.ChatPage{},
fmt.Errorf("%w: %v", ErrInvalidCursor, err)
}
cursorData = decodedCursor
}
s.mu.RLock()
defer s.mu.RUnlock()
var result []domain.Chat
chats := make([]domain.Chat, 0)
for _, chat := range s.chatsByID {
for _, m := range chat.MemberIDs {
if m == userID {
result = append(result, chat)
for _, memberID := range chat.MemberIDs {
if memberID == userID {
chats = append(chats, chat)
break
}
}
}
//по контракту: сортировка по created_at, id по возрастанию
sort.Slice(result, func(i, j int) bool {
if result[i].CreatedAt.Equal(result[j].CreatedAt) {
return result[i].ID < result[j].ID
sort.Slice(chats, func(i, j int) bool {
if chats[i].CreatedAt.Equal(chats[j].CreatedAt) {
return chats[i].ID < chats[j].ID
}
return result[i].CreatedAt.Before(result[j].CreatedAt)
return chats[i].CreatedAt.Before(chats[j].CreatedAt)
})
if limit > 0 && len(result) > limit {
result = result[:limit]
start := 0
if cursorData != nil {
start = sort.Search(len(chats), func(index int) bool {
chat := chats[index]
if chat.CreatedAt.After(cursorData.CreatedAt) {
return true
}
return chat.CreatedAt.Equal(cursorData.CreatedAt) &&
chat.ID > cursorData.ChatID
})
}
return result, nil
page := domain.ChatPage{
Items: make([]domain.Chat, 0),
NextCursor: nil,
}
if start >= len(chats) {
return page, nil
}
end := start + limit
if end > len(chats) {
end = len(chats)
}
page.Items = make([]domain.Chat, end-start)
copy(page.Items, chats[start:end])
if end < len(chats) {
lastChat := page.Items[len(page.Items)-1]
nextCursor := domain.EncodeChatCursor(
lastChat.CreatedAt,
lastChat.ID,
userID,
)
page.NextCursor = &nextCursor
}
return page, nil
}
// ---Сообщения---
+46 -13
View File
@@ -73,32 +73,65 @@ func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
reqID := middleware.GetRequestID(r.Context())
currentUser := middleware.GetCurrentUser(r.Context())
query := r.URL.Query()
limit := 50
limitStr := r.URL.Query().Get("limit")
if limitStr != "" {
if query.Has("limit") {
limitStr := query.Get("limit")
val, err := strconv.Atoi(limitStr)
if err != nil || val < 1 || val > 100 {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "limit must be an integer between 1 and 100", reqID)
response.WriteError(
w,
http.StatusBadRequest,
response.CodeInvalidRequest,
"limit must be an integer between 1 and 100",
reqID,
)
return
}
limit = val
}
chats, err := h.store.GetChatsForUser(currentUser.ID, limit)
if err != nil {
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID)
cursor := query.Get("cursor")
if query.Has("cursor") && cursor == "" {
response.WriteError(
w,
http.StatusBadRequest,
response.CodeInvalidRequest,
"cursor must not be empty",
reqID,
)
return
}
//если чатов нет, сериализую в пустой массив [], а не null
if chats == nil {
chats = make([]domain.Chat, 0)
}
page, err := h.store.GetChatsForUser(
currentUser.ID,
limit,
cursor,
)
if err != nil {
if errors.Is(err, store.ErrInvalidCursor) {
response.WriteError(
w,
http.StatusBadRequest,
response.CodeInvalidRequest,
"invalid cursor",
reqID,
)
return
}
page := domain.ChatPage{
Items: chats,
NextCursor: nil,
response.WriteError(
w,
http.StatusInternalServerError,
response.CodeInternalError,
"internal error",
reqID,
)
return
}
response.WriteJSON(w, http.StatusOK, page, reqID)
+236
View File
@@ -7,6 +7,8 @@ import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"sort"
"sync"
"testing"
@@ -171,6 +173,240 @@ func TestCursorPaginationMultiplePages(t *testing.T) {
}
}
func TestChatCursorPaginationMultiplePages(t *testing.T) {
ts, st := setupTestServer()
defer ts.Close()
user, err := st.CreateUser("chat_paging_user", "Пейджер чатов")
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
outsider, err := st.CreateUser("chat_paging_outsider", "Посторонний")
if err != nil {
t.Fatalf("failed to create outsider: %v", err)
}
createdChats := make([]domain.Chat, 0, 5)
for i := 1; i <= 5; i++ {
chat, createErr := st.CreateChat(
fmt.Sprintf("Chat %d", i),
[]string{user.ID},
)
if createErr != nil {
t.Fatalf("failed to create chat %d: %v", i, createErr)
}
createdChats = append(createdChats, chat)
// Чужой чат создаётся между доступными чатами и не должен
// влиять на размер страницы или next_cursor пользователя.
if i == 3 {
if _, createErr = st.CreateChat(
"Outsider chat",
[]string{outsider.ID},
); createErr != nil {
t.Fatalf("failed to create outsider chat: %v", createErr)
}
}
}
sort.Slice(createdChats, func(i, j int) bool {
if createdChats[i].CreatedAt.Equal(createdChats[j].CreatedAt) {
return createdChats[i].ID < createdChats[j].ID
}
return createdChats[i].CreatedAt.Before(createdChats[j].CreatedAt)
})
var receivedIDs []string
seenIDs := make(map[string]bool)
seenCursors := make(map[string]bool)
cursor := ""
finished := false
for pageNumber := 1; pageNumber <= 10; pageNumber++ {
requestURL := ts.URL + "/api/v1/chats?limit=2"
if cursor != "" {
requestURL += "&cursor=" + url.QueryEscape(cursor)
}
req, err := http.NewRequest(http.MethodGet, requestURL, nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
req.Header.Set("X-User-Id", user.ID)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("failed to list chats: %v", err)
}
var page domain.ChatPage
decodeErr := json.NewDecoder(res.Body).Decode(&page)
res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", res.StatusCode)
}
if decodeErr != nil {
t.Fatalf("failed to decode chat page: %v", decodeErr)
}
if len(page.Items) > 2 {
t.Fatalf("page contains %d chats with limit=2", len(page.Items))
}
for _, chat := range page.Items {
if seenIDs[chat.ID] {
t.Fatalf("chat %s was returned more than once", chat.ID)
}
seenIDs[chat.ID] = true
receivedIDs = append(receivedIDs, chat.ID)
}
if page.NextCursor == nil {
finished = true
break
}
if seenCursors[*page.NextCursor] {
t.Fatalf("cursor cycle detected")
}
seenCursors[*page.NextCursor] = true
cursor = *page.NextCursor
}
if !finished {
t.Fatal("chat pagination did not finish")
}
if len(receivedIDs) != len(createdChats) {
t.Fatalf(
"expected %d chats across all pages, got %d",
len(createdChats),
len(receivedIDs),
)
}
for i, chat := range createdChats {
if receivedIDs[i] != chat.ID {
t.Fatalf(
"chat order differs at position %d: expected %s, got %s",
i,
chat.ID,
receivedIDs[i],
)
}
}
}
func TestChatCursorValidation(t *testing.T) {
ts, st := setupTestServer()
defer ts.Close()
alice, err := st.CreateUser("chat_cursor_alice", "Алиса")
if err != nil {
t.Fatalf("failed to create Alice: %v", err)
}
bob, err := st.CreateUser("chat_cursor_bob", "Боб")
if err != nil {
t.Fatalf("failed to create Bob: %v", err)
}
for i := 1; i <= 2; i++ {
if _, err = st.CreateChat(
fmt.Sprintf("Alice chat %d", i),
[]string{alice.ID},
); err != nil {
t.Fatalf("failed to create Alice chat: %v", err)
}
}
if _, err = st.CreateChat("Bob chat", []string{bob.ID}); err != nil {
t.Fatalf("failed to create Bob chat: %v", err)
}
firstRequest, err := http.NewRequest(
http.MethodGet,
ts.URL+"/api/v1/chats?limit=1",
nil,
)
if err != nil {
t.Fatalf("failed to create first request: %v", err)
}
firstRequest.Header.Set("X-User-Id", alice.ID)
firstResponse, err := http.DefaultClient.Do(firstRequest)
if err != nil {
t.Fatalf("failed to request first page: %v", err)
}
var firstPage domain.ChatPage
decodeErr := json.NewDecoder(firstResponse.Body).Decode(&firstPage)
firstResponse.Body.Close()
if firstResponse.StatusCode != http.StatusOK {
t.Fatalf("expected first page status 200, got %d", firstResponse.StatusCode)
}
if decodeErr != nil {
t.Fatalf("failed to decode first page: %v", decodeErr)
}
if firstPage.NextCursor == nil {
t.Fatal("expected next_cursor for Alice")
}
foreignRequest, err := http.NewRequest(
http.MethodGet,
ts.URL+"/api/v1/chats?limit=1&cursor="+
url.QueryEscape(*firstPage.NextCursor),
nil,
)
if err != nil {
t.Fatalf("failed to create foreign cursor request: %v", err)
}
foreignRequest.Header.Set("X-User-Id", bob.ID)
foreignResponse, err := http.DefaultClient.Do(foreignRequest)
if err != nil {
t.Fatalf("failed to send foreign cursor request: %v", err)
}
foreignResponse.Body.Close()
if foreignResponse.StatusCode != http.StatusBadRequest {
t.Fatalf(
"expected 400 for another user's cursor, got %d",
foreignResponse.StatusCode,
)
}
malformedRequest, err := http.NewRequest(
http.MethodGet,
ts.URL+"/api/v1/chats?cursor=not-valid-base64!",
nil,
)
if err != nil {
t.Fatalf("failed to create malformed cursor request: %v", err)
}
malformedRequest.Header.Set("X-User-Id", alice.ID)
malformedResponse, err := http.DefaultClient.Do(malformedRequest)
if err != nil {
t.Fatalf("failed to send malformed cursor request: %v", err)
}
malformedResponse.Body.Close()
if malformedResponse.StatusCode != http.StatusBadRequest {
t.Fatalf(
"expected 400 for malformed cursor, got %d",
malformedResponse.StatusCode,
)
}
}
// 6 тест: 100 сообщений от 10 клиентов одновременно, защита от гонок
func TestConcurrent100MessagesFrom10Clients(t *testing.T) {
ts, st := setupTestServer()