forked from mtusi2026/mtusi2026lab3
Добавить две реплики API за HAProxy и проверку отказа одной из них.
Общие сессии и ключ идемпотентности позволяют продолжать чтение и запись, когда одна реплика остановлена.
This commit is contained in:
+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