Добавьте S3-вложения с дедупликацией и безопасной сверкой хранилищ
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user