Добавьте S3-вложения с дедупликацией и безопасной сверкой хранилищ

This commit is contained in:
2026-11-16 12:36:59 +03:00
parent b323f2dab9
commit d761861def
54 changed files with 5061 additions and 102 deletions
+72
View File
@@ -0,0 +1,72 @@
package chat_test
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/chat"
"messenger/internal/platform/httpx"
)
func messageRouter(f fixture, actor uuid.UUID) *gin.Engine {
r := gin.New()
r.Use(func(c *gin.Context) { httpx.SetUserID(c, actor) })
chat.NewHandler(f.svc).Register(r)
return r
}
func sendJSON(r http.Handler, chatID uuid.UUID, key, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/chats/"+chatID.String()+"/messages", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec
}
func TestMessageAttachmentJSONEmptyArrayAndOmitted(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice)
r := messageRouter(f, f.alice)
for i, body := range []string{`{"text":"hello","attachment_ids":[]}`, `{"text":"hello"}`} {
rec := sendJSON(r, c, fmt.Sprint(i), body)
if rec.Code != http.StatusCreated {
t.Fatalf("send %s: %d %s", body, rec.Code, rec.Body)
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(rec.Body.Bytes(), &fields); err != nil {
t.Fatal(err)
}
if string(fields["attachment_ids"]) != "[]" {
t.Fatalf("attachment_ids = %s, want []", fields["attachment_ids"])
}
}
}
func TestMessageAttachmentJSONRejectsInvalidArrays(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice)
r := messageRouter(f, f.alice)
id := uuid.NewString()
for _, raw := range []string{
"null", `"not an array"`, "{}", "1", "[null]", "[1]", `["bad"]`,
`["00000000-0000-0000-0000-000000000000"]`,
fmt.Sprintf("[%q]", strings.ReplaceAll(id, "-", "")),
fmt.Sprintf("[%q,%q]", id, strings.ToUpper(id)),
"[" + strings.TrimSuffix(strings.Repeat(fmt.Sprintf("%q,", id), 11), ",") + "]",
} {
t.Run(raw, func(t *testing.T) {
rec := sendJSON(r, c, "invalid", `{"text":"hello","attachment_ids":`+raw+"}")
if rec.Code != http.StatusBadRequest {
t.Fatalf("send: %d %s", rec.Code, rec.Body)
}
})
}
}
+125
View File
@@ -0,0 +1,125 @@
package chat_test
import (
"crypto/sha256"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/google/uuid"
"messenger/internal/chat"
"messenger/internal/platform/ident"
"messenger/internal/platform/pagination"
)
func (f fixture) attachment(t *testing.T, chatID, owner uuid.UUID, status string) uuid.UUID {
t.Helper()
id := ident.New()
hash := sha256.Sum256([]byte(id.String()))
_, err := db.Pool.Exec(f.ctx, `
WITH file AS (
INSERT INTO files (hash, size_bytes, mime_type, status, created_at)
VALUES ($1, 7, 'image/png', $2, now()) RETURNING hash)
INSERT INTO attachments (id, chat_id, owner_id, filename, file_hash, created_at)
SELECT $3, $4, $5, 'image.png', hash, now() FROM file`, hash[:], status, id, chatID, owner)
if err != nil {
t.Fatal(err)
}
return id
}
func TestAttachmentHTTPRoundTripReplayAndOrderedConflict(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice, f.bob)
a, b := f.attachment(t, c, f.bob, "ready"), f.attachment(t, c, f.alice, "ready")
r := messageRouter(f, f.alice)
body := fmt.Sprintf(`{"text":"","attachment_ids":[%q,%q]}`, b, a)
first := sendJSON(r, c, "attachments", body)
if first.Code != http.StatusCreated {
t.Fatalf("attachment-only send: %d %s", first.Code, first.Body)
}
var message chat.MessageResponse
if err := json.Unmarshal(first.Body.Bytes(), &message); err != nil {
t.Fatal(err)
}
if message.Text != "" || !reflect.DeepEqual(message.AttachmentIDs, []string{b.String(), a.String()}) {
t.Fatalf("message = %+v", message)
}
if again := sendJSON(r, c, "attachments", body); again.Code != http.StatusCreated || again.Body.String() != first.Body.String() {
t.Fatalf("replay: %d %s, want %s", again.Code, again.Body, first.Body)
}
for _, changed := range []string{
fmt.Sprintf(`{"text":"","attachment_ids":[%q,%q]}`, a, b),
fmt.Sprintf(`{"text":"","attachment_ids":[%q]}`, b),
fmt.Sprintf(`{"text":"different","attachment_ids":[%q,%q]}`, b, a),
} {
if rec := sendJSON(r, c, "attachments", changed); rec.Code != http.StatusConflict {
t.Fatalf("changed payload: %d %s", rec.Code, rec.Body)
}
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/chats/"+c.String()+"/messages", nil))
var page pagination.PageResponse[chat.MessageResponse]
if rec.Code != http.StatusOK {
t.Fatalf("history: %d %s", rec.Code, rec.Body)
}
if err := json.Unmarshal(rec.Body.Bytes(), &page); err != nil {
t.Fatal(err)
}
if len(page.Items) != 1 || !reflect.DeepEqual(page.Items[0], message) {
t.Fatalf("history = %+v, want %+v", page, message)
}
without := sendJSON(r, c, "empty", `{"text":"text-only"}`)
empty := sendJSON(r, c, "empty", `{"attachment_ids":[],"text":"text-only"}`)
if without.Code != http.StatusCreated || empty.Code != http.StatusCreated || without.Body.String() != empty.Body.String() {
t.Fatalf("omitted vs empty replay: %d %s; %d %s", without.Code, without.Body, empty.Code, empty.Body)
}
}
func TestAttachmentHTTPStatusAndChatAccess(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice, f.bob)
other := f.newChat(t, f.alice)
ready := f.attachment(t, c, f.bob, "ready")
foreign := f.attachment(t, other, f.alice, "ready")
failed := f.attachment(t, c, f.alice, "failed")
pending := f.attachment(t, c, f.alice, "pending")
for _, tc := range []struct {
name string
actor, attachment uuid.UUID
want int
}{
{"unknown", f.alice, ident.New(), http.StatusNotFound},
{"foreign", f.alice, foreign, http.StatusNotFound},
{"failed", f.alice, failed, http.StatusConflict},
{"pending", f.alice, pending, http.StatusConflict},
{"outsider", f.eve, ready, http.StatusNotFound},
{"other-owner", f.alice, ready, http.StatusCreated},
} {
t.Run(tc.name, func(t *testing.T) {
body := fmt.Sprintf(`{"text":"","attachment_ids":[%q]}`, tc.attachment)
rec := sendJSON(messageRouter(f, tc.actor), c, "same", body)
if rec.Code != tc.want {
t.Fatalf("send: %d %s, want %d", rec.Code, rec.Body, tc.want)
}
})
}
}
func TestMessageJSONRequiresTextString(t *testing.T) {
f := newFixture(t)
c := f.newChat(t, f.alice)
r := messageRouter(f, f.alice)
for _, body := range []string{"null", `{}`, `{"text":null}`, `{"text":1}`, `{"text":[]}`, `{"text":"","attachment_ids":[]}`} {
if rec := sendJSON(r, c, "text", body); rec.Code != http.StatusBadRequest {
t.Fatalf("send %s: %d %s", body, rec.Code, rec.Body)
}
}
if rec := sendJSON(r, c, "text", `{"text":"valid"}`); rec.Code != http.StatusCreated {
t.Fatalf("valid payload after rejected requests: %d %s", rec.Code, rec.Body)
}
}
+66
View File
@@ -0,0 +1,66 @@
package chat_test
import (
"reflect"
"strings"
"testing"
"github.com/google/uuid"
"messenger/internal/chat"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
)
func TestAttachmentMessageValidatesAndOwnsOrderedIDs(t *testing.T) {
a, b := ident.New(), ident.New()
ids := []uuid.UUID{b, a}
m, err := chat.NewMessage(ident.New(), ident.New(), ident.New(), "", ids...)
if err != nil || m.Text != "" || !reflect.DeepEqual(m.AttachmentIDs, ids) {
t.Fatalf("attachment-only message = %+v, %v", m, err)
}
ids[0] = a
if m.AttachmentIDs[0] != b {
t.Fatal("message aliases caller's attachment slice")
}
for _, tc := range []struct {
text string
ids []uuid.UUID
}{
{"ok", []uuid.UUID{a, a}},
{"ok", []uuid.UUID{uuid.Nil}},
{"ok", make([]uuid.UUID, 11)},
{strings.Repeat("x", 4001), []uuid.UUID{a}},
{"nul\x00", []uuid.UUID{a}},
} {
_, err := chat.NewMessage(ident.New(), ident.New(), ident.New(), tc.text, tc.ids...)
if err == nil || apperr.KindOf(err) != apperr.KindInvalid {
t.Fatalf("invalid message accepted: %v", err)
}
}
ten := make([]uuid.UUID, 10)
for i := range ten {
ten[i] = ident.New()
}
if _, err := chat.NewMessage(ident.New(), ident.New(), ident.New(), " \n", ten...); err != nil {
t.Fatalf("ten attachments: %v", err)
}
}
func TestSameContentIncludesOrderedAttachmentsAndTreatsNilAsEmpty(t *testing.T) {
a, b := ident.New(), ident.New()
m := chat.Message{Text: "hello", AttachmentIDs: []uuid.UUID{b, a}}
for _, tc := range []struct {
ids []uuid.UUID
equal bool
}{
{[]uuid.UUID{b, a}, true}, {[]uuid.UUID{a, b}, false}, {[]uuid.UUID{a}, false}, {nil, false},
} {
if got := m.SameContent(chat.Message{Text: "hello", AttachmentIDs: tc.ids}); got != tc.equal {
t.Fatalf("attachments %v: equality=%v, want %v", tc.ids, got, tc.equal)
}
}
if !(chat.Message{Text: "hello"}).SameContent(chat.Message{Text: "hello", AttachmentIDs: []uuid.UUID{}}) {
t.Fatal("nil attachments must equal empty attachments")
}
}
+56 -12
View File
@@ -1,6 +1,8 @@
package chat
import (
"bytes"
"encoding/json"
"net/http"
"regexp"
@@ -36,7 +38,8 @@ type createChatRequest struct {
}
type createMessageRequest struct {
Text string `json:"text"`
Text *string `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
type ChatResponse struct {
@@ -47,11 +50,12 @@ type ChatResponse struct {
}
type MessageResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
}
func toChatResponse(c ChatWithMembers) ChatResponse {
@@ -68,12 +72,17 @@ func toChatResponse(c ChatWithMembers) ChatResponse {
}
func toMessageResponse(m Message) MessageResponse {
ids := make([]string, 0, len(m.AttachmentIDs))
for _, id := range m.AttachmentIDs {
ids = append(ids, id.String())
}
return MessageResponse{
ID: m.ID.String(),
ChatID: m.ChatID.String(),
SenderID: m.SenderID.String(),
Text: m.Text,
CreatedAt: httpx.Timestamp(m.CreatedAt),
AttachmentIDs: ids,
ID: m.ID.String(),
ChatID: m.ChatID.String(),
SenderID: m.SenderID.String(),
Text: m.Text,
CreatedAt: httpx.Timestamp(m.CreatedAt),
}
}
@@ -144,7 +153,16 @@ func (h *Handler) send(c *gin.Context, actor uuid.UUID) {
httpx.Error(c, err)
return
}
message, err := h.chats.Send(c.Request.Context(), actor, MessagePayload{ChatID: chatID, IdempotencyKey: key, Text: req.Text})
if req.Text == nil {
httpx.Error(c, apperr.Invalid("text must be a string"))
return
}
attachments, err := decodeAttachmentIDs(req.AttachmentIDs)
if err != nil {
httpx.Error(c, err)
return
}
message, err := h.chats.Send(c.Request.Context(), actor, MessagePayload{ChatID: chatID, IdempotencyKey: key, Text: *req.Text, AttachmentIDs: attachments})
if err != nil {
httpx.Error(c, err)
return
@@ -207,3 +225,29 @@ func listing(c *gin.Context, scope uuid.UUID) (int, *uuid.UUID, error) {
}
return limit, &last, nil
}
// RawMessage distinguishes an omitted optional array from an explicit null.
func decodeAttachmentIDs(raw json.RawMessage) ([]uuid.UUID, error) {
if raw == nil {
return nil, nil
}
if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
return nil, apperr.Invalid("attachment_ids must be an array")
}
var values []string
if err := json.Unmarshal(raw, &values); err != nil {
return nil, apperr.Invalid("attachment_ids must be an array of UUIDs")
}
if len(values) > MaxAttachments {
return nil, apperr.Invalid("attachment_ids must have at most 10 entries")
}
ids := make([]uuid.UUID, 0, len(values))
for _, value := range values {
id, err := ident.Parse(value)
if err != nil {
return nil, apperr.Invalid("attachment_ids must contain valid UUIDs")
}
ids = append(ids, id)
}
return ids, nil
}
+34 -15
View File
@@ -2,6 +2,7 @@ package chat
import (
"fmt"
"slices"
"strings"
"time"
"unicode/utf8"
@@ -12,19 +13,36 @@ import (
"messenger/internal/platform/ident"
)
const MaxTextCodePoints = 4000
const (
MaxTextCodePoints = 4000
MaxAttachments = 10
)
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
AttachmentIDs []uuid.UUID
}
// NewMessage keeps the text verbatim; only blank or oversized text is rejected.
func NewMessage(id, chatID, senderID uuid.UUID, text string) (Message, error) {
if strings.TrimSpace(text) == "" {
// NewMessage keeps text and attachment order verbatim; it owns its attachment slice.
func NewMessage(id, chatID, senderID uuid.UUID, text string, attachmentIDs ...uuid.UUID) (Message, error) {
if len(attachmentIDs) > MaxAttachments {
return Message{}, apperr.Invalid("attachment_ids must have at most 10 entries")
}
seen := make(map[uuid.UUID]struct{}, len(attachmentIDs))
for _, id := range attachmentIDs {
if id == uuid.Nil {
return Message{}, apperr.Invalid("attachment_ids must contain non-nil UUIDs")
}
if _, duplicate := seen[id]; duplicate {
return Message{}, apperr.Invalid("attachment_ids must be unique")
}
seen[id] = struct{}{}
}
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
return Message{}, apperr.Invalid("text must not be blank")
}
if utf8.RuneCountInString(text) > MaxTextCodePoints {
@@ -35,16 +53,17 @@ func NewMessage(id, chatID, senderID uuid.UUID, text string) (Message, error) {
return Message{}, apperr.Invalid("text must not contain the NUL character")
}
return Message{
ID: id,
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: ident.TimeOf(id),
ID: id,
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: ident.TimeOf(id),
AttachmentIDs: slices.Clone(attachmentIDs),
}, 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
return m.Text == other.Text && slices.Equal(m.AttachmentIDs, other.AttachmentIDs)
}
+3 -2
View File
@@ -78,15 +78,16 @@ type MessagePayload struct {
ChatID uuid.UUID
IdempotencyKey string
Text string
AttachmentIDs []uuid.UUID
}
// Send checks access and the text on every attempt, a replay included, as the
// Send checks access and content 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(), p.ChatID, actor, p.Text)
message, err := NewMessage(ident.New(), p.ChatID, actor, p.Text, p.AttachmentIDs...)
if err != nil {
return Message{}, err
}
+3 -2
View File
@@ -7,6 +7,7 @@ import (
"io"
"log/slog"
"os"
"reflect"
"strings"
"sync/atomic"
"testing"
@@ -217,14 +218,14 @@ func TestHistoryPagesAndHidesForeignChat(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(page.Items) != 1 || page.Items[0] != first || page.Next == nil || *page.Next != first.ID {
if len(page.Items) != 1 || !reflect.DeepEqual(page.Items[0], first) || page.Next == nil || *page.Next != first.ID {
t.Fatalf("first page = %+v", page)
}
rest, err := f.svc.History(f.ctx, f.alice, c.ID, page.Next, 1)
if err != nil {
t.Fatal(err)
}
if len(rest.Items) != 1 || rest.Items[0] != second || rest.Next != nil {
if len(rest.Items) != 1 || !reflect.DeepEqual(rest.Items[0], second) || rest.Next != nil {
t.Fatalf("second page = %+v", rest)
}
if _, err := f.svc.History(f.ctx, f.eve, c.ID, nil, 10); !errors.Is(err, chat.ErrNotFound) {
+312
View File
@@ -0,0 +1,312 @@
package store_test
import (
"context"
"crypto/sha256"
"fmt"
"reflect"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/chat"
"messenger/internal/chat/store"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
)
func (f fixture) attachment(t *testing.T, chatID, owner uuid.UUID, status string) uuid.UUID {
t.Helper()
id := ident.New()
hash := sha256.Sum256([]byte(id.String()))
_, err := db.Pool.Exec(f.ctx, `
WITH file AS (
INSERT INTO files (hash, size_bytes, mime_type, status, created_at)
VALUES ($1, 7, 'image/png', $2, now()) RETURNING hash)
INSERT INTO attachments (id, chat_id, owner_id, filename, file_hash, created_at)
SELECT $3, $4, $5, 'image.png', hash, now() FROM file`,
hash[:], status, id, chatID, owner)
if err != nil {
t.Fatal(err)
}
return id
}
func attachedMessage(t *testing.T, c, sender uuid.UUID, ids ...uuid.UUID) chat.Message {
t.Helper()
m, err := chat.NewMessage(ident.New(), c, sender, "", ids...)
if err != nil {
t.Fatal(err)
}
return m
}
func assertCounts(t *testing.T, messages, keys, joins int) {
t.Helper()
var gotMessages, gotKeys, gotJoins int
err := db.Pool.QueryRow(context.Background(), `
SELECT (SELECT count(*) FROM messages),
(SELECT count(*) FROM message_idempotency_keys),
(SELECT count(*) FROM message_attachments)`).Scan(&gotMessages, &gotKeys, &gotJoins)
if err != nil || gotMessages != messages || gotKeys != keys || gotJoins != joins {
t.Fatalf("counts = %d/%d/%d, %v; want %d/%d/%d", gotMessages, gotKeys, gotJoins, err, messages, keys, joins)
}
}
func TestAppendOnceRejectsUnknownAttachmentWithoutClaim(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
m := attachedMessage(t, c.ID, alice, ident.New())
_, err := f.messages.AppendOnce(f.ctx, m, "unknown", keyTTL)
if err == nil || apperr.KindOf(err) != apperr.KindNotFound {
t.Fatalf("unknown attachment: %v; want not found", err)
}
var messages, keys int
err = db.Pool.QueryRow(f.ctx, `SELECT (SELECT count(*) FROM messages), (SELECT count(*) FROM message_idempotency_keys)`).Scan(&messages, &keys)
if err != nil || messages != 0 || keys != 0 {
t.Fatalf("failed validation persisted %d messages/%d keys: %v", messages, keys, err)
}
}
func TestAppendOnceAttachmentValidationIsAtomic(t *testing.T) {
for _, status := range []string{"foreign", "failed", "pending", "mixed"} {
t.Run(status, func(t *testing.T) {
f := newFixture(t)
alice, bob := f.mustUser(t), f.mustUser(t)
c := f.mustChat(t, alice, bob)
other := f.mustChat(t, alice)
ready := f.attachment(t, c.ID, bob, "ready")
var invalid uuid.UUID
want := apperr.KindConflict
switch status {
case "foreign":
invalid = f.attachment(t, other.ID, alice, "ready")
want = apperr.KindNotFound
case "mixed":
ready = f.attachment(t, c.ID, bob, "failed")
invalid = ident.New()
want = apperr.KindNotFound
default:
invalid = f.attachment(t, c.ID, alice, status)
}
_, err := f.messages.AppendOnce(f.ctx, attachedMessage(t, c.ID, alice, ready, invalid), "bad", keyTTL)
if err == nil || apperr.KindOf(err) != want {
t.Fatalf("validation: %v; want %v", err, want)
}
assertCounts(t, 0, 0, 0)
good := f.attachment(t, c.ID, bob, "ready")
f.appendOnce(t, attachedMessage(t, c.ID, alice, good), "bad")
assertCounts(t, 1, 1, 1)
})
}
}
func TestAppendOnceAttachmentOrderReplayAndExpiration(t *testing.T) {
f := newFixture(t)
alice, bob := f.mustUser(t), f.mustUser(t)
c := f.mustChat(t, alice, bob)
a, b := f.attachment(t, c.ID, bob, "ready"), f.attachment(t, c.ID, bob, "ready")
first := attachedMessage(t, c.ID, alice, b, a)
got := f.appendOnce(t, first, "k")
if !reflect.DeepEqual(got, first) {
t.Fatalf("append = %+v, want %+v", got, first)
}
replayed := f.appendOnce(t, attachedMessage(t, c.ID, alice, a, b), "k")
if !reflect.DeepEqual(replayed, first) {
t.Fatalf("replay must return original ordered attachments: %+v", replayed)
}
assertCounts(t, 1, 1, 2)
expire(t)
second := attachedMessage(t, c.ID, bob, a)
f.appendOnce(t, second, "k2")
replacement := attachedMessage(t, c.ID, alice, a, b)
f.appendOnce(t, replacement, "k")
assertCounts(t, 3, 2, 5)
page, err := f.messages.ListByChat(f.ctx, c.ID, nil, 1)
if err != nil || len(page) != 1 || !reflect.DeepEqual(page[0], first) {
t.Fatalf("first page = %+v, %v", page, err)
}
page, err = f.messages.ListByChat(f.ctx, c.ID, &first.ID, 10)
if err != nil || !reflect.DeepEqual(page, []chat.Message{second, replacement}) {
t.Fatalf("remaining page = %+v, %v", page, err)
}
}
func TestAppendOnceRevalidatesAttachmentOnReplay(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
a := f.attachment(t, c.ID, alice, "ready")
first := attachedMessage(t, c.ID, alice, a)
f.appendOnce(t, first, "k")
if _, err := db.Pool.Exec(f.ctx, `UPDATE files SET status = 'failed'`); err != nil {
t.Fatal(err)
}
_, err := f.messages.AppendOnce(f.ctx, attachedMessage(t, c.ID, alice, a), "k", keyTTL)
if err == nil || apperr.KindOf(err) != apperr.KindConflict {
t.Fatalf("failed replay attachment = %v, want conflict", err)
}
page, err := f.messages.ListByChat(f.ctx, c.ID, nil, 10)
if err != nil || len(page) != 1 || !reflect.DeepEqual(page[0], first) {
t.Fatalf("failed blob must preserve history attachment ids: %+v, %v", page, err)
}
assertCounts(t, 1, 1, 1)
}
func TestAppendOnceRollsBackClaimAndMessageOnJoinFailure(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
a := f.attachment(t, c.ID, alice, "ready")
// A database fault at the join boundary must not leave a key or message.
_, err := db.Pool.Exec(f.ctx, `ALTER TABLE message_attachments ADD CONSTRAINT test_reject_join CHECK (ordinal < 0)`)
if err != nil {
t.Fatal(err)
}
defer func() {
if _, err := db.Pool.Exec(f.ctx, `ALTER TABLE message_attachments DROP CONSTRAINT test_reject_join`); err != nil {
t.Error(err)
}
}()
if _, err := f.messages.AppendOnce(f.ctx, attachedMessage(t, c.ID, alice, a), "k", keyTTL); err == nil {
t.Fatal("join fault must fail append")
}
assertCounts(t, 0, 0, 0)
}
func TestConcurrentAttachmentAppendsSameKeyStoreOneOrderedSet(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
a, b := f.attachment(t, c.ID, alice, "ready"), f.attachment(t, c.ID, alice, "ready")
const requests = 20
results := make(chan chat.Message, requests)
start := make(chan struct{})
var wg sync.WaitGroup
for i := range requests {
ids := []uuid.UUID{a, b}
if i%2 != 0 {
ids = []uuid.UUID{b, a}
}
m := attachedMessage(t, c.ID, alice, ids...)
wg.Go(func() {
<-start
got, err := f.messages.AppendOnce(f.ctx, m, "same", keyTTL)
if err != nil {
t.Error(err)
return
}
results <- got
})
}
close(start)
wg.Wait()
close(results)
var winner *chat.Message
n := 0
for got := range results {
n++
if winner == nil {
winner = &got
} else if !reflect.DeepEqual(got, *winner) {
t.Fatalf("concurrent replay differs: %+v, want %+v", got, *winner)
}
}
if n != requests {
t.Fatalf("got %d successful replies, want %d", n, requests)
}
assertCounts(t, 1, 1, 2)
}
type queryCounter struct{ count atomic.Int32 }
func (c *queryCounter) TraceQueryStart(ctx context.Context, _ *pgx.Conn, _ pgx.TraceQueryStartData) context.Context {
c.count.Add(1)
return ctx
}
func (*queryCounter) TraceQueryEnd(context.Context, *pgx.Conn, pgx.TraceQueryEndData) {}
func TestAttachmentHistorySingleQueryAndBatchedValidation(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
var ids []uuid.UUID
for range 10 {
ids = append(ids, f.attachment(t, c.ID, alice, "ready"))
}
cfg := db.Pool.Config()
counter := &queryCounter{}
cfg.ConnConfig.Tracer = counter
pool, err := pgxpool.NewWithConfig(f.ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err := pool.Ping(f.ctx); err != nil {
t.Fatal(err)
}
repo := store.NewMessages(pool)
counter.count.Store(0)
if _, err := repo.AppendOnce(f.ctx, attachedMessage(t, c.ID, alice, ids[0]), "one", keyTTL); err != nil {
t.Fatal(err)
}
one := counter.count.Swap(0)
if _, err := repo.AppendOnce(f.ctx, attachedMessage(t, c.ID, alice, ids...), "ten", keyTTL); err != nil {
t.Fatal(err)
}
ten := counter.count.Swap(0)
if one != ten {
t.Fatalf("queries grew from %d to %d for 1 vs 10 attachments", one, ten)
}
page, err := repo.ListByChat(f.ctx, c.ID, nil, 10)
if err != nil || len(page) != 2 || !reflect.DeepEqual(page[1].AttachmentIDs, ids) {
t.Fatalf("history = %+v, %v", page, err)
}
if n := counter.count.Load(); n != 1 {
t.Fatalf("history used %d queries, want one", n)
}
}
func TestAppendOnceRetriesWhenBoundKeyDisappears(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
first := f.newMessage(t, c.ID, alice)
f.appendOnce(t, first, "vanish")
next := f.newMessage(t, c.ID, alice)
// Simulate the missing-key boundary after an unsuccessful claim using a
// statement trigger. Its second invocation sees no key and is a no-op.
_, err := db.Pool.Exec(f.ctx, fmt.Sprintf(`
CREATE FUNCTION test_vanish_key() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM messages WHERE id = '%s'::uuid) THEN
DELETE FROM message_idempotency_keys WHERE key = 'vanish';
END IF;
RETURN NULL;
END $$;
CREATE TRIGGER test_vanish_key AFTER INSERT ON messages
FOR EACH STATEMENT EXECUTE FUNCTION test_vanish_key()`, next.ID.String()))
if err != nil {
t.Fatal(err)
}
defer func() {
if _, err := db.Pool.Exec(f.ctx, `DROP TRIGGER test_vanish_key ON messages; DROP FUNCTION test_vanish_key()`); err != nil {
t.Error(err)
}
}()
ctx, cancel := context.WithTimeout(f.ctx, 3*time.Second)
defer cancel()
got, err := f.messages.AppendOnce(ctx, next, "vanish", keyTTL)
if err != nil || got.ID != next.ID {
t.Fatalf("missing bound key = %+v, %v; want new message", got, err)
}
if n := f.count(t, c.ID); n != 2 {
t.Fatalf("history has %d messages, want 2", n)
}
}
+99 -29
View File
@@ -19,6 +19,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/chat"
"messenger/internal/platform/apperr"
"messenger/internal/platform/postgres"
)
@@ -118,9 +119,8 @@ func NewMessages(pool *pgxpool.Pool) *Messages {
return &Messages{pool: pool}
}
// 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.
// claimSQL binds the key and inserts the message in one statement. An expired
// key is taken over; a valid one leaves claimed and the message insert empty.
const claimSQL = `
WITH claimed AS (
INSERT INTO message_idempotency_keys AS k (user_id, chat_id, key, message_id)
@@ -132,30 +132,100 @@ const claimSQL = `
INSERT INTO messages (chat_id, id, sender_id, text, created_at)
SELECT $2, message_id, $1, $6, $7 FROM claimed`
// The bound message is read by a second statement: the claim's snapshot
// cannot see a key that a concurrent request has just committed.
// The transaction keeps attachment readiness, message joins and the key atomic.
// The replay uses a new statement snapshot to see a concurrent winner.
func (r *Messages) AppendOnce(ctx context.Context, m chat.Message, key string, ttl time.Duration) (chat.Message, error) {
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
}
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)
err := pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error {
if err := validateAttachments(ctx, tx, m.ChatID, m.AttachmentIDs); err != nil {
return err
}
for {
if err := ctx.Err(); err != nil {
return err
}
tag, err := tx.Exec(ctx, claimSQL,
m.SenderID, m.ChatID, key, m.ID, interval(ttl), m.Text, m.CreatedAt)
if err != nil {
return fmt.Errorf("insert message: %w", err)
}
if tag.RowsAffected() == 1 {
if len(m.AttachmentIDs) > 0 {
_, err := tx.Exec(ctx, `
INSERT INTO message_attachments (chat_id, message_id, attachment_id, ordinal)
SELECT $1, $2, id, (ord - 1)::smallint
FROM unnest($3::uuid[]) WITH ORDINALITY AS a(id, ord)`,
m.ChatID, m.ID, m.AttachmentIDs)
if err != nil {
return fmt.Errorf("insert message attachments: %w", err)
}
}
stored = m
return nil
}
stored, err = scanMessage(tx.QueryRow(ctx, `
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(SELECT a.attachment_id FROM message_attachments a
WHERE a.chat_id = m.chat_id AND a.message_id = m.id ORDER BY a.ordinal)
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))
if errors.Is(err, pgx.ErrNoRows) {
// A vanished key is available again; retry its atomic claim.
continue
}
if err != nil {
return fmt.Errorf("select message by key: %w", err)
}
return nil
}
})
if err != nil {
return chat.Message{}, fmt.Errorf("select message by key: %w", postgres.Classify(err))
return chat.Message{}, postgres.Classify(err)
}
return stored, nil
}
func validateAttachments(ctx context.Context, tx pgx.Tx, chatID uuid.UUID, ids []uuid.UUID) error {
if len(ids) == 0 {
return nil
}
// Shared row locks prevent deletion or a readiness change until joins commit.
rows, err := tx.Query(ctx, `
SELECT f.status
FROM attachments a
JOIN files f ON f.hash = a.file_hash
WHERE a.chat_id = $1 AND a.id = ANY($2::uuid[])
ORDER BY a.id
FOR SHARE OF a, f`, chatID, ids)
if err != nil {
return fmt.Errorf("check attachments: %w", err)
}
statuses, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
return fmt.Errorf("read attachment status: %w", err)
}
if len(statuses) != len(ids) {
return apperr.NotFound("attachment not found")
}
for _, status := range statuses {
if status != "ready" {
return apperr.Conflict("attachment is not ready")
}
}
return nil
}
func scanMessage(row pgx.Row) (chat.Message, error) {
var m chat.Message
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs)
if len(m.AttachmentIDs) == 0 {
m.AttachmentIDs = nil
}
return m, err
}
// 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) {
@@ -179,14 +249,16 @@ func interval(d time.Duration) string {
return fmt.Sprintf("%d milliseconds", d.Milliseconds())
}
// ListByChat is the history query; scripts/explain-history.sql runs the same
// statement for the EXPLAIN evidence.
// ListByChat keeps keyset pagination on messages and collects each ordered
// attachment array in the same statement.
func (r *Messages) ListByChat(ctx context.Context, chatID uuid.UUID, after *uuid.UUID, limit int) ([]chat.Message, error) {
rows, err := r.pool.Query(ctx, `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
AND id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(SELECT a.attachment_id FROM message_attachments a
WHERE a.chat_id = m.chat_id AND a.message_id = m.id ORDER BY a.ordinal)
FROM messages m
WHERE m.chat_id = $1
AND m.id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)
ORDER BY id
LIMIT $3`,
chatID, after, limit)
@@ -194,9 +266,7 @@ func (r *Messages) ListByChat(ctx context.Context, chatID uuid.UUID, after *uuid
return nil, fmt.Errorf("select messages: %w", postgres.Classify(err))
}
messages, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (chat.Message, error) {
var m chat.Message
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
return m, err
return scanMessage(row)
})
if err != nil {
return nil, fmt.Errorf("read messages: %w", postgres.Classify(err))
+2 -1
View File
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"os"
"reflect"
"sync"
"testing"
"time"
@@ -214,7 +215,7 @@ func TestAppendOutOfOrderIsListedByID(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(got) != 3 || got[0] != first || got[1] != second || got[2] != third {
if len(got) != 3 || !reflect.DeepEqual(got[0], first) || !reflect.DeepEqual(got[1], second) || !reflect.DeepEqual(got[2], third) {
t.Fatalf("history must be ordered by id and round-trip every field, got %+v", got)
}
}