forked from mtusi2026/mtusi2026lab3
Добавить две реплики API за HAProxy и проверку отказа одной из них.
Общие сессии и ключ идемпотентности позволяют продолжать чтение и запись, когда одна реплика остановлена.
This commit is contained in:
+98
-28
@@ -14,7 +14,8 @@ import (
|
||||
// PG — источник истины для пользователей, чатов и сообщений.
|
||||
// Запросы только с параметрами. Пул ограничен, у сессии соединения есть statement_timeout.
|
||||
type PG struct {
|
||||
pool *pgxpool.Pool
|
||||
pool *pgxpool.Pool
|
||||
idemTTL time.Duration
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, databaseURL string, maxConns int32) (*PG, error) {
|
||||
@@ -45,7 +46,14 @@ func Open(ctx context.Context, databaseURL string, maxConns int32) (*PG, error)
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &PG{pool: pool}, nil
|
||||
return &PG{pool: pool, idemTTL: 24 * time.Hour}, nil
|
||||
}
|
||||
|
||||
// SetIdempotencyTTL задаёт, сколько хранить результат POST сообщения.
|
||||
func (p *PG) SetIdempotencyTTL(ttl time.Duration) {
|
||||
if ttl > 0 {
|
||||
p.idemTTL = ttl
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PG) Close() { p.pool.Close() }
|
||||
@@ -214,37 +222,72 @@ func (p *PG) ListChats(ctx context.Context, userID string, cur *Cursor, limit in
|
||||
return items, hasMore, nil
|
||||
}
|
||||
|
||||
func (p *PG) AddMessage(ctx context.Context, chatID, senderID, text string) (Message, error) {
|
||||
func (p *PG) AddMessage(ctx context.Context, chatID, senderID, text, idemKey, fingerprint string) (Message, error) {
|
||||
if idemKey == "" || fingerprint == "" {
|
||||
return Message{}, ErrInvalid
|
||||
}
|
||||
var last error
|
||||
for attempt := 0; attempt < 5; attempt++ {
|
||||
msg, retry, err := p.addMessageOnce(ctx, chatID, senderID, text, idemKey, fingerprint)
|
||||
if !retry {
|
||||
return msg, err
|
||||
}
|
||||
last = err
|
||||
}
|
||||
if last == nil {
|
||||
last = ErrUnavailable
|
||||
}
|
||||
return Message{}, ErrUnavailable
|
||||
}
|
||||
|
||||
// addMessageOnce пишет сообщение и ключ одной транзакцией.
|
||||
// retry=true значит, что параллельная реплика заняла тот же ключ раньше: свою вставку откатываем и читаем её результат.
|
||||
func (p *PG) addMessageOnce(ctx context.Context, chatID, senderID, text, idemKey, fingerprint string) (Message, bool, error) {
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
// Блокировка строки чата сериализует writers одного чата.
|
||||
var exists string
|
||||
err = tx.QueryRow(ctx, `SELECT id::text FROM chats WHERE id = $1 FOR UPDATE`, chatID).Scan(&exists)
|
||||
if err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
var member int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
var last time.Time
|
||||
|
||||
var storedFP, messageID string
|
||||
var expires time.Time
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT created_at FROM messages WHERE chat_id = $1
|
||||
ORDER BY created_at DESC LIMIT 1`, chatID).Scan(&last)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
last = time.Time{}
|
||||
} else if err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
SELECT fingerprint, message_id::text, expires_at
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND idem_key = $3
|
||||
FOR UPDATE`, senderID, chatID, idemKey).Scan(&storedFP, &messageID, &expires)
|
||||
if err == nil {
|
||||
if expires.After(time.Now()) {
|
||||
if storedFP != fingerprint {
|
||||
return Message{}, false, ErrIdempotencyMismatch
|
||||
}
|
||||
msg, err := scanMessage(tx.QueryRow(ctx, `
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages WHERE id = $1`, messageID))
|
||||
if err != nil {
|
||||
return Message{}, false, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
return msg, false, nil
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND idem_key = $3`, senderID, chatID, idemKey); err != nil {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
if !last.IsZero() && !now.After(last.UTC()) {
|
||||
now = last.UTC().Add(time.Microsecond)
|
||||
}
|
||||
m := Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
@@ -255,12 +298,31 @@ func (p *PG) AddMessage(ctx context.Context, chatID, senderID, text string) (Mes
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
recorded := time.Now().UTC().Truncate(time.Microsecond)
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_idempotency
|
||||
(user_id, chat_id, idem_key, fingerprint, message_id, created_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
senderID, chatID, idemKey, fingerprint, m.ID, recorded, recorded.Add(p.idemTTL)); err != nil {
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
return m, nil
|
||||
return m, false, nil
|
||||
}
|
||||
|
||||
func retryable(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "23505", "40001", "40P01":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *PG) ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error) {
|
||||
@@ -302,11 +364,10 @@ func (p *PG) ListMessages(ctx context.Context, chatID, userID string, cur *Curso
|
||||
defer rows.Close()
|
||||
items := make([]Message, 0)
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
m, err := scanMessage(rows)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
@@ -350,6 +411,15 @@ func (p *PG) memberIDs(ctx context.Context, q queryer, chatIDs []string) (map[st
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func scanMessage(row pgx.Row) (Message, error) {
|
||||
var m Message
|
||||
if err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func scanUser(row pgx.Row) (User, error) {
|
||||
var u User
|
||||
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
|
||||
@@ -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()
|
||||
|
||||
+46
-7
@@ -10,11 +10,12 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalid = errors.New("invalid")
|
||||
ErrBadCursor = errors.New("bad cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrIdempotencyMismatch = errors.New("idempotency mismatch")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalid = errors.New("invalid")
|
||||
ErrBadCursor = errors.New("bad cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
)
|
||||
|
||||
// User — публичная карточка. Хеш пароля в неё не входит.
|
||||
@@ -57,7 +58,10 @@ type Repository interface {
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string, caller string) (Chat, error)
|
||||
ChatFor(ctx context.Context, chatID, userID string) (Chat, error)
|
||||
ListChats(ctx context.Context, userID string, cur *Cursor, limit int) ([]Chat, bool, error)
|
||||
AddMessage(ctx context.Context, chatID, senderID, text string) (Message, error)
|
||||
// AddMessage создаёт сообщение или возвращает уже записанное для того же ключа.
|
||||
// fingerprint — каноническое тело (текст). Другой fingerprint при живом ключе даёт ErrIdempotencyMismatch.
|
||||
// Ключ живёт idempotencyTTL. Область: отправитель + чат + ключ (метод POST и путь чата).
|
||||
AddMessage(ctx context.Context, chatID, senderID, text, idemKey, fingerprint string) (Message, error)
|
||||
ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error)
|
||||
}
|
||||
|
||||
@@ -66,6 +70,12 @@ type chatRec struct {
|
||||
members map[string]struct{}
|
||||
}
|
||||
|
||||
type idemRec struct {
|
||||
fingerprint string
|
||||
messageID string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// Memory сериализует записи мьютексом. Это двойник контракта для тестов без PostgreSQL.
|
||||
type Memory struct {
|
||||
mu sync.RWMutex
|
||||
@@ -76,6 +86,8 @@ type Memory struct {
|
||||
chatOrder []string
|
||||
messages map[string][]Message
|
||||
msgIndex map[string]map[string]int
|
||||
idem map[string]idemRec
|
||||
idemTTL time.Duration
|
||||
last time.Time
|
||||
}
|
||||
|
||||
@@ -87,9 +99,21 @@ func New() *Memory {
|
||||
chats: make(map[string]*chatRec),
|
||||
messages: make(map[string][]Message),
|
||||
msgIndex: make(map[string]map[string]int),
|
||||
idem: make(map[string]idemRec),
|
||||
idemTTL: 24 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// SetIdempotencyTTL меняет срок ключа. Нужен тестам; в PostgreSQL тот же смысл у IDEMPOTENCY_TTL_SECONDS.
|
||||
func (s *Memory) SetIdempotencyTTL(d time.Duration) {
|
||||
if d <= 0 {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.idemTTL = d
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Memory) Ping(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
@@ -218,10 +242,13 @@ func (s *Memory) ListChats(ctx context.Context, userID string, cur *Cursor, limi
|
||||
return append([]Chat(nil), filtered[start:end]...), end < len(filtered), nil
|
||||
}
|
||||
|
||||
func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text string) (Message, error) {
|
||||
func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text, idemKey, fingerprint string) (Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Message{}, ErrUnavailable
|
||||
}
|
||||
if idemKey == "" || fingerprint == "" {
|
||||
return Message{}, ErrInvalid
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
rec, ok := s.chats[chatID]
|
||||
@@ -231,6 +258,17 @@ func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text string)
|
||||
if _, member := rec.members[senderID]; !member {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
slot := senderID + "\x00" + chatID + "\x00" + idemKey
|
||||
if prev, ok := s.idem[slot]; ok && prev.expires.After(time.Now()) {
|
||||
if prev.fingerprint != fingerprint {
|
||||
return Message{}, ErrIdempotencyMismatch
|
||||
}
|
||||
idx, ok := s.msgIndex[chatID][prev.messageID]
|
||||
if !ok {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
return s.messages[chatID][idx], nil
|
||||
}
|
||||
m := Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
@@ -241,6 +279,7 @@ func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text string)
|
||||
idx := len(s.messages[chatID])
|
||||
s.messages[chatID] = append(s.messages[chatID], m)
|
||||
s.msgIndex[chatID][m.ID] = idx
|
||||
s.idem[slot] = idemRec{fingerprint: fingerprint, messageID: m.ID, expires: time.Now().Add(s.idemTTL)}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user