Сделать отправку сообщения идемпотентной по Idempotency-Key с общей таблицей ключей и их чисткой

This commit is contained in:
2026-11-02 17:11:04 +03:00
parent 7fa8881eb3
commit 951fd0d517
19 changed files with 856 additions and 40 deletions
+37 -5
View File
@@ -3,6 +3,7 @@ package chat
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
@@ -22,10 +23,13 @@ type Service struct {
chats ChatRepository
messages MessageRepository
users UserLookup
keyTTL time.Duration
}
func NewService(chats ChatRepository, messages MessageRepository, users UserLookup) *Service {
return &Service{chats: chats, messages: messages, users: users}
// NewService builds the chats service; keyTTL is how long a message
// Idempotency-Key stays bound to its message.
func NewService(chats ChatRepository, messages MessageRepository, users UserLookup, keyTTL time.Duration) *Service {
return &Service{chats: chats, messages: messages, users: users, keyTTL: keyTTL}
}
func (s *Service) Create(ctx context.Context, creator uuid.UUID, title string, memberIDs []uuid.UUID) (ChatWithMembers, error) {
@@ -62,7 +66,11 @@ func (s *Service) List(ctx context.Context, actor uuid.UUID, after *uuid.UUID, l
return pagination.Cut(items, limit, func(c ChatWithMembers) uuid.UUID { return c.ID }), nil
}
func (s *Service) Send(ctx context.Context, actor, chatID uuid.UUID, text string) (Message, error) {
// Send stores a message under the sender's Idempotency-Key. Access and the
// text are checked first, on every attempt: a retry is a new request that
// must still be authorised and valid. A key already bound to a message with
// the same text returns that message; with a different text it is a conflict.
func (s *Service) Send(ctx context.Context, actor, chatID uuid.UUID, key, text string) (Message, error) {
if err := s.requireMember(ctx, actor, chatID); err != nil {
return Message{}, err
}
@@ -70,10 +78,34 @@ func (s *Service) Send(ctx context.Context, actor, chatID uuid.UUID, text string
if err != nil {
return Message{}, err
}
if err := s.messages.Append(ctx, message); err != nil {
stored, err := s.messages.AppendOnce(ctx, message, key, s.keyTTL)
if err != nil {
return Message{}, err
}
return message, nil
if stored.ID != message.ID && stored.Text != message.Text {
return Message{}, ErrKeyReused
}
return stored, nil
}
// keyPurgeBatch bounds one delete statement, so the cleanup never holds many
// row locks or runs long.
const keyPurgeBatch = 1000
// PurgeExpiredKeys deletes every key older than the retention period, batch
// by batch, and reports how many it deleted.
func (s *Service) PurgeExpiredKeys(ctx context.Context) (int64, error) {
var total int64
for {
n, err := s.messages.DeleteExpiredKeys(ctx, s.keyTTL, keyPurgeBatch)
total += n
if err != nil {
return total, err
}
if n < keyPurgeBatch {
return total, nil
}
}
}
func (s *Service) History(ctx context.Context, actor, chatID uuid.UUID, after *uuid.UUID, limit int) (pagination.Page[Message], error) {