This commit is contained in:
2026-10-22 18:41:56 +03:00
parent 665c37c0b8
commit 3695ab6dfa
32 changed files with 881 additions and 156 deletions
+45 -14
View File
@@ -12,6 +12,7 @@ import (
"time"
"mtusi2026/internal/cache"
"mtusi2026/internal/idgen"
"mtusi2026/internal/model"
"mtusi2026/internal/sessionstore"
"mtusi2026/internal/store"
@@ -21,6 +22,39 @@ import (
//вспомогательные функции
func newKey() string { return idgen.GenerateUUIDv4() }
func doMessage(srv *httptest.Server, chatID, token, key string, body any) (*http.Response, error) {
var buf bytes.Buffer
if s, ok := body.(string); ok {
buf.WriteString(s)
} else if err := json.NewEncoder(&buf).Encode(body); err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost,
fmt.Sprintf("%s/api/v1/chats/%s/messages", srv.URL, chatID), &buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
if key != "" {
req.Header.Set("Idempotency-Key", key)
}
return srv.Client().Do(req)
}
func postMessage(t *testing.T, srv *httptest.Server, chatID, token, key string, body any) *http.Response {
t.Helper()
resp, err := doMessage(srv, chatID, token, key, body)
if err != nil {
t.Fatalf("do request: %v", err)
}
return resp
}
func newUnlimitedLimiter() *store.Limiter {
return store.NewLimiter(1_000_000, 1000)
}
@@ -412,9 +446,8 @@ func TestCreateMessage_EmptyText_Returns400(t *testing.T) {
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: "",
})
resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: ""})
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400 for empty text, got %d", resp.StatusCode)
}
@@ -427,9 +460,8 @@ func TestCreateMessage_WhitespaceOnlyText_Returns400(t *testing.T) {
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 ",
})
resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: " \t\n "})
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400 for whitespace-only text, got %d", resp.StatusCode)
}
@@ -445,9 +477,8 @@ func TestCreateMessage_ForeignChat_Returns404(t *testing.T) {
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: "Я тут чужая",
})
resp := postMessage(t, srv, chat.ID, carol.Token, newKey(), model.CreateMessageRequest{Text: "Я тут чужая"})
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("expected 404 for foreign chat, got %d", resp.StatusCode)
}
@@ -462,7 +493,7 @@ func TestCreateMessage_SenderIDIgnoredFromRequestBody(t *testing.T) {
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)
resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), raw)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400 (unknown field sender_id), got %d", resp.StatusCode)
}
@@ -479,7 +510,7 @@ func TestListMessages_PaginationAcrossMultiplePages(t *testing.T) {
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{
resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), model.CreateMessageRequest{
Text: fmt.Sprintf("сообщение %d", i),
})
if resp.StatusCode != http.StatusCreated {
@@ -536,8 +567,8 @@ func TestListMessages_CursorFromDifferentChat_Returns400(t *testing.T) {
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()
postMessage(t, srv, chatA.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: "первое"}).Body.Close()
postMessage(t, srv, chatA.ID, alice.Token, newKey(), 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)
@@ -761,7 +792,7 @@ func TestChatCache_WarmCache(t *testing.T) {
[]string{user.ID},
)
// Первый GET прогревает cache.
// Первый GET прогревает cache
resp := getJSON(
t,
srv,
+13 -1
View File
@@ -3,18 +3,24 @@ package httpapi
import (
"context"
"net/http"
"sync/atomic"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
)
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 {
func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, draining *atomic.Bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestID := newRequestID()
if draining.Load() {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "shutting down")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
@@ -22,6 +28,12 @@ func handleHealthReady(pool *pgxpool.Pool) http.HandlerFunc {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
return
}
if rdb != nil {
if err := rdb.Ping(ctx).Err(); err != nil {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "session store unavailable")
return
}
}
writeJSON(w, http.StatusOK, requestID, map[string]string{"status": "ok"})
}
}
+184
View File
@@ -0,0 +1,184 @@
package httpapi
import (
"fmt"
"net/http"
"strings"
"sync"
"testing"
"mtusi2026/internal/model"
)
func TestIdempotency_RepeatReturnsSameMessage(t *testing.T) {
srv := newTestServer(t)
defer srv.Close()
alice := mustRegisterUser(t, srv, "alice")
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
key := newKey()
body := model.CreateMessageRequest{Text: "привет"}
r1 := postMessage(t, srv, chat.ID, alice.Token, key, body)
if r1.StatusCode != http.StatusCreated {
t.Fatalf("first: expected 201, got %d", r1.StatusCode)
}
m1 := decodeBody[model.Message](t, r1)
r2 := postMessage(t, srv, chat.ID, alice.Token, key, body)
if r2.StatusCode != http.StatusCreated {
t.Fatalf("repeat: expected 201, got %d", r2.StatusCode)
}
m2 := decodeBody[model.Message](t, r2)
if m1.ID != m2.ID || !m1.CreatedAt.Equal(m2.CreatedAt) {
t.Fatalf("repeat returned a different message: %+v vs %+v", m1, m2)
}
page := decodeBody[model.MessagePage](t,
getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token))
if len(page.Items) != 1 {
t.Fatalf("expected 1 message in history, got %d", len(page.Items))
}
}
func TestIdempotency_DifferentBodySameKey_Returns409(t *testing.T) {
srv := newTestServer(t)
defer srv.Close()
alice := mustRegisterUser(t, srv, "alice")
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
key := newKey()
postMessage(t, srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "один"}).Body.Close()
resp := postMessage(t, srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "два"})
defer resp.Body.Close()
if resp.StatusCode != http.StatusConflict {
t.Fatalf("expected 409, got %d", resp.StatusCode)
}
}
func TestIdempotency_MissingOrInvalidKey_Returns400(t *testing.T) {
srv := newTestServer(t)
defer srv.Close()
alice := mustRegisterUser(t, srv, "alice")
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
keys := map[string]string{
"missing": "",
"space": "bad key",
"too long": strings.Repeat("a", 129),
"cyrillic": "ключ",
}
for name, key := range keys {
resp := postMessage(t, srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "x"})
resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("%s: expected 400, got %d", name, resp.StatusCode)
}
}
}
func TestIdempotency_ConcurrentSameKey_OneMessage(t *testing.T) {
srv := newTestServer(t)
defer srv.Close()
alice := mustRegisterUser(t, srv, "alice")
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
const workers = 20
key := newKey()
start := make(chan struct{})
type result struct {
status int
id string
err error
}
results := make(chan result, workers)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
resp, err := doMessage(srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "гонка"})
if err != nil {
results <- result{err: err}
return
}
defer resp.Body.Close()
var m model.Message
_ = t.Fatal
results <- result{status: resp.StatusCode, id: m.ID}
}()
}
close(start)
wg.Wait()
close(results)
ids := map[string]bool{}
for r := range results {
if r.err != nil {
t.Errorf("request error: %v", r.err)
continue
}
if r.status != http.StatusCreated {
t.Errorf("expected 201, got %d", r.status)
}
ids[r.id] = true
}
if len(ids) != 1 {
t.Fatalf("expected one distinct message id, got %d", len(ids))
}
page := decodeBody[model.MessagePage](t,
getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token))
if len(page.Items) != 1 {
t.Fatalf("expected exactly 1 message stored, got %d", len(page.Items))
}
}
func TestIdempotency_ScopeIsPerUserAndChat(t *testing.T) {
srv := newTestServer(t)
defer srv.Close()
alice := mustRegisterUser(t, srv, "alice")
bob := mustRegisterUser(t, srv, "bob")
chatA := mustCreateChat(t, srv, alice, "A", []string{alice.ID, bob.ID})
chatB := mustCreateChat(t, srv, alice, "B", []string{alice.ID, bob.ID})
key := newKey()
body := model.CreateMessageRequest{Text: "то же самое"}
ids := map[string]bool{}
for _, c := range []struct {
chat string
token string
}{
{chatA.ID, alice.Token}, {chatB.ID, alice.Token}, {chatA.ID, bob.Token},
} {
resp := postMessage(t, srv, c.chat, c.token, key, body)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("expected 201, got %d", resp.StatusCode)
}
ids[decodeBody[model.Message](t, resp).ID] = true
}
if len(ids) != 3 {
t.Fatalf("same key in different scopes must create 3 messages, got %d", len(ids))
}
}
func TestIdempotency_ForeignChatRepeat_Returns404(t *testing.T) {
srv := newTestServer(t)
defer srv.Close()
alice := mustRegisterUser(t, srv, "alice")
carol := mustRegisterUser(t, srv, "carol")
chat := mustCreateChat(t, srv, alice, "Приватный", []string{alice.ID})
key := newKey()
for i := 0; i < 2; i++ {
resp := postMessage(t, srv, chat.ID, carol.Token, key, model.CreateMessageRequest{Text: "чужой"})
resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("attempt %d: expected 404, got %d", i, resp.StatusCode)
}
}
}
+16 -7
View File
@@ -1,36 +1,45 @@
package httpapi
import (
"errors"
"net/http"
"regexp"
"mtusi2026/internal/model"
"mtusi2026/internal/store"
)
var idemKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
chatID := r.PathValue("chat_id")
key := r.Header.Get("Idempotency-Key")
if !idemKeyRe.MatchString(key) {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "missing or invalid Idempotency-Key")
return
}
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)
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text)
if err != nil {
switch err {
case store.ErrChatNotFound:
switch {
case errors.Is(err, 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:
case errors.Is(err, store.ErrIdempotencyConflict):
writeError(w, http.StatusConflict, requestID, codeConflict, "Idempotency-Key was used with a different request body")
case errors.Is(err, 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)
}
+1
View File
@@ -44,6 +44,7 @@ func TestConcurrentMessages_NoLostOrDuplicated(t *testing.T) {
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+alice.Token)
req.Header.Set("Idempotency-Key", fmt.Sprintf("race-%d-%d", clientNum, i))
resp, err := client.Do(req)
if err != nil {
errCh <- fmt.Errorf("client %d: do request: %w", clientNum, err)
+47 -47
View File
@@ -2,8 +2,10 @@ package httpapi
import (
"net/http"
"sync/atomic"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"mtusi2026/internal/cache"
"mtusi2026/internal/model"
@@ -11,40 +13,18 @@ import (
"mtusi2026/internal/store"
)
type Options struct {
InstanceID string
Redis *redis.Client
Draining *atomic.Bool
}
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
return NewRouterWithCache(s, pool, ss, nil)
}
func NewRouterWithCache(
@@ -52,33 +32,53 @@ func NewRouterWithCache(
pool *pgxpool.Pool,
sessionStore sessionstore.Store,
chatCache *cache.Cache,
opts ...Options,
) http.Handler {
var o Options
if len(opts) > 0 {
o = opts[0]
}
if o.InstanceID == "" {
o.InstanceID = "local"
}
if o.Draining == nil {
o.Draining = new(atomic.Bool)
}
a := &api{
store: s,
sessionStore: sessionStore,
chatCache: chatCache,
}
apiMux := http.NewServeMux()
apiMux.HandleFunc("POST /api/v1/users", a.handleRegisterUser)
apiMux.HandleFunc("GET /api/v1/users/me", a.authMiddleware(a.handleCurrentUser))
apiMux.HandleFunc("POST /api/v1/chats", a.authMiddleware(a.handleCreateChat))
apiMux.HandleFunc("GET /api/v1/chats", a.authMiddleware(a.handleListChats))
apiMux.HandleFunc("GET /api/v1/chats/{chat_id}", a.authMiddleware(a.handleGetChat))
apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleCreateMessage))
apiMux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleListMessages))
apiMux.HandleFunc("POST /api/v1/auth/sessions", a.handleCreateSession)
apiMux.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)
}))
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)
}))
root := http.NewServeMux()
root.HandleFunc("GET /health/live", handleHealthLive)
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Draining))
root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux))
var handler http.Handler = mux
handler = loggingMiddleware(handler)
handler = concurrencyMiddleware(s.Limiter, handler)
var h http.Handler = root
h = loggingMiddleware(h)
h = instanceMiddleware(o.InstanceID, h)
return h
}
return handler
func instanceMiddleware(id string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", id)
next.ServeHTTP(w, r)
})
}