forked from mtusi2026/mtusi2026lab2
уровень 5 трек 1
This commit is contained in:
@@ -0,0 +1,952 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026/internal/auth"
|
||||
"mtusi2026/internal/config"
|
||||
"mtusi2026/internal/model"
|
||||
)
|
||||
|
||||
const sessionTTLEnvKey = "SESSION_TTL_SECONDS"
|
||||
|
||||
func (a *api) handleCreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "missing or malformed Basic credentials")
|
||||
return
|
||||
}
|
||||
|
||||
u, passwordHash, err := a.store.GetUserByUsername(r.Context(), username)
|
||||
if err != nil {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid username or password")
|
||||
return
|
||||
}
|
||||
|
||||
valid, err := auth.VerifyPassword(password, passwordHash)
|
||||
if err != nil || !valid {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid username or password")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := auth.GenerateSessionToken()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
|
||||
ttl := config.ParseDurationSecondsEnv(sessionTTLEnvKey, 3600)
|
||||
expiresAt, err := a.sessionStore.Create(r.Context(), token, u.ID, ttl)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "session service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, requestID, model.Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
User: u,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *api) handleDeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
|
||||
token, ok := bearerToken(r)
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "missing or malformed Bearer token")
|
||||
return
|
||||
}
|
||||
|
||||
deleted, err := a.sessionStore.Delete(r.Context(), token)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "session service unavailable")
|
||||
return
|
||||
}
|
||||
if !deleted {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "unknown or already revoked token")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) (string, bool) {
|
||||
h := r.Header.Get("Authorization")
|
||||
const prefix = "Bearer "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimPrefix(h, prefix)
|
||||
if token == "" {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
func parseLimit(r *http.Request) (int, bool) {
|
||||
raw := r.URL.Query().Get("limit")
|
||||
if raw == "" {
|
||||
return 50, true
|
||||
}
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
func (a *api) handleCreateChat(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
var req model.CreateChatRequest
|
||||
if err := decodeJSONStrict(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body")
|
||||
return
|
||||
}
|
||||
|
||||
c, err := a.store.CreateChat(r.Context(), u.ID, req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
if err == store.ErrValidation {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, requestID, c)
|
||||
}
|
||||
|
||||
func (a *api) handleListChats(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
limit, ok := parseLimit(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid limit")
|
||||
return
|
||||
}
|
||||
cursorStr := r.URL.Query().Get("cursor")
|
||||
|
||||
items, next, err := a.store.ListChatsForUser(r.Context(), u.ID, cursorStr, limit)
|
||||
if err != nil {
|
||||
if err == store.ErrValidation {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []model.Chat{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, model.ChatPage{Items: items, NextCursor: next})
|
||||
}
|
||||
|
||||
func (a *api) handleGetChat(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
if a.chatCache != nil {
|
||||
c, hit, err := a.chatCache.Get(r.Context(), u.ID, chatID)
|
||||
if err == nil && hit {
|
||||
writeJSON(w, http.StatusOK, requestID, c)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
flightKey := u.ID + ":" + chatID
|
||||
|
||||
result, err, _ := a.chatFlight.Do(flightKey, func() (any, error) {
|
||||
if a.chatCache != nil {
|
||||
c, hit, err := a.chatCache.Get(r.Context(), u.ID, chatID)
|
||||
if err == nil && hit {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
c, err := a.store.GetChat(r.Context(), chatID, u.ID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
if a.chatCache != nil {
|
||||
_ = a.chatCache.Set(r.Context(), u.ID, chatID, c)
|
||||
}
|
||||
|
||||
return c, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
|
||||
return
|
||||
}
|
||||
|
||||
c, ok := result.(model.Chat)
|
||||
if !ok {
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, requestID, c)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func handleHealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, newRequestID(), map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func handleHealthReady(pool *pgxpool.Pool) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, map[string]string{"status": "ok"})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type errorCode string
|
||||
|
||||
const (
|
||||
codeInvalidRequest errorCode = "invalid_request"
|
||||
codeUnauthorized errorCode = "unauthorized"
|
||||
codeNotFound errorCode = "not_found"
|
||||
codeConflict errorCode = "conflict"
|
||||
codeUnavailable errorCode = "unavailable"
|
||||
codeInternal errorCode = "internal_error"
|
||||
)
|
||||
|
||||
func newRequestID() string {
|
||||
b := make([]byte, 12)
|
||||
_, _ = rand.Read(b)
|
||||
return fmt.Sprintf("%x", b)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, requestID string, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.WriteHeader(status)
|
||||
if payload != nil {
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, requestID string, code errorCode, message string) {
|
||||
writeJSON(w, status, requestID, map[string]any{
|
||||
"error": map[string]any{
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": requestID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func decodeJSONStrict(r *http.Request, dst any) error {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
if err == io.EOF {
|
||||
return fmt.Errorf("empty body")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if dec.More() {
|
||||
return fmt.Errorf("trailing data after JSON body")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
var req model.CreateMessageRequest
|
||||
if err := decodeJSONStrict(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body")
|
||||
return
|
||||
}
|
||||
|
||||
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, req.Text)
|
||||
if err != nil {
|
||||
switch err {
|
||||
case store.ErrChatNotFound:
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
|
||||
case store.ErrCapacityExceeded:
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "message storage capacity reached")
|
||||
case store.ErrValidation:
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid text")
|
||||
default:
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, requestID, m)
|
||||
}
|
||||
|
||||
func (a *api) handleListMessages(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
limit, ok := parseLimit(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid limit")
|
||||
return
|
||||
}
|
||||
cursorStr := r.URL.Query().Get("cursor")
|
||||
|
||||
items, next, err := a.store.ListMessages(r.Context(), chatID, u.ID, cursorStr, limit)
|
||||
if err != nil {
|
||||
switch err {
|
||||
case store.ErrChatNotFound:
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
|
||||
case store.ErrValidation:
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
|
||||
default:
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []model.Message{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, model.MessagePage{Items: items, NextCursor: next})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(status int) {
|
||||
r.status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
log.Printf("method=%s path=%s status=%d duration=%s",
|
||||
r.Method, r.URL.Path, rec.status, time.Since(start))
|
||||
})
|
||||
}
|
||||
|
||||
func concurrencyMiddleware(limiter *store.Limiter, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !limiter.TryAcquire() {
|
||||
requestID := newRequestID()
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "сервер перегружен, попробуйте позже")
|
||||
return
|
||||
}
|
||||
defer limiter.Release()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"mtusi2026/internal/model"
|
||||
)
|
||||
|
||||
func TestConcurrentMessages_NoLostOrDuplicated(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chat := mustCreateChat(t, srv, alice, "нагрузочный чат", []string{alice.ID})
|
||||
const clients = 10
|
||||
const perClients = 10
|
||||
const total = clients * perClients
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, total)
|
||||
client := srv.Client()
|
||||
|
||||
for c := 0; c < clients; c++ {
|
||||
wg.Add(1)
|
||||
go func(clientNum int) {
|
||||
defer wg.Done()
|
||||
for i := 0; i < perClients; i++ {
|
||||
text := fmt.Sprintf("client-%d-msg-%d", clientNum, i)
|
||||
body, _ := json.Marshal(model.CreateMessageRequest{Text: text})
|
||||
req, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", srv.URL, chat.ID),
|
||||
bytes.NewReader(body),
|
||||
)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("client %d: build request: %w", clientNum, err)
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+alice.Token)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("client %d: do request: %w", clientNum, err)
|
||||
continue
|
||||
}
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
errCh <- fmt.Errorf("client %d msg %d: expected 201, got %d", clientNum, i, resp.StatusCode)
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
}(c)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
|
||||
for err := range errCh {
|
||||
t.Error(err)
|
||||
}
|
||||
if t.Failed() {
|
||||
t.Fatal("прекращение из-за ошбок запросов")
|
||||
}
|
||||
|
||||
resp := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?limit=100", chat.ID), alice.Token)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("list messages: expected 200, got %d", resp.StatusCode)
|
||||
}
|
||||
page := decodeBody[model.MessagePage](t, resp)
|
||||
|
||||
if page.NextCursor != nil {
|
||||
t.Fatalf("expected all %d messages to fit on one page with limit=100, got next_cursor", total)
|
||||
}
|
||||
if len(page.Items) != total {
|
||||
t.Fatalf("expected exactly %d messages, got %d", total, len(page.Items))
|
||||
}
|
||||
|
||||
seen := make(map[string]bool, total)
|
||||
for _, m := range page.Items {
|
||||
if seen[m.ID] {
|
||||
t.Fatalf("duplicate message ID found: %s", m.ID)
|
||||
}
|
||||
seen[m.ID] = true
|
||||
if m.SenderID != alice.ID {
|
||||
t.Fatalf("unexpected sender_id: %s", m.SenderID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterUser_ConcurrentDuplicateUsername_OnlyOneSucceeds(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
const workers = 20
|
||||
|
||||
statuses := make(chan int, workers)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(workers)
|
||||
|
||||
for i := 0; i < workers; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
body := `{
|
||||
"username": "raceuser",
|
||||
"display_name": "Race User",
|
||||
"password": "correct-horse-battery-staple"
|
||||
}`
|
||||
|
||||
req, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
srv.URL+"/api/v1/users",
|
||||
strings.NewReader(body),
|
||||
)
|
||||
if err != nil {
|
||||
statuses <- -1
|
||||
return
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
statuses <- -1
|
||||
return
|
||||
}
|
||||
|
||||
statuses <- resp.StatusCode
|
||||
resp.Body.Close()
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(statuses)
|
||||
|
||||
created := 0
|
||||
conflicts := 0
|
||||
|
||||
for status := range statuses {
|
||||
switch status {
|
||||
case http.StatusCreated:
|
||||
created++
|
||||
case http.StatusConflict:
|
||||
conflicts++
|
||||
default:
|
||||
t.Errorf("unexpected status code: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
if created != 1 {
|
||||
t.Fatalf("ожидалась одна успешная регистрация, got %d", created)
|
||||
}
|
||||
|
||||
if conflicts != workers-1 {
|
||||
t.Fatalf("expected %d conflicts, got %d", workers-1, conflicts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026/internal/cache"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/sessionstore"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
func NewRouter(s *store.Store, pool *pgxpool.Pool, sessionStores ...sessionstore.Store) http.Handler {
|
||||
var ss sessionstore.Store
|
||||
if len(sessionStores) > 0 {
|
||||
ss = sessionStores[0]
|
||||
}
|
||||
|
||||
a := &api{
|
||||
store: s,
|
||||
sessionStore: ss,
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", handleHealthLive)
|
||||
mux.HandleFunc("GET /health/ready", handleHealthReady(pool))
|
||||
|
||||
mux.HandleFunc("POST /api/v1/users", a.handleRegisterUser)
|
||||
mux.HandleFunc("GET /api/v1/users/me", a.authMiddleware(a.handleCurrentUser))
|
||||
|
||||
mux.HandleFunc("POST /api/v1/chats", a.authMiddleware(a.handleCreateChat))
|
||||
mux.HandleFunc("GET /api/v1/chats", a.authMiddleware(a.handleListChats))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", a.authMiddleware(a.handleGetChat))
|
||||
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleCreateMessage))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleListMessages))
|
||||
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", a.handleCreateSession)
|
||||
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.authMiddleware(func(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
a.handleDeleteSession(w, r)
|
||||
}))
|
||||
|
||||
var handler http.Handler = mux
|
||||
handler = loggingMiddleware(handler)
|
||||
handler = concurrencyMiddleware(s.Limiter, handler)
|
||||
return handler
|
||||
}
|
||||
|
||||
func NewRouterWithCache(
|
||||
s *store.Store,
|
||||
pool *pgxpool.Pool,
|
||||
sessionStore sessionstore.Store,
|
||||
chatCache *cache.Cache,
|
||||
) http.Handler {
|
||||
a := &api{
|
||||
store: s,
|
||||
sessionStore: sessionStore,
|
||||
chatCache: chatCache,
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", handleHealthLive)
|
||||
mux.HandleFunc("GET /health/ready", handleHealthReady(pool))
|
||||
mux.HandleFunc("POST /api/v1/users", a.handleRegisterUser)
|
||||
mux.HandleFunc("GET /api/v1/users/me", a.authMiddleware(a.handleCurrentUser))
|
||||
mux.HandleFunc("POST /api/v1/chats", a.authMiddleware(a.handleCreateChat))
|
||||
mux.HandleFunc("GET /api/v1/chats", a.authMiddleware(a.handleListChats))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", a.authMiddleware(a.handleGetChat))
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleCreateMessage))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleListMessages))
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", a.handleCreateSession)
|
||||
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.authMiddleware(func(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
a.handleDeleteSession(w, r)
|
||||
}))
|
||||
|
||||
var handler http.Handler = mux
|
||||
handler = loggingMiddleware(handler)
|
||||
handler = concurrencyMiddleware(s.Limiter, handler)
|
||||
|
||||
return handler
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/sessionstore"
|
||||
)
|
||||
|
||||
type memorySession struct {
|
||||
userID string
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type memorySessionStore struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]memorySession
|
||||
}
|
||||
|
||||
func newMemorySessionStore() *memorySessionStore {
|
||||
return &memorySessionStore{
|
||||
sessions: make(map[string]memorySession),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *memorySessionStore) Create(
|
||||
_ context.Context,
|
||||
token string,
|
||||
userID string,
|
||||
ttl time.Duration,
|
||||
) (time.Time, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
expiresAt := time.Now().UTC().Add(ttl)
|
||||
s.sessions[token] = memorySession{
|
||||
userID: userID,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
return expiresAt, nil
|
||||
}
|
||||
|
||||
func (s *memorySessionStore) GetUserID(
|
||||
_ context.Context,
|
||||
token string,
|
||||
) (string, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
session, ok := s.sessions[token]
|
||||
if !ok || !time.Now().UTC().Before(session.expiresAt) {
|
||||
delete(s.sessions, token)
|
||||
return "", sessionstore.ErrNotFound
|
||||
}
|
||||
|
||||
return session.userID, nil
|
||||
}
|
||||
|
||||
func (s *memorySessionStore) Delete(
|
||||
_ context.Context,
|
||||
token string,
|
||||
) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if _, ok := s.sessions[token]; !ok {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
delete(s.sessions, token)
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
tcredis "github.com/testcontainers/testcontainers-go/modules/redis"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
)
|
||||
|
||||
var testPool *pgxpool.Pool
|
||||
var testRedis *redis.Client
|
||||
|
||||
// поднимает эфемерный Postgres в Docker применяет миграции даёт testPool
|
||||
// всем тестам пакета и гарантированно убивает контейнер в конце прогона :)
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
|
||||
pgContainer, err := tcpostgres.Run(ctx,
|
||||
"postgres:16.4-alpine",
|
||||
tcpostgres.WithDatabase("messenger_test"),
|
||||
tcpostgres.WithUsername("messenger_test"),
|
||||
tcpostgres.WithPassword("messenger_test"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatalf("start postgres container: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := pgContainer.Terminate(ctx); err != nil {
|
||||
log.Printf("terminate postgres container: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
dsn, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
if err != nil {
|
||||
log.Fatalf("get connection string: %v", err)
|
||||
}
|
||||
|
||||
if err := applyMigrations(dsn); err != nil {
|
||||
log.Fatalf("apply migrations: %v", err)
|
||||
}
|
||||
|
||||
poolCfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
log.Fatalf("parse pool config: %v", err)
|
||||
}
|
||||
testPool, err = pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
log.Fatalf("create pool: %v", err)
|
||||
}
|
||||
defer testPool.Close()
|
||||
|
||||
if err := testPool.Ping(ctx); err != nil {
|
||||
log.Fatalf("ping test db: %v", err)
|
||||
}
|
||||
|
||||
redisContainer, err := tcredis.Run(ctx, "redis:7.4-alpine")
|
||||
if err != nil {
|
||||
log.Fatalf("start redis container: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := testcontainers.TerminateContainer(redisContainer); err != nil {
|
||||
log.Printf("terminate redis container: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
redisURL, err := redisContainer.ConnectionString(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("get redis connection string: %v", err)
|
||||
}
|
||||
|
||||
redisOpts, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
log.Fatalf("parse redis url: %v", err)
|
||||
}
|
||||
|
||||
testRedis = redis.NewClient(redisOpts)
|
||||
defer testRedis.Close()
|
||||
|
||||
if err := testRedis.Ping(ctx).Err(); err != nil {
|
||||
log.Fatalf("ping test redis: %v", err)
|
||||
}
|
||||
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
// тесты запускаются из internal/httpapi/ поэтому путь на три уровня вверх
|
||||
// и прогоняет все .up.sql через golang-migrate
|
||||
func applyMigrations(dsn string) error {
|
||||
migrationsPath, err := filepath.Abs(filepath.Join("..", "..", "migrations"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
u.Scheme = "pgx5"
|
||||
|
||||
m, err := migrate.New(
|
||||
fmt.Sprintf("file://%s", migrationsPath),
|
||||
u.String(),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrate.New: %w", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
|
||||
return fmt.Errorf("migrate.Up: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// truncateAll очищает все таблицы между тестами сохраняя схему
|
||||
// быстрее чем пересоздавать контейнер на каждый тест
|
||||
func truncateAll(t *testing.T) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
_, err := testPool.Exec(ctx,
|
||||
`TRUNCATE TABLE messages, chat_members, chats, sessions, users RESTART IDENTITY CASCADE`,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("truncate tables: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
func TestCreateChat_RollsBackOnMemberInsertFailure(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "rollback_alice")
|
||||
|
||||
ctx := context.Background()
|
||||
s := store.New(testPool, newUnlimitedLimiter())
|
||||
|
||||
missingUserID := "00000000-0000-0000-0000-000000000000"
|
||||
|
||||
_, err := s.CreateChat(
|
||||
ctx,
|
||||
alice.ID,
|
||||
"rollback-test",
|
||||
[]string{alice.ID, missingUserID},
|
||||
)
|
||||
|
||||
if !errors.Is(err, store.ErrValidation) {
|
||||
t.Fatalf("expected ErrValidation, got %v", err)
|
||||
}
|
||||
|
||||
var chatCount int
|
||||
err = testPool.QueryRow(
|
||||
ctx,
|
||||
`SELECT COUNT(*) FROM chats WHERE title = $1`,
|
||||
"rollback-test",
|
||||
).Scan(&chatCount)
|
||||
if err != nil {
|
||||
t.Fatalf("check chats after rollback: %v", err)
|
||||
}
|
||||
|
||||
if chatCount != 0 {
|
||||
t.Fatalf("expected 0 chats after rollback, got %d", chatCount)
|
||||
}
|
||||
|
||||
var membershipCount int
|
||||
err = testPool.QueryRow(
|
||||
ctx,
|
||||
`SELECT COUNT(*)
|
||||
FROM chat_members cm
|
||||
JOIN chats c ON c.id = cm.chat_id
|
||||
WHERE c.title = $1`,
|
||||
"rollback-test",
|
||||
).Scan(&membershipCount)
|
||||
if err != nil {
|
||||
t.Fatalf("check chat_members after rollback: %v", err)
|
||||
}
|
||||
|
||||
if membershipCount != 0 {
|
||||
t.Fatalf("expected 0 chat members after rollback, got %d", membershipCount)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"mtusi2026/internal/auth"
|
||||
"mtusi2026/internal/cache"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/sessionstore"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type api struct {
|
||||
store *store.Store
|
||||
sessionStore sessionstore.Store
|
||||
chatCache *cache.Cache
|
||||
chatFlight singleflight.Group
|
||||
}
|
||||
|
||||
func (a *api) authMiddleware(next func(w http.ResponseWriter, r *http.Request, u model.User, requestID string)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
|
||||
token, ok := bearerToken(r)
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "missing or malformed Bearer token")
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := a.sessionStore.GetUserID(r.Context(), token)
|
||||
if err != nil {
|
||||
if errors.Is(err, sessionstore.ErrNotFound) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid, expired or revoked token")
|
||||
return
|
||||
}
|
||||
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "session service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
u, ok, err := a.store.GetUserByID(r.Context(), userID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "database unavailable")
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid session user")
|
||||
return
|
||||
}
|
||||
|
||||
next(w, r, u, requestID)
|
||||
}
|
||||
}
|
||||
|
||||
func validDisplayName(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
func validPassword(s string) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 12 && n <= 128
|
||||
}
|
||||
|
||||
func (a *api) handleRegisterUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
|
||||
var req model.CreateUserRequest
|
||||
if err := decodeJSONStrict(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body")
|
||||
return
|
||||
}
|
||||
|
||||
if !usernameRe.MatchString(req.Username) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "username must match ^[a-z0-9_]{3,32}$")
|
||||
return
|
||||
}
|
||||
if !validDisplayName(req.DisplayName) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "display_name must be 1-100 non-blank code points")
|
||||
return
|
||||
}
|
||||
if !validPassword(req.Password) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "password must be 12-128 code points")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := auth.HashPassword(req.Password)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
|
||||
u, err := a.store.CreateUser(r.Context(), req.Username, req.DisplayName, passwordHash)
|
||||
if err != nil {
|
||||
if err == store.ErrUsernameTaken {
|
||||
writeError(w, http.StatusConflict, requestID, codeConflict, "username already taken")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, requestID, u)
|
||||
}
|
||||
|
||||
func (a *api) handleCurrentUser(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
writeJSON(w, http.StatusOK, requestID, u)
|
||||
}
|
||||
Reference in New Issue
Block a user