lab3
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type IdempotencySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestIdempotencySuite(t *testing.T) {
|
||||
suite.Run(t, new(IdempotencySuite))
|
||||
}
|
||||
|
||||
func messageDraft(chat domain.Chat, sender domain.User, key, text string) domain.MessageDraft {
|
||||
return domain.MessageDraft{
|
||||
ChatID: chat.ID,
|
||||
SenderID: sender.ID,
|
||||
Text: text,
|
||||
Idempotency: domain.MessageIdempotency{
|
||||
Key: key,
|
||||
RequestHash: sha256.Sum256([]byte(text)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) history(chat domain.Chat, actor domain.User) []domain.Message {
|
||||
s.T().Helper()
|
||||
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, actor.ID, nil, 100)
|
||||
s.Require().NoError(err)
|
||||
|
||||
return page.Items
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestReplayReturnsStoredMessage() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
draft := messageDraft(chat, alice, "key-1", "привет")
|
||||
|
||||
created, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
|
||||
replayed, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal(created, replayed, "повтор с тем же ключом и payload возвращает исходное сообщение")
|
||||
s.Len(s.history(chat, bob), 1, "повтор не создаёт дубль")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestSameKeyWithAnotherPayloadConflicts() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
created, err := s.store.Messages().Create(s.T().Context(), messageDraft(chat, alice, "key-1", "привет"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = s.store.Messages().Create(s.T().Context(), messageDraft(chat, alice, "key-1", "другое"))
|
||||
s.Require().ErrorIs(err, domain.ErrIdempotency)
|
||||
|
||||
history := s.history(chat, bob)
|
||||
s.Require().Len(history, 1, "конфликт не создаёт сообщение")
|
||||
s.Equal(created.ID, history[0].ID, "исходное сообщение не изменено")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestConcurrentReplaysCreateOneMessage() {
|
||||
const callers = 8
|
||||
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
draft := messageDraft(chat, alice, "key-concurrent", "конкурентный повтор")
|
||||
|
||||
ctx := s.T().Context()
|
||||
results := make([]domain.Message, callers)
|
||||
errs := make([]error, callers)
|
||||
|
||||
start := make(chan struct{})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := range callers {
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
<-start
|
||||
|
||||
results[i], errs[i] = s.store.Messages().Create(ctx, draft)
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
for i := range callers {
|
||||
s.Require().NoError(errs[i], "caller %d", i)
|
||||
s.Equal(results[0].ID, results[i].ID, "все одновременные повторы получают одно сообщение")
|
||||
}
|
||||
|
||||
s.Len(s.history(chat, bob), 1, "конкурентный повтор создаёт ровно одно сообщение")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestKeyIsScopedToActorAndChat() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
carol := s.createUser("carol")
|
||||
|
||||
first := s.createChat(alice, bob)
|
||||
second := s.createChat(alice, carol)
|
||||
|
||||
mine, err := s.store.Messages().Create(s.T().Context(), messageDraft(first, alice, "shared-key", "от Алисы"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
byBob, err := s.store.Messages().Create(s.T().Context(), messageDraft(first, bob, "shared-key", "от Боба"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.NotEqual(mine.ID, byBob.ID, "одинаковый ключ разных пользователей независим")
|
||||
|
||||
another, err := s.store.Messages().Create(s.T().Context(), messageDraft(second, alice, "shared-key", "в другом чате"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.NotEqual(mine.ID, another.ID, "одинаковый ключ в другом чате независим")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestExpiredKeyIsReplaced() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
draft := messageDraft(chat, alice, "key-expiring", "первое")
|
||||
|
||||
// Отрицательный TTL: записи идемпотентности истекают сразу.
|
||||
expiring := openStoreWithTTL(s.T(), s.db, -time.Second, nil)
|
||||
s.T().Cleanup(expiring.Close)
|
||||
|
||||
created, err := expiring.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
|
||||
replaced, err := expiring.Messages().Create(s.T().Context(), messageDraft(chat, alice, "key-expiring", "второе"))
|
||||
s.Require().NoError(err, "истёкший ключ можно использовать с другим payload")
|
||||
s.NotEqual(created.ID, replaced.ID)
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestClaimForMissingChatIsNotFound() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
// Чат не существует: claim ключа ссылается на chats(id), поэтому наружу
|
||||
// должен уйти 404, а не 500 из-за нарушения внешнего ключа.
|
||||
_, err := s.store.Messages().Create(
|
||||
s.T().Context(),
|
||||
messageDraft(domain.Chat{ID: uuid.New()}, alice, "key-1", "привет"),
|
||||
)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestFailedAttemptLeavesNoClaim() {
|
||||
alice := s.createUser("alice")
|
||||
outsider := s.createUser("outsider")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
_, err := s.store.Messages().Create(s.T().Context(), messageDraft(chat, outsider, "key-1", "привет"))
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
|
||||
var claims int
|
||||
|
||||
s.Require().NoError(
|
||||
s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM message_idempotency").Scan(&claims),
|
||||
)
|
||||
s.Zero(claims, "отклонённая попытка не оставляет claim: транзакция откатывается целиком")
|
||||
}
|
||||
Reference in New Issue
Block a user