400 lines
13 KiB
Go
400 lines
13 KiB
Go
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/pipeline"
|
|
"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[:], "pending", id, chatID, owner)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, err = db.Pool.Exec(f.ctx, `INSERT INTO attachment_jobs(attachment_id,source_key,state,error_code)
|
|
VALUES ($1,$2,$3,CASE WHEN $3='failed' THEN 'source_missing' END)`, id, "staging/"+id.String(), status)
|
|
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 TestAppendOnceAcceptsQueuedAttachmentDuringPublish(t *testing.T) {
|
|
f := newFixture(t)
|
|
alice := f.mustUser(t)
|
|
c := f.mustChat(t, alice)
|
|
id := f.attachment(t, c.ID, alice, "queued")
|
|
m := attachedMessage(t, c.ID, alice, id)
|
|
found, err := pipeline.NewStore(db.Pool).PublishOne(f.ctx, func(ctx context.Context, j pipeline.Job) error {
|
|
if j.AttachmentID != id {
|
|
t.Fatalf("publisher selected %s, want %s", j.AttachmentID, id)
|
|
}
|
|
// The callback holds the publisher transaction open until AppendOnce returns.
|
|
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
|
defer cancel()
|
|
_, err := f.messages.AppendOnce(ctx, m, "during-publish", keyTTL)
|
|
return err
|
|
})
|
|
if err != nil || !found {
|
|
t.Fatalf("linking queued attachment while awaiting broker confirm: found=%v, err=%v", found, err)
|
|
}
|
|
assertCounts(t, 1, 1, 1)
|
|
}
|
|
|
|
func TestAppendOnceSeesFailureCommittedWhileValidating(t *testing.T) {
|
|
f := newFixture(t)
|
|
alice := f.mustUser(t)
|
|
c := f.mustChat(t, alice)
|
|
id := f.attachment(t, c.ID, alice, "queued")
|
|
if _, err := db.Pool.Exec(f.ctx, `UPDATE attachment_jobs SET state='processing',
|
|
lease_token=gen_random_uuid(),lease_until=now()+interval '1 hour' WHERE attachment_id=$1`, id); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
tx, err := db.Pool.Begin(f.ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer tx.Rollback(f.ctx)
|
|
// Fail and lease recovery both take this lock before deciding the terminal state.
|
|
if _, err := tx.Exec(f.ctx, `SELECT job_id FROM attachment_jobs WHERE attachment_id=$1 FOR UPDATE`, id); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := tx.Exec(f.ctx, `UPDATE attachment_jobs SET state='failed',error_code='retry_exhausted',
|
|
lease_token=NULL,lease_until=NULL WHERE attachment_id=$1`, id); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
m := attachedMessage(t, c.ID, alice, id)
|
|
ctx, cancel := context.WithTimeout(f.ctx, 5*time.Second)
|
|
defer cancel()
|
|
done := make(chan error, 1)
|
|
go func() {
|
|
_, err := f.messages.AppendOnce(ctx, m, "failing", keyTTL)
|
|
done <- err
|
|
}()
|
|
for {
|
|
var waiting bool
|
|
err := db.Pool.QueryRow(ctx, `SELECT EXISTS (
|
|
SELECT FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)))`, tx.Conn().PgConn().PID()).Scan(&waiting)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if waiting {
|
|
break
|
|
}
|
|
select {
|
|
case err := <-done:
|
|
t.Fatalf("message finished before the terminal transition: %v", err)
|
|
case <-time.After(10 * time.Millisecond):
|
|
}
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := <-done; err == nil || apperr.KindOf(err) != apperr.KindConflict {
|
|
t.Fatalf("message with concurrently failed attachment: %v; want conflict", err)
|
|
}
|
|
assertCounts(t, 0, 0, 0)
|
|
}
|
|
|
|
func TestAppendOnceAttachmentValidationIsAtomic(t *testing.T) {
|
|
for _, status := range []string{"foreign", "failed", "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, "queued")
|
|
var invalid uuid.UUID
|
|
want := apperr.KindConflict
|
|
switch status {
|
|
case "foreign":
|
|
invalid = f.attachment(t, other.ID, alice, "queued")
|
|
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, "queued")
|
|
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, "queued"), f.attachment(t, c.ID, bob, "queued")
|
|
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 TestAppendOnceReplaysAcceptedMessageAfterAttachmentFails(t *testing.T) {
|
|
f := newFixture(t)
|
|
alice := f.mustUser(t)
|
|
c := f.mustChat(t, alice)
|
|
a := f.attachment(t, c.ID, alice, "queued")
|
|
first := attachedMessage(t, c.ID, alice, a)
|
|
f.appendOnce(t, first, "k")
|
|
if _, err := db.Pool.Exec(f.ctx, `UPDATE attachment_jobs SET state = 'failed',error_code='source_missing'`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got := f.appendOnce(t, attachedMessage(t, c.ID, alice, a), "k")
|
|
if !reflect.DeepEqual(got, first) {
|
|
t.Fatalf("replay = %+v, want original %+v", got, first)
|
|
}
|
|
_, err := f.messages.AppendOnce(f.ctx, attachedMessage(t, c.ID, alice, a), "new", keyTTL)
|
|
if err == nil || apperr.KindOf(err) != apperr.KindConflict {
|
|
t.Fatalf("new message with failed 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, "queued")
|
|
// 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, "queued"), f.attachment(t, c.ID, alice, "queued")
|
|
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, "queued"))
|
|
}
|
|
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)
|
|
}
|
|
}
|