forked from mtusi2026/mtusi2026lab3
Добавить две реплики API за HAProxy и проверку отказа одной из них.
Общие сессии и ключ идемпотентности позволяют продолжать чтение и запись, когда одна реплика остановлена.
This commit is contained in:
@@ -121,6 +121,58 @@ func TestIntegrationChatRollback(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationIdempotencyRace(t *testing.T) {
|
||||
pg := openIntegration(t)
|
||||
ctx := context.Background()
|
||||
u, err := pg.CreateUser(ctx, "idm_"+newID()[:8], "Ключ", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat, err := pg.CreateChat(ctx, "идемпотентность", []string{u.ID}, u.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const n = 16
|
||||
var wg sync.WaitGroup
|
||||
ids := make(chan string, n)
|
||||
errs := make(chan error, n)
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
msg, err := pg.AddMessage(ctx, chat.ID, u.ID, "одно", "key-1", "одно")
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
ids <- msg.ID
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(ids)
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
for id := range ids {
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if len(seen) != 1 {
|
||||
t.Fatalf("concurrent key created %d messages", len(seen))
|
||||
}
|
||||
if _, err := pg.AddMessage(ctx, chat.ID, u.ID, "другое", "key-1", "другое"); !errors.Is(err, ErrIdempotencyMismatch) {
|
||||
t.Fatalf("mismatch: %v", err)
|
||||
}
|
||||
var count int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM messages WHERE chat_id = $1`, chat.ID).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("messages = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresUnreachable(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
Reference in New Issue
Block a user