Исправить замечания ревью кода: убрать повтор в AppendOnce за счёт запаса у чистки ключей, вынести MessagePayload и SameContent, принять X-Request-Id от балансировщика, упростить фоновые задачи сервера, сократить комментарии

This commit is contained in:
2026-11-04 12:19:49 +03:00
parent c9d0f73221
commit 7fbd781ca3
25 changed files with 207 additions and 247 deletions
+1 -4
View File
@@ -6,10 +6,7 @@ import (
"time"
)
// RunKeyCleanup deletes expired Idempotency-Keys every period until ctx is
// cancelled. Every replica runs it: the deletes skip rows another replica or
// a request holds, so concurrent runs share the work instead of waiting, and
// a failed run is simply retried at the next tick.
// RunKeyCleanup purges expired Idempotency-Keys every period until ctx is done.
func RunKeyCleanup(ctx context.Context, log *slog.Logger, svc *Service, every time.Duration) {
ticker := time.NewTicker(every)
defer ticker.Stop()
+2 -5
View File
@@ -144,7 +144,7 @@ func (h *Handler) send(c *gin.Context, actor uuid.UUID) {
httpx.Error(c, err)
return
}
message, err := h.chats.Send(c.Request.Context(), actor, chatID, key, req.Text)
message, err := h.chats.Send(c.Request.Context(), actor, MessagePayload{ChatID: chatID, IdempotencyKey: key, Text: req.Text})
if err != nil {
httpx.Error(c, err)
return
@@ -173,10 +173,7 @@ func (h *Handler) history(c *gin.Context, actor uuid.UUID) {
var keyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
// idempotencyKey reads the Idempotency-Key that names one send attempt. It
// is part of this endpoint's input contract, so it is checked here, with
// the path and the body, and before access: the answer to a malformed key
// is the same for any chat. Two headers are ambiguous and rejected.
// idempotencyKey rejects two values of the header as ambiguous.
func idempotencyKey(c *gin.Context) (string, error) {
values := c.Request.Header.Values("Idempotency-Key")
if len(values) != 1 || !keyPattern.MatchString(values[0]) {
+6
View File
@@ -42,3 +42,9 @@ func NewMessage(id, chatID, senderID uuid.UUID, text string) (Message, error) {
CreatedAt: ident.TimeOf(id),
}, nil
}
// SameContent reports whether two messages say the same thing, whatever their
// ids and times.
func (m Message) SameContent(other Message) bool {
return m.Text == other.Text
}
+13
View File
@@ -45,3 +45,16 @@ func TestNewMessageKeepsSurroundingWhitespace(t *testing.T) {
t.Fatalf("text must be stored verbatim, got %q", m.Text)
}
}
func TestSameContentComparesWhatTheSenderWrote(t *testing.T) {
chatID, alice := ident.New(), ident.New()
first, _ := chat.NewMessage(ident.New(), chatID, alice, "привет")
retry, _ := chat.NewMessage(ident.New(), chatID, alice, "привет")
other, _ := chat.NewMessage(ident.New(), chatID, alice, "привет!")
if !first.SameContent(retry) {
t.Fatal("messages with the same text must have the same content")
}
if first.SameContent(other) {
t.Fatal("messages with different text must differ")
}
}
+4 -6
View File
@@ -24,13 +24,11 @@ type ChatRepository interface {
}
type MessageRepository interface {
// AppendOnce stores message under the sender's key in its chat, unless
// the key was used there within ttl; it returns the message the key is
// bound to: the given one or the earlier one.
// AppendOnce stores message under the sender's key unless the key was
// used in this chat within ttl, and returns the message the key is bound
// to: the given one or the earlier one.
AppendOnce(ctx context.Context, message Message, key string, ttl time.Duration) (Message, error)
// DeleteExpiredKeys removes up to limit keys older than ttl and reports
// how many it removed.
DeleteExpiredKeys(ctx context.Context, ttl time.Duration, limit int) (int64, error)
DeleteExpiredKeys(ctx context.Context, olderThan time.Duration, limit int) (int64, error)
// ListByChat returns up to limit messages ordered by (created_at, id),
// strictly after the message identified by after when set. An unknown
// chat yields an empty history.
+24 -18
View File
@@ -12,6 +12,13 @@ import (
"messenger/internal/platform/pagination"
)
const (
keyPurgeBatch = 1000
// keyPurgeGrace keeps a key past its TTL, so a key that a request has just
// found valid cannot vanish before the request reads its message back.
keyPurgeGrace = time.Minute
)
// UserLookup is what this module needs from the users module: one batched
// existence check. It is declared here, on the consumer side, so this
// package never imports the users package and tests substitute a map.
@@ -26,8 +33,8 @@ type Service struct {
keyTTL time.Duration
}
// NewService builds the chats service; keyTTL is how long a message
// Idempotency-Key stays bound to its message.
// NewService takes keyTTL, how long an 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}
}
@@ -66,38 +73,37 @@ 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
}
// 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 {
// MessagePayload is one send attempt: the message and its Idempotency-Key.
type MessagePayload struct {
ChatID uuid.UUID
IdempotencyKey string
Text string
}
// Send checks access and the text on every attempt, a replay included, as the
// contract requires of a repeat.
func (s *Service) Send(ctx context.Context, actor uuid.UUID, p MessagePayload) (Message, error) {
if err := s.requireMember(ctx, actor, p.ChatID); err != nil {
return Message{}, err
}
message, err := NewMessage(ident.New(), chatID, actor, text)
message, err := NewMessage(ident.New(), p.ChatID, actor, p.Text)
if err != nil {
return Message{}, err
}
stored, err := s.messages.AppendOnce(ctx, message, key, s.keyTTL)
stored, err := s.messages.AppendOnce(ctx, message, p.IdempotencyKey, s.keyTTL)
if err != nil {
return Message{}, err
}
if stored.ID != message.ID && stored.Text != message.Text {
if !stored.SameContent(message) {
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)
n, err := s.messages.DeleteExpiredKeys(ctx, s.keyTTL+keyPurgeGrace, keyPurgeBatch)
total += n
if err != nil {
return total, err
+30 -9
View File
@@ -190,15 +190,15 @@ func TestSendChecksAccessBeforeValidation(t *testing.T) {
if err != nil {
t.Fatal(err)
}
_, err = f.svc.Send(f.ctx, f.eve, c.ID, "k1", " ")
_, err = f.svc.Send(f.ctx, f.eve, chat.MessagePayload{ChatID: c.ID, IdempotencyKey: "k1", Text: " "})
if !errors.Is(err, chat.ErrNotFound) {
t.Fatalf("outsider with blank text: err = %v, want ErrNotFound", err)
}
_, err = f.svc.Send(f.ctx, f.bob, c.ID, "k2", " ")
_, err = f.svc.Send(f.ctx, f.bob, chat.MessagePayload{ChatID: c.ID, IdempotencyKey: "k2", Text: " "})
if apperr.KindOf(err) != apperr.KindInvalid {
t.Fatalf("member with blank text: kind = %v, want KindInvalid", apperr.KindOf(err))
}
msg, err := f.svc.Send(f.ctx, f.bob, c.ID, "k3", "Привет 👋")
msg, err := f.svc.Send(f.ctx, f.bob, chat.MessagePayload{ChatID: c.ID, IdempotencyKey: "k3", Text: "Привет 👋"})
if err != nil || msg.SenderID != f.bob || msg.ChatID != c.ID || msg.Text != "Привет 👋" {
t.Fatalf("Send = %+v, %v", msg, err)
}
@@ -210,8 +210,8 @@ func TestHistoryPagesAndHidesForeignChat(t *testing.T) {
if err != nil {
t.Fatal(err)
}
first, _ := f.svc.Send(f.ctx, f.alice, c.ID, "k1", "1")
second, _ := f.svc.Send(f.ctx, f.bob, c.ID, "k2", "2")
first, _ := f.svc.Send(f.ctx, f.alice, chat.MessagePayload{ChatID: c.ID, IdempotencyKey: "k1", Text: "1"})
second, _ := f.svc.Send(f.ctx, f.bob, chat.MessagePayload{ChatID: c.ID, IdempotencyKey: "k2", Text: "2"})
page, err := f.svc.History(f.ctx, f.bob, c.ID, nil, 1)
if err != nil {
@@ -247,7 +247,7 @@ func (f fixture) newChat(t *testing.T, members ...uuid.UUID) uuid.UUID {
func (f fixture) send(t *testing.T, actor, c uuid.UUID, key, text string) chat.Message {
t.Helper()
m, err := f.svc.Send(f.ctx, actor, c, key, text)
m, err := f.svc.Send(f.ctx, actor, chat.MessagePayload{ChatID: c, IdempotencyKey: key, Text: text})
if err != nil {
t.Fatal(err)
}
@@ -268,7 +268,7 @@ func TestSendConflictsOnDifferentBody(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice, f.bob)
f.send(t, f.alice, c, "k", "первое")
_, err := f.svc.Send(f.ctx, f.alice, c, "k", "другое")
_, err := f.svc.Send(f.ctx, f.alice, chat.MessagePayload{ChatID: c, IdempotencyKey: "k", Text: "другое"})
if !errors.Is(err, chat.ErrKeyReused) || apperr.KindOf(err) != apperr.KindConflict {
t.Fatalf("different body under a used key: err = %v, want ErrKeyReused (conflict)", err)
}
@@ -292,7 +292,7 @@ func TestSendChecksAccessBeforeKey(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice, f.bob)
first := f.send(t, f.alice, c, "k", "секрет")
if _, err := f.svc.Send(f.ctx, f.eve, c, "k", "секрет"); !errors.Is(err, chat.ErrNotFound) {
if _, err := f.svc.Send(f.ctx, f.eve, chat.MessagePayload{ChatID: c, IdempotencyKey: "k", Text: "секрет"}); !errors.Is(err, chat.ErrNotFound) {
t.Fatalf("outsider with a used key: err = %v, want ErrNotFound", err)
}
if again := f.send(t, f.alice, c, "k", "секрет"); again.ID != first.ID {
@@ -304,7 +304,7 @@ func TestInvalidTextWithUsedKeyIsInvalid(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice, f.bob)
f.send(t, f.alice, c, "k", "текст")
if _, err := f.svc.Send(f.ctx, f.alice, c, "k", " "); apperr.KindOf(err) != apperr.KindInvalid {
if _, err := f.svc.Send(f.ctx, f.alice, chat.MessagePayload{ChatID: c, IdempotencyKey: "k", Text: " "}); apperr.KindOf(err) != apperr.KindInvalid {
t.Fatalf("blank text under a used key: kind = %v, want KindInvalid", apperr.KindOf(err))
}
}
@@ -334,6 +334,27 @@ func TestPurgeExpiredKeysDeletesInBatches(t *testing.T) {
}
}
// A key the claim has just seen valid must survive until the replay lookup,
// so the cleanup leaves keys alone for a while after they expire.
func TestPurgeExpiredKeysWaitsAGraceAfterTTL(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice)
f.send(t, f.alice, c, "just-expired", "1")
f.send(t, f.alice, c, "long-expired", "2")
if _, err := db.Pool.Exec(f.ctx, `
UPDATE message_idempotency_keys
SET created_at = now() - interval '1 hour' - CASE key WHEN 'just-expired' THEN interval '10 seconds' ELSE interval '10 minutes' END`); err != nil {
t.Fatal(err)
}
if deleted, err := f.svc.PurgeExpiredKeys(f.ctx); err != nil || deleted != 1 {
t.Fatalf("PurgeExpiredKeys = %d, %v; want only the long expired key", deleted, err)
}
var left string
if err := db.Pool.QueryRow(f.ctx, `SELECT key FROM message_idempotency_keys`).Scan(&left); err != nil || left != "just-expired" {
t.Fatalf("left %q, %v; want just-expired", left, err)
}
}
func TestRunKeyCleanupPurgesAndStops(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice)
-9
View File
@@ -1,9 +0,0 @@
package store
// SetAfterClaim installs a hook that runs between the claiming statement and
// the replay lookup of AppendOnce; it returns a function restoring the old one.
func SetAfterClaim(hook func()) (restore func()) {
old := afterClaim
afterClaim = hook
return func() { afterClaim = old }
}
-24
View File
@@ -9,7 +9,6 @@ import (
"github.com/google/uuid"
"messenger/internal/chat"
"messenger/internal/chat/store"
)
const keyTTL = time.Hour
@@ -168,29 +167,6 @@ func TestCleanerSkipsRowLockedByRequest(t *testing.T) {
}
}
// The key is alive when the claim runs but deleted before the replay lookup,
// as by a cleaner whose clock is a moment later at the TTL boundary. The
// operation starts over and stores the new message.
func TestAppendOnceRetriesWhenKeyVanishes(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
f.appendOnce(t, f.newMessage(t, c.ID, alice), "k1")
var once sync.Once
restore := store.SetAfterClaim(func() {
once.Do(func() {
if _, err := db.Pool.Exec(context.Background(), `DELETE FROM message_idempotency_keys WHERE key = 'k1'`); err != nil {
t.Error(err)
}
})
})
defer restore()
next := f.newMessage(t, c.ID, alice)
if got := f.appendOnce(t, next, "k1"); got.ID != next.ID {
t.Fatalf("got %v, want the new message %v", got.ID, next.ID)
}
}
func TestDeleteExpiredKeysOnlyExpiredAndUpToLimit(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
+27 -52
View File
@@ -118,16 +118,9 @@ func NewMessages(pool *pgxpool.Pool) *Messages {
return &Messages{pool: pool}
}
// afterClaim runs between the claiming statement and the replay lookup of
// AppendOnce; tests use it to delete the key in that window.
var afterClaim func()
// claimSQL stores the key and the message in one statement. A key older than
// the retention period is taken over for the new message. The key row is
// inserted first: when it already exists and is still valid, claimed is
// empty and so is the message insert. One statement holds the key's lock
// only while the server executes it, never across a round trip to a replica
// that might die in between.
// claimSQL binds the key and inserts the message in one statement, so the
// key's lock never spans a round trip. An expired key is taken over; a valid
// one leaves claimed, and so the message insert, empty.
const claimSQL = `
WITH claimed AS (
INSERT INTO message_idempotency_keys AS k (user_id, chat_id, key, message_id)
@@ -139,51 +132,33 @@ const claimSQL = `
INSERT INTO messages (chat_id, id, sender_id, text, created_at)
SELECT $2, message_id, $1, $6, $7 FROM claimed`
// AppendOnce stores m under key unless the sender already used the key in
// this chat within ttl; it returns the message the key is bound to, m itself
// or the earlier one. Deciding whether the earlier message answers the same
// request is the caller's job.
//
// The lookup of an existing key is a second statement: within the claiming
// one, a plain SELECT would see the snapshot taken before a concurrent
// request committed the key. Between the two statements the cleaner may
// delete a key at the ttl boundary; the operation then starts over once,
// which stores m under the now free key.
// The bound message is read by a second statement: the claim's snapshot
// cannot see a key that a concurrent request has just committed.
func (r *Messages) AppendOnce(ctx context.Context, m chat.Message, key string, ttl time.Duration) (chat.Message, error) {
for range 2 {
tag, err := r.pool.Exec(ctx, claimSQL,
m.SenderID, m.ChatID, key, m.ID, interval(ttl), m.Text, m.CreatedAt)
if err != nil {
return chat.Message{}, fmt.Errorf("insert message: %w", postgres.Classify(err))
}
if tag.RowsAffected() == 1 {
return m, nil
}
if afterClaim != nil {
afterClaim()
}
var stored chat.Message
err = r.pool.QueryRow(ctx, `
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM message_idempotency_keys k
JOIN messages m ON m.chat_id = k.chat_id AND m.id = k.message_id
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`,
m.SenderID, m.ChatID, key).Scan(&stored.ID, &stored.ChatID, &stored.SenderID, &stored.Text, &stored.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
continue
}
if err != nil {
return chat.Message{}, fmt.Errorf("select message by key: %w", postgres.Classify(err))
}
return stored, nil
tag, err := r.pool.Exec(ctx, claimSQL,
m.SenderID, m.ChatID, key, m.ID, interval(ttl), m.Text, m.CreatedAt)
if err != nil {
return chat.Message{}, fmt.Errorf("insert message: %w", postgres.Classify(err))
}
return chat.Message{}, errors.New("idempotency key vanished twice between claim and lookup")
if tag.RowsAffected() == 1 {
return m, nil
}
var stored chat.Message
err = r.pool.QueryRow(ctx, `
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM message_idempotency_keys k
JOIN messages m ON m.chat_id = k.chat_id AND m.id = k.message_id
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`,
m.SenderID, m.ChatID, key).Scan(&stored.ID, &stored.ChatID, &stored.SenderID, &stored.Text, &stored.CreatedAt)
if err != nil {
return chat.Message{}, fmt.Errorf("select message by key: %w", postgres.Classify(err))
}
return stored, nil
}
// DeleteExpiredKeys removes up to limit keys older than ttl. SKIP LOCKED lets
// replicas cleaning at the same time, and requests holding a key, pass each
// other instead of waiting.
func (r *Messages) DeleteExpiredKeys(ctx context.Context, ttl time.Duration, limit int) (int64, error) {
// DeleteExpiredKeys skips rows locked by another cleaner or a request rather
// than waiting for them.
func (r *Messages) DeleteExpiredKeys(ctx context.Context, olderThan time.Duration, limit int) (int64, error) {
tag, err := r.pool.Exec(ctx, `
DELETE FROM message_idempotency_keys
WHERE (user_id, chat_id, key) IN (
@@ -192,7 +167,7 @@ func (r *Messages) DeleteExpiredKeys(ctx context.Context, ttl time.Duration, lim
ORDER BY created_at
LIMIT $2
FOR UPDATE SKIP LOCKED)`,
interval(ttl), limit)
interval(olderThan), limit)
if err != nil {
return 0, fmt.Errorf("delete expired keys: %w", postgres.Classify(err))
}