ЛР 2: PostgreSQL, сессии в Valkey, кэш истории (трек 1)

This commit is contained in:
Нурлыгаянова Екатерина
2026-10-29 11:29:38 +03:00
parent 65003b6119
commit 1503b5db81
132 changed files with 15114 additions and 20 deletions
+312
View File
@@ -0,0 +1,312 @@
package http
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
)
func TestLimits_PayloadTooLarge(t *testing.T) {
r := newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: 256,
MaxInFlight: 16,
MaxMessagesGlobal: 100,
MaxHeapBytes: 1 << 40,
})
alice := r.createUser("a_"+randomSuffix(), "Алиса")
bob := r.createUser("b_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
ok, _, _ := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: "ok"}))
if ok != http.StatusCreated {
t.Fatalf("baseline send expected 201, got %d", ok)
}
stored := r.memory.MessagesTotal()
if stored != 1 {
t.Fatalf("baseline total expected 1, got %d", stored)
}
big := strings.Repeat("x", 512)
status, _, body := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: big}))
if status != http.StatusRequestEntityTooLarge {
t.Fatalf("expected 413 by content-length, got %d body=%s", status, string(body))
}
code := extractErrorCode(t, body)
if code != CodePayloadTooLarge {
t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code)
}
if got := r.memory.MessagesTotal(); got != stored {
t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got)
}
}
func TestLimits_PayloadBoundaries(t *testing.T) {
const limit = 256
r := newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: limit,
MaxInFlight: 16,
MaxMessagesGlobal: 100,
MaxHeapBytes: 1 << 40,
})
alice := r.createUser("a_"+randomSuffix(), "Алиса")
bob := r.createUser("b_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
exact := []byte(`{"text":"` + strings.Repeat("x", limit-len(`{"text":""}`)) + `"}`)
if len(exact) != limit {
t.Fatalf("test bug: body is %d bytes, want %d", len(exact), limit)
}
post := func(body io.Reader) (int, []byte) {
req, _ := http.NewRequest(http.MethodPost,
r.server.URL+"/api/v1/chats/"+chat.ID+"/messages", body)
req.Header.Set("Content-Type", "application/json")
r.setAuth(req, alice.ID)
resp, err := r.client.Do(req)
if err != nil {
t.Fatalf("send: %v", err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
return resp.StatusCode, data
}
chunked := func(b []byte) io.Reader { return io.MultiReader(bytes.NewReader(b)) }
if status, body := post(bytes.NewReader(exact)); status != http.StatusCreated {
t.Fatalf("body ровно %d байт с Content-Length: expected 201, got %d body=%s", limit, status, body)
}
if status, body := post(chunked(exact)); status != http.StatusCreated {
t.Fatalf("body ровно %d байт без Content-Length: expected 201, got %d body=%s", limit, status, body)
}
stored := r.memory.MessagesTotal()
over := []byte(`{"text":"` + strings.Repeat("x", limit) + `"}`)
status, body := post(chunked(over))
if status != http.StatusRequestEntityTooLarge {
t.Fatalf("body %d байт без Content-Length: expected 413, got %d body=%s", len(over), status, body)
}
if code := extractErrorCode(t, body); code != CodePayloadTooLarge {
t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code)
}
if got := r.memory.MessagesTotal(); got != stored {
t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got)
}
}
type slowSessions struct {
*session.Memory
delay atomic.Int64
}
func (s *slowSessions) Get(ctx context.Context, h []byte) (session.Session, error) {
time.Sleep(time.Duration(s.delay.Load()))
return s.Memory.Get(ctx, h)
}
func TestLimits_RateLimited(t *testing.T) {
sessions := &slowSessions{Memory: session.NewMemory()}
r := newRig(t, config.Limits{
MaxBodyBytes: 1 << 16,
MaxInFlight: 2,
MaxMessagesGlobal: 10000,
MaxHeapBytes: 1 << 40,
}, sessions, time.Hour)
alice := r.createUser("c_"+randomSuffix(), "Алиса")
bob := r.createUser("d_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
sessions.delay.Store(int64(20 * time.Millisecond))
const total = 50
var (
ok atomic.Int32
throttled atomic.Int32
errs atomic.Int32
wg sync.WaitGroup
)
wg.Add(total)
start := make(chan struct{})
for i := 0; i < total; i++ {
i := i
go func() {
defer wg.Done()
<-start
client := &http.Client{Timeout: 10 * time.Second}
body, _ := json.Marshal(dto.CreateMessageRequest{Text: fmt.Sprintf("flood-%d", i)})
req, _ := http.NewRequest(http.MethodPost,
r.server.URL+"/api/v1/chats/"+chat.ID+"/messages",
bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
r.setAuth(req, alice.ID)
resp, err := client.Do(req)
if err != nil {
errs.Add(1)
return
}
switch resp.StatusCode {
case http.StatusCreated:
ok.Add(1)
case http.StatusTooManyRequests:
throttled.Add(1)
default:
errs.Add(1)
}
resp.Body.Close()
}()
}
close(start)
wg.Wait()
sessions.delay.Store(0)
if errs.Load() != 0 {
t.Fatalf("неожиданные ошибки/статусы под нагрузкой: %d", errs.Load())
}
if throttled.Load() == 0 {
t.Fatalf("ожидался хотя бы один 429 при maxInFlight=2 и %d параллельных запросах", total)
}
if ok.Load() == 0 {
t.Fatalf("ни одного 201 — лимит не пропускает валидный трафик")
}
if int(ok.Load()+throttled.Load()) != total {
t.Fatalf("ok=%d throttled=%d не покрывают total=%d", ok.Load(), throttled.Load(), total)
}
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
status, _ := r.send(alice, chat.ID, "после-пика "+randomSuffix())
if status == http.StatusCreated {
break
}
time.Sleep(20 * time.Millisecond)
}
status, _ := r.send(alice, chat.ID, "после-пика-2 "+randomSuffix())
if status != http.StatusCreated {
t.Fatalf("после отступления нагрузки сервис не восстановился: %d", status)
}
collected, _ := r.listMessages(alice, chat.ID, 100)
if int32(len(collected)) < ok.Load() {
t.Fatalf("часть подтверждённых сообщений потеряна: подтверждено %d, в истории %d",
ok.Load(), len(collected))
}
t.Logf("ok=%d throttled=%d errors=%d; history=%d", ok.Load(), throttled.Load(), errs.Load(), len(collected))
}
func TestLimits_MessageQuota(t *testing.T) {
const quota = 10
r := newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: 1 << 16,
MaxInFlight: 16,
MaxMessagesGlobal: quota,
MaxHeapBytes: 1 << 40,
})
alice := r.createUser("e_"+randomSuffix(), "Алиса")
bob := r.createUser("f_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
var saved []string
for i := 0; i < quota; i++ {
status, msg := r.send(alice, chat.ID, fmt.Sprintf("saved-%02d", i))
if status != http.StatusCreated {
t.Fatalf("send %d: expected 201, got %d", i, status)
}
saved = append(saved, msg.ID)
}
status, _, body := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: "overflow"}))
if status != http.StatusServiceUnavailable {
t.Fatalf("expected 503 after quota exhausted, got %d body=%s", status, string(body))
}
if code := extractErrorCode(t, body); code != CodeUnavailable {
t.Fatalf("expected code %q, got %q", CodeUnavailable, code)
}
collected, _ := r.listMessages(alice, chat.ID, 100)
if len(collected) != quota {
t.Fatalf("после 503 история чата %d, ожидалось %d", len(collected), quota)
}
gotIDs := make(map[string]struct{}, len(collected))
for _, m := range collected {
gotIDs[m.ID] = struct{}{}
}
for _, id := range saved {
if _, ok := gotIDs[id]; !ok {
t.Fatalf("подтверждённое сообщение %s исчезло из истории", id)
}
}
for i := 0; i < 5; i++ {
s, _, _ := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: "still-over"}))
if s != http.StatusServiceUnavailable {
t.Fatalf("повторный 503 ожидался, получен %d", s)
}
}
req, _ := http.NewRequest(http.MethodGet, r.server.URL+"/health/live", nil)
resp, err := r.client.Do(req)
if err != nil {
t.Fatalf("health/live: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("health/live под перегрузкой: ожидали 200, получили %d", resp.StatusCode)
}
}
func TestLimits_NoSilentLoss(t *testing.T) {
const quota = 20
r := newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: 1 << 16,
MaxInFlight: 8,
MaxMessagesGlobal: quota,
MaxHeapBytes: 1 << 40,
})
alice := r.createUser("g_"+randomSuffix(), "Алиса")
bob := r.createUser("h_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
const attempts = quota * 3
acked := make([]string, 0, quota)
codes := make(map[int]int)
for i := 0; i < attempts; i++ {
status, msg, _ := r.sendRaw(alice, chat.ID, mustJSON(dto.CreateMessageRequest{Text: fmt.Sprintf("loss-%03d", i)}))
codes[status]++
if status == http.StatusCreated {
acked = append(acked, msg.ID)
}
}
if len(acked) != quota {
t.Fatalf("ожидалось ровно %d подтверждённых записей, получено %d; codes=%v", quota, len(acked), codes)
}
if codes[http.StatusServiceUnavailable] == 0 {
t.Fatalf("ни одного 503 — лимит не сработал")
}
collected, _ := r.listMessages(alice, chat.ID, 100)
gotIDs := make(map[string]struct{}, len(collected))
for _, m := range collected {
gotIDs[m.ID] = struct{}{}
}
for _, id := range acked {
if _, ok := gotIDs[id]; !ok {
t.Fatalf("подтверждённое сообщение %s исчезло из истории — незаметная потеря данных", id)
}
}
if len(collected) != len(acked) {
t.Fatalf("история чата содержит %d сообщений, подтверждено %d — скрытое отличие",
len(collected), len(acked))
}
t.Logf("codes=%v acked=%d history=%d", codes, len(acked), len(collected))
}