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)
|
||||
|
||||
Reference in New Issue
Block a user