953 lines
23 KiB
Go
953 lines
23 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"mtusi2026/internal/cache"
|
|
"mtusi2026/internal/model"
|
|
"mtusi2026/internal/sessionstore"
|
|
"mtusi2026/internal/store"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
//вспомогательные функции
|
|
|
|
func newUnlimitedLimiter() *store.Limiter {
|
|
return store.NewLimiter(1_000_000, 1000)
|
|
}
|
|
|
|
func newTestServer(t *testing.T) *httptest.Server {
|
|
t.Helper()
|
|
srv, _ := newTestServerWithStore(t)
|
|
return srv
|
|
}
|
|
|
|
func newTestServerWithStore(t *testing.T) (*httptest.Server, *store.Store) {
|
|
t.Helper()
|
|
truncateAll(t)
|
|
|
|
s := store.New(testPool, newUnlimitedLimiter())
|
|
ss := newMemorySessionStore()
|
|
|
|
return httptest.NewServer(NewRouter(s, testPool, ss)), s
|
|
}
|
|
|
|
func newRedisTestServer(t *testing.T) *httptest.Server {
|
|
t.Helper()
|
|
srv, _ := newRedisTestServerWithStore(t)
|
|
return srv
|
|
}
|
|
|
|
func newRedisTestServerWithStore(t *testing.T) (*httptest.Server, *store.Store) {
|
|
t.Helper()
|
|
truncateAll(t)
|
|
|
|
if err := testRedis.FlushDB(context.Background()).Err(); err != nil {
|
|
t.Fatalf("flush redis: %v", err)
|
|
}
|
|
|
|
s := store.New(testPool, newUnlimitedLimiter())
|
|
ss := sessionstore.NewRedis(testRedis)
|
|
|
|
return httptest.NewServer(NewRouter(s, testPool, ss)), s
|
|
}
|
|
|
|
func newCachedRedisTestServer(t *testing.T) (*httptest.Server, *store.Store) {
|
|
t.Helper()
|
|
truncateAll(t)
|
|
|
|
if err := testRedis.FlushDB(context.Background()).Err(); err != nil {
|
|
t.Fatalf("flush redis: %v", err)
|
|
}
|
|
|
|
s := store.New(testPool, newUnlimitedLimiter())
|
|
ss := sessionstore.NewRedis(testRedis)
|
|
chatCache := cache.New(testRedis, 30*time.Second)
|
|
|
|
srv := httptest.NewServer(
|
|
NewRouterWithCache(s, testPool, ss, chatCache),
|
|
)
|
|
|
|
return srv, s
|
|
}
|
|
|
|
type testUser struct {
|
|
model.User
|
|
Token string
|
|
}
|
|
|
|
func postJSON(t *testing.T, srv *httptest.Server, path string, token string, body any) *http.Response {
|
|
t.Helper()
|
|
var buf bytes.Buffer
|
|
if s, ok := body.(string); ok {
|
|
buf.WriteString(s)
|
|
} else if err := json.NewEncoder(&buf).Encode(body); err != nil {
|
|
t.Fatalf("encode request body: %v", err)
|
|
}
|
|
req, err := http.NewRequest(http.MethodPost, srv.URL+path, &buf)
|
|
if err != nil {
|
|
t.Fatalf("build request: %v", err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
resp, err := srv.Client().Do(req)
|
|
if err != nil {
|
|
t.Fatalf("do request: %v", err)
|
|
}
|
|
return resp
|
|
}
|
|
|
|
func getJSON(t *testing.T, srv *httptest.Server, path string, token string) *http.Response {
|
|
t.Helper()
|
|
req, err := http.NewRequest(http.MethodGet, srv.URL+path, nil)
|
|
if err != nil {
|
|
t.Fatalf("build request: %v", err)
|
|
}
|
|
if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
resp, err := srv.Client().Do(req)
|
|
if err != nil {
|
|
t.Fatalf("do request: %v", err)
|
|
}
|
|
return resp
|
|
}
|
|
|
|
func decodeBody[T any](t *testing.T, resp *http.Response) T {
|
|
t.Helper()
|
|
defer resp.Body.Close()
|
|
var v T
|
|
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
|
|
t.Fatalf("decode response body: %v", err)
|
|
}
|
|
return v
|
|
}
|
|
|
|
func mustLogin(t *testing.T, srv *httptest.Server, username, password string) string {
|
|
t.Helper()
|
|
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
|
|
if err != nil {
|
|
t.Fatalf("build login request: %v", err)
|
|
}
|
|
req.SetBasicAuth(username, password)
|
|
|
|
resp, err := srv.Client().Do(req)
|
|
if err != nil {
|
|
t.Fatalf("do login request: %v", err)
|
|
}
|
|
if resp.StatusCode != http.StatusCreated {
|
|
t.Fatalf("login %s: expected 201, got %d", username, resp.StatusCode)
|
|
}
|
|
session := decodeBody[model.Session](t, resp)
|
|
return session.Token
|
|
}
|
|
|
|
func mustRegisterUser(t *testing.T, srv *httptest.Server, username string) testUser {
|
|
t.Helper()
|
|
const password = "correct-horse-battery-staple"
|
|
|
|
resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{
|
|
Username: username,
|
|
DisplayName: "Test " + username,
|
|
Password: password,
|
|
})
|
|
if resp.StatusCode != http.StatusCreated {
|
|
t.Fatalf("register %s: expected 201, got %d", username, resp.StatusCode)
|
|
}
|
|
u := decodeBody[model.User](t, resp)
|
|
|
|
token := mustLogin(t, srv, username, password)
|
|
return testUser{User: u, Token: token}
|
|
}
|
|
|
|
func mustCreateChat(t *testing.T, srv *httptest.Server, caller testUser, title string, memberIDs []string) model.Chat {
|
|
t.Helper()
|
|
resp := postJSON(t, srv, "/api/v1/chats", caller.Token, model.CreateChatRequest{
|
|
Title: title,
|
|
MemberIDs: memberIDs,
|
|
})
|
|
if resp.StatusCode != http.StatusCreated {
|
|
t.Fatalf("create chat: expected 201, got %d", resp.StatusCode)
|
|
}
|
|
return decodeBody[model.Chat](t, resp)
|
|
}
|
|
|
|
// тесты пользователи
|
|
|
|
func TestRegisterUser_DuplicateUsername_Returns409(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
mustRegisterUser(t, srv, "alice")
|
|
|
|
resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{
|
|
Username: "alice",
|
|
DisplayName: "Другая Алиса",
|
|
Password: "correct-horse-battery-staple",
|
|
})
|
|
if resp.StatusCode != http.StatusConflict {
|
|
t.Fatalf("expected 409, got %d", resp.StatusCode)
|
|
}
|
|
errBody := decodeBody[model.ErrorEnvelope](t, resp)
|
|
if errBody.Error.Code != "conflict" {
|
|
t.Fatalf("expected error code 'conflict', got %q", errBody.Error.Code)
|
|
}
|
|
if errBody.Error.RequestID == "" {
|
|
t.Fatal("expected non-empty request_id")
|
|
}
|
|
}
|
|
|
|
func TestRegisterUser_InvalidPasswordLength_Returns400(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
cases := []string{"short", strings.Repeat("a", 129)}
|
|
for _, password := range cases {
|
|
resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{
|
|
Username: "alice",
|
|
DisplayName: "Алиса",
|
|
Password: password,
|
|
})
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Errorf("password len %d: expected 400, got %d", len(password), resp.StatusCode)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRegisterUser_InvalidJSON_Returns400(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
resp := postJSON(t, srv, "/api/v1/users", "", `{"username":`)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("expected 400, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestRegisterUser_UnknownField_Returns400(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
resp := postJSON(t, srv, "/api/v1/users", "", `{"username":"bob","display_name":"Боб","password":"correct-horse-battery-staple","extra":"whatever"}`)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("expected 400 on unknown field, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestRegisterUser_InvalidUsernamePattern_Returns400(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
cases := []string{"AB", "ab", "Has-Dash", "こんにちは"}
|
|
for _, username := range cases {
|
|
resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{
|
|
Username: username,
|
|
DisplayName: "Тест",
|
|
Password: "correct-horse-battery-staple",
|
|
})
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Errorf("username %q: expected 400, got %d", username, resp.StatusCode)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCurrentUser_MissingHeader_Returns401(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
resp := getJSON(t, srv, "/api/v1/users/me", "")
|
|
if resp.StatusCode != http.StatusUnauthorized {
|
|
t.Fatalf("expected 401, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestCurrentUser_UnknownToken_Returns401(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
resp := getJSON(t, srv, "/api/v1/users/me", "totally-made-up-token")
|
|
if resp.StatusCode != http.StatusUnauthorized {
|
|
t.Fatalf("expected 401, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
//тесты вход и сессии
|
|
|
|
func TestCreateSession_WrongPassword_Returns401(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
mustRegisterUser(t, srv, "alice")
|
|
|
|
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
|
|
req.SetBasicAuth("alice", "totally-wrong-password")
|
|
resp, err := srv.Client().Do(req)
|
|
if err != nil {
|
|
t.Fatalf("do request: %v", err)
|
|
}
|
|
if resp.StatusCode != http.StatusUnauthorized {
|
|
t.Fatalf("expected 401, got %d", resp.StatusCode)
|
|
}
|
|
if resp.Header.Get("WWW-Authenticate") == "" {
|
|
t.Error("expected WWW-Authenticate header on failed login")
|
|
}
|
|
}
|
|
|
|
func TestCreateSession_UnknownUsername_Returns401(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
|
|
req.SetBasicAuth("nobody_here", "whatever-password-12")
|
|
resp, err := srv.Client().Do(req)
|
|
if err != nil {
|
|
t.Fatalf("do request: %v", err)
|
|
}
|
|
if resp.StatusCode != http.StatusUnauthorized {
|
|
t.Fatalf("expected 401, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestDeleteSession_ThenReuse_Returns401(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
|
|
req, _ := http.NewRequest(http.MethodDelete, srv.URL+"/api/v1/auth/sessions/current", nil)
|
|
req.Header.Set("Authorization", "Bearer "+alice.Token)
|
|
resp, err := srv.Client().Do(req)
|
|
if err != nil {
|
|
t.Fatalf("do logout request: %v", err)
|
|
}
|
|
if resp.StatusCode != http.StatusNoContent {
|
|
t.Fatalf("expected 204, got %d", resp.StatusCode)
|
|
}
|
|
|
|
// повторное использование отозванного токена -401
|
|
resp2 := getJSON(t, srv, "/api/v1/users/me", alice.Token)
|
|
if resp2.StatusCode != http.StatusUnauthorized {
|
|
t.Fatalf("expected 401 after logout, got %d", resp2.StatusCode)
|
|
}
|
|
}
|
|
|
|
//тесты чаты и membership
|
|
|
|
func TestCreateChat_CallerNotInMembers_Returns400(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
bob := mustRegisterUser(t, srv, "bob")
|
|
|
|
resp := postJSON(t, srv, "/api/v1/chats", alice.Token, model.CreateChatRequest{
|
|
Title: "Без себя",
|
|
MemberIDs: []string{bob.ID},
|
|
})
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("expected 400, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestCreateChat_DuplicateMemberIDs_Returns400(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
|
|
resp := postJSON(t, srv, "/api/v1/chats", alice.Token, model.CreateChatRequest{
|
|
Title: "Дубли",
|
|
MemberIDs: []string{alice.ID, alice.ID},
|
|
})
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("expected 400, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestGetChat_NotMember_Returns404NotForbidden(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
bob := mustRegisterUser(t, srv, "bob")
|
|
carol := mustRegisterUser(t, srv, "carol")
|
|
|
|
chat := mustCreateChat(t, srv, alice, "Приватный", []string{alice.ID, bob.ID})
|
|
|
|
resp := getJSON(t, srv, "/api/v1/chats/"+chat.ID, carol.Token)
|
|
if resp.StatusCode != http.StatusNotFound {
|
|
t.Fatalf("expected 404 for non-member (never 403), got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestGetChat_UnknownChatID_Returns404(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
|
|
resp := getJSON(t, srv, "/api/v1/chats/11111111-1111-4111-8111-111111111111", alice.Token)
|
|
if resp.StatusCode != http.StatusNotFound {
|
|
t.Fatalf("expected 404, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
// тесты: сообщения
|
|
|
|
func TestCreateMessage_EmptyText_Returns400(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
|
|
|
resp := postJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token, model.CreateMessageRequest{
|
|
Text: "",
|
|
})
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("expected 400 for empty text, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestCreateMessage_WhitespaceOnlyText_Returns400(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
|
|
|
resp := postJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token, model.CreateMessageRequest{
|
|
Text: " \t\n ",
|
|
})
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("expected 400 for whitespace-only text, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestCreateMessage_ForeignChat_Returns404(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
bob := mustRegisterUser(t, srv, "bob")
|
|
carol := mustRegisterUser(t, srv, "carol")
|
|
|
|
chat := mustCreateChat(t, srv, alice, "Приватный", []string{alice.ID, bob.ID})
|
|
|
|
resp := postJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), carol.Token, model.CreateMessageRequest{
|
|
Text: "Я тут чужая",
|
|
})
|
|
if resp.StatusCode != http.StatusNotFound {
|
|
t.Fatalf("expected 404 for foreign chat, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestCreateMessage_SenderIDIgnoredFromRequestBody(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
bob := mustRegisterUser(t, srv, "bob")
|
|
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID, bob.ID})
|
|
|
|
raw := fmt.Sprintf(`{"text":"Привет","sender_id":%q}`, bob.ID)
|
|
resp := postJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token, raw)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("expected 400 (unknown field sender_id), got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
// тесты пагинация
|
|
|
|
func TestListMessages_PaginationAcrossMultiplePages(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
|
|
|
const total = 5
|
|
for i := 0; i < total; i++ {
|
|
resp := postJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token, model.CreateMessageRequest{
|
|
Text: fmt.Sprintf("сообщение %d", i),
|
|
})
|
|
if resp.StatusCode != http.StatusCreated {
|
|
t.Fatalf("create message %d: expected 201, got %d", i, resp.StatusCode)
|
|
}
|
|
resp.Body.Close()
|
|
}
|
|
|
|
seen := make(map[string]bool)
|
|
cursor := ""
|
|
pages := 0
|
|
for {
|
|
path := fmt.Sprintf("/api/v1/chats/%s/messages?limit=2", chat.ID)
|
|
if cursor != "" {
|
|
path += "&cursor=" + cursor
|
|
}
|
|
resp := getJSON(t, srv, path, alice.Token)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("list messages: expected 200, got %d", resp.StatusCode)
|
|
}
|
|
page := decodeBody[model.MessagePage](t, resp)
|
|
pages++
|
|
|
|
for _, m := range page.Items {
|
|
if seen[m.ID] {
|
|
t.Fatalf("duplicate message across pages: %s", m.ID)
|
|
}
|
|
seen[m.ID] = true
|
|
}
|
|
|
|
if page.NextCursor == nil {
|
|
break
|
|
}
|
|
cursor = *page.NextCursor
|
|
|
|
if pages > total {
|
|
t.Fatal("too many pages — possible cursor bug (infinite loop)")
|
|
}
|
|
}
|
|
|
|
if len(seen) != total {
|
|
t.Fatalf("expected %d unique messages across all pages, got %d", total, len(seen))
|
|
}
|
|
if pages < 2 {
|
|
t.Fatalf("expected pagination to span multiple pages, got %d page(s)", pages)
|
|
}
|
|
}
|
|
|
|
func TestListMessages_CursorFromDifferentChat_Returns400(t *testing.T) {
|
|
srv := newTestServer(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
chatA := mustCreateChat(t, srv, alice, "Чат A", []string{alice.ID})
|
|
chatB := mustCreateChat(t, srv, alice, "Чат B", []string{alice.ID})
|
|
|
|
postJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chatA.ID), alice.Token, model.CreateMessageRequest{Text: "первое"}).Body.Close()
|
|
postJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chatA.ID), alice.Token, model.CreateMessageRequest{Text: "второе"}).Body.Close()
|
|
|
|
respA := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?limit=1", chatA.ID), alice.Token)
|
|
pageA := decodeBody[model.MessagePage](t, respA)
|
|
if pageA.NextCursor == nil {
|
|
t.Fatal("expected next_cursor to be present after inserting 2 messages with limit=1")
|
|
}
|
|
|
|
resp := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?cursor=%s", chatB.ID, *pageA.NextCursor), alice.Token)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("expected 400 for cross-chat cursor, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestCreateSession_RedisTTLExpires(t *testing.T) {
|
|
srv := newRedisTestServer(t)
|
|
defer srv.Close()
|
|
|
|
mustRegisterUser(t, srv, "alice")
|
|
|
|
t.Setenv("SESSION_TTL_SECONDS", "1")
|
|
|
|
token := mustLogin(t, srv, "alice", "correct-horse-battery-staple")
|
|
|
|
resp := getJSON(t, srv, "/api/v1/users/me", token)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("expected 200 immediately after login, got %d", resp.StatusCode)
|
|
}
|
|
resp.Body.Close()
|
|
|
|
time.Sleep(1500 * time.Millisecond)
|
|
|
|
resp = getJSON(t, srv, "/api/v1/users/me", token)
|
|
if resp.StatusCode != http.StatusUnauthorized {
|
|
t.Fatalf("expected 401 after session TTL expiration, got %d", resp.StatusCode)
|
|
}
|
|
resp.Body.Close()
|
|
}
|
|
|
|
func TestCurrentUser_RedisUnavailable_Returns503(t *testing.T) {
|
|
srv, s := newRedisTestServerWithStore(t)
|
|
defer srv.Close()
|
|
|
|
alice := mustRegisterUser(t, srv, "alice")
|
|
|
|
resp := getJSON(t, srv, "/api/v1/users/me", alice.Token)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("expected 200 before redis failure, got %d", resp.StatusCode)
|
|
}
|
|
resp.Body.Close()
|
|
|
|
redisDownClient := redis.NewClient(&redis.Options{
|
|
Addr: "127.0.0.1:1",
|
|
})
|
|
defer redisDownClient.Close()
|
|
|
|
redisDownSessionStore := sessionstore.NewRedis(redisDownClient)
|
|
|
|
downSrv := httptest.NewServer(
|
|
NewRouter(s, testPool, redisDownSessionStore),
|
|
)
|
|
defer downSrv.Close()
|
|
|
|
resp = getJSON(t, downSrv, "/api/v1/users/me", alice.Token)
|
|
if resp.StatusCode != http.StatusServiceUnavailable {
|
|
t.Fatalf(
|
|
"expected 503 when redis is unavailable, got %d",
|
|
resp.StatusCode,
|
|
)
|
|
}
|
|
resp.Body.Close()
|
|
|
|
}
|
|
|
|
func TestChatCache_ConcurrentRequests(t *testing.T) {
|
|
const concurrentRequests = 50
|
|
|
|
baselineSrv, baselineStore := newTestServerWithStore(t)
|
|
defer baselineSrv.Close()
|
|
|
|
baselineUser := mustRegisterUser(t, baselineSrv, "cachebaseline")
|
|
baselineChat := mustCreateChat(
|
|
t,
|
|
baselineSrv,
|
|
baselineUser,
|
|
"Cache baseline",
|
|
[]string{baselineUser.ID},
|
|
)
|
|
|
|
baselineStore.ResetChatSQLQueries()
|
|
|
|
start := make(chan struct{})
|
|
errCh := make(chan error, concurrentRequests)
|
|
|
|
baselineStart := time.Now()
|
|
|
|
for i := 0; i < concurrentRequests; i++ {
|
|
go func() {
|
|
<-start
|
|
|
|
_, err := baselineStore.GetChat(
|
|
context.Background(),
|
|
baselineChat.ID,
|
|
baselineUser.ID,
|
|
)
|
|
errCh <- err
|
|
}()
|
|
}
|
|
|
|
close(start)
|
|
|
|
for i := 0; i < concurrentRequests; i++ {
|
|
if err := <-errCh; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
baselineLatency := time.Since(baselineStart)
|
|
baselineQueries := baselineStore.ChatSQLQueries()
|
|
|
|
cachedSrv, cachedStore := newCachedRedisTestServer(t)
|
|
defer cachedSrv.Close()
|
|
|
|
cachedUser := mustRegisterUser(t, cachedSrv, "cacheprotected")
|
|
cachedChat := mustCreateChat(
|
|
t,
|
|
cachedSrv,
|
|
cachedUser,
|
|
"Cache protected",
|
|
[]string{cachedUser.ID},
|
|
)
|
|
|
|
cacheKey := "chat:" + cachedUser.ID + ":" + cachedChat.ID
|
|
|
|
if err := testRedis.Del(context.Background(), cacheKey).Err(); err != nil {
|
|
t.Fatalf("delete cache key: %v", err)
|
|
}
|
|
|
|
cachedStore.ResetChatSQLQueries()
|
|
|
|
start = make(chan struct{})
|
|
errCh = make(chan error, concurrentRequests)
|
|
|
|
cachedStart := time.Now()
|
|
|
|
for i := 0; i < concurrentRequests; i++ {
|
|
go func() {
|
|
<-start
|
|
|
|
resp := getJSON(
|
|
t,
|
|
cachedSrv,
|
|
"/api/v1/chats/"+cachedChat.ID,
|
|
cachedUser.Token,
|
|
)
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
errCh <- fmt.Errorf("unexpected status: %d", resp.StatusCode)
|
|
return
|
|
}
|
|
|
|
errCh <- nil
|
|
}()
|
|
}
|
|
|
|
close(start)
|
|
|
|
for i := 0; i < concurrentRequests; i++ {
|
|
if err := <-errCh; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
cachedLatency := time.Since(cachedStart)
|
|
cachedQueries := cachedStore.ChatSQLQueries()
|
|
|
|
t.Logf(
|
|
"baseline: requests=%d sql_queries=%d latency=%s",
|
|
concurrentRequests,
|
|
baselineQueries,
|
|
baselineLatency,
|
|
)
|
|
|
|
t.Logf(
|
|
"cold cache + singleflight: requests=%d sql_queries=%d latency=%s",
|
|
concurrentRequests,
|
|
cachedQueries,
|
|
cachedLatency,
|
|
)
|
|
|
|
expectedBaselineQueries := int64(concurrentRequests * 2)
|
|
|
|
if baselineQueries != expectedBaselineQueries {
|
|
t.Errorf(
|
|
"baseline: expected %d SQL queries, got %d",
|
|
expectedBaselineQueries,
|
|
baselineQueries,
|
|
)
|
|
}
|
|
|
|
if cachedQueries > 2 {
|
|
t.Errorf(
|
|
"cold cache + singleflight: expected <=2 SQL queries, got %d",
|
|
cachedQueries,
|
|
)
|
|
}
|
|
}
|
|
|
|
func TestChatCache_WarmCache(t *testing.T) {
|
|
const concurrentRequests = 50
|
|
|
|
srv, s := newCachedRedisTestServer(t)
|
|
defer srv.Close()
|
|
|
|
user := mustRegisterUser(t, srv, "cachewarm")
|
|
chat := mustCreateChat(
|
|
t,
|
|
srv,
|
|
user,
|
|
"Warm cache",
|
|
[]string{user.ID},
|
|
)
|
|
|
|
// Первый GET прогревает cache.
|
|
resp := getJSON(
|
|
t,
|
|
srv,
|
|
"/api/v1/chats/"+chat.ID,
|
|
user.Token,
|
|
)
|
|
resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("warm-up GET: unexpected status %d", resp.StatusCode)
|
|
}
|
|
|
|
s.ResetChatSQLQueries()
|
|
|
|
start := make(chan struct{})
|
|
errCh := make(chan error, concurrentRequests)
|
|
|
|
startedAt := time.Now()
|
|
|
|
for i := 0; i < concurrentRequests; i++ {
|
|
go func() {
|
|
<-start
|
|
|
|
resp := getJSON(
|
|
t,
|
|
srv,
|
|
"/api/v1/chats/"+chat.ID,
|
|
user.Token,
|
|
)
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
errCh <- fmt.Errorf(
|
|
"unexpected status: %d",
|
|
resp.StatusCode,
|
|
)
|
|
return
|
|
}
|
|
|
|
errCh <- nil
|
|
}()
|
|
}
|
|
|
|
close(start)
|
|
|
|
for i := 0; i < concurrentRequests; i++ {
|
|
if err := <-errCh; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
latency := time.Since(startedAt)
|
|
queries := s.ChatSQLQueries()
|
|
|
|
t.Logf(
|
|
"warm cache: requests=%d sql_queries=%d latency=%s",
|
|
concurrentRequests,
|
|
queries,
|
|
latency,
|
|
)
|
|
|
|
if queries != 0 {
|
|
t.Errorf(
|
|
"warm cache: expected 0 SQL queries, got %d",
|
|
queries,
|
|
)
|
|
}
|
|
}
|
|
|
|
func TestChatCache_ReadAfterWriteAndRecovery(t *testing.T) {
|
|
srv, s := newCachedRedisTestServer(t)
|
|
defer srv.Close()
|
|
|
|
user := mustRegisterUser(t, srv, "cacherecovery")
|
|
|
|
chat := mustCreateChat(
|
|
t,
|
|
srv,
|
|
user,
|
|
"Read after write",
|
|
[]string{user.ID},
|
|
)
|
|
|
|
s.ResetChatSQLQueries()
|
|
|
|
resp := getJSON(
|
|
t,
|
|
srv,
|
|
"/api/v1/chats/"+chat.ID,
|
|
user.Token,
|
|
)
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("read-after-write: unexpected status %d", resp.StatusCode)
|
|
}
|
|
|
|
got := decodeBody[model.Chat](t, resp)
|
|
|
|
if got.ID != chat.ID {
|
|
t.Fatalf(
|
|
"read-after-write: expected chat %s, got %s",
|
|
chat.ID,
|
|
got.ID,
|
|
)
|
|
}
|
|
|
|
if got.Title != "Read after write" {
|
|
t.Fatalf(
|
|
"read-after-write: expected title %q, got %q",
|
|
"Read after write",
|
|
got.Title,
|
|
)
|
|
}
|
|
|
|
if queries := s.ChatSQLQueries(); queries != 2 {
|
|
t.Fatalf(
|
|
"read-after-write: expected 2 SQL queries on cache miss, got %d",
|
|
queries,
|
|
)
|
|
}
|
|
|
|
cacheKey := "chat:" + user.ID + ":" + chat.ID
|
|
|
|
exists, err := testRedis.Exists(context.Background(), cacheKey).Result()
|
|
if err != nil {
|
|
t.Fatalf("check cache: %v", err)
|
|
}
|
|
|
|
if exists != 1 {
|
|
t.Fatalf("expected chat to be present in cache")
|
|
}
|
|
|
|
if err := testRedis.Del(context.Background(), cacheKey).Err(); err != nil {
|
|
t.Fatalf("delete cache: %v", err)
|
|
}
|
|
|
|
s.ResetChatSQLQueries()
|
|
|
|
resp2 := getJSON(
|
|
t,
|
|
srv,
|
|
"/api/v1/chats/"+chat.ID,
|
|
user.Token,
|
|
)
|
|
defer resp2.Body.Close()
|
|
|
|
if resp2.StatusCode != http.StatusOK {
|
|
t.Fatalf(
|
|
"recovery after cache loss: unexpected status %d",
|
|
resp2.StatusCode,
|
|
)
|
|
}
|
|
|
|
recovered := decodeBody[model.Chat](t, resp2)
|
|
|
|
if recovered.ID != chat.ID {
|
|
t.Fatalf(
|
|
"recovery: expected chat %s, got %s",
|
|
chat.ID,
|
|
recovered.ID,
|
|
)
|
|
}
|
|
|
|
if recovered.Title != chat.Title {
|
|
t.Fatalf(
|
|
"recovery: expected title %q, got %q",
|
|
chat.Title,
|
|
recovered.Title,
|
|
)
|
|
}
|
|
|
|
if queries := s.ChatSQLQueries(); queries != 2 {
|
|
t.Fatalf(
|
|
"recovery: expected 2 SQL queries after cache loss, got %d",
|
|
queries,
|
|
)
|
|
}
|
|
|
|
exists, err = testRedis.Exists(context.Background(), cacheKey).Result()
|
|
if err != nil {
|
|
t.Fatalf("check recovered cache: %v", err)
|
|
}
|
|
|
|
if exists != 1 {
|
|
t.Fatalf("expected cache to be restored after database read")
|
|
}
|
|
}
|