Перенесите реализацию ЛР 4 на стенд ЛР 5
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
)
|
||||
|
||||
const keyTTL = time.Hour
|
||||
|
||||
// expire makes every stored key older than keyTTL.
|
||||
func expire(t *testing.T) {
|
||||
t.Helper()
|
||||
if _, err := db.Pool.Exec(context.Background(),
|
||||
`UPDATE message_idempotency_keys SET created_at = now() - interval '2 hours'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (f fixture) appendOnce(t *testing.T, m chat.Message, key string) chat.Message {
|
||||
t.Helper()
|
||||
got, err := f.messages.AppendOnce(f.ctx, m, key, keyTTL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func (f fixture) count(t *testing.T, chatID uuid.UUID) int {
|
||||
t.Helper()
|
||||
got, err := f.messages.ListByChat(f.ctx, chatID, nil, 1000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return len(got)
|
||||
}
|
||||
|
||||
func keyTarget(t *testing.T, key string) uuid.UUID {
|
||||
t.Helper()
|
||||
var id uuid.UUID
|
||||
if err := db.Pool.QueryRow(context.Background(),
|
||||
`SELECT message_id FROM message_idempotency_keys WHERE key = $1`, key).Scan(&id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func TestAppendOnceInsertsThenReplays(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
first := f.newMessage(t, c.ID, alice)
|
||||
if got := f.appendOnce(t, first, "k1"); got.ID != first.ID {
|
||||
t.Fatalf("first append returned %v, want the new message %v", got.ID, first.ID)
|
||||
}
|
||||
retry := f.newMessage(t, c.ID, alice)
|
||||
got := f.appendOnce(t, retry, "k1")
|
||||
if got.ID != first.ID || !got.CreatedAt.Equal(first.CreatedAt) || got.Text != first.Text || got.SenderID != alice {
|
||||
t.Fatalf("replay returned %+v, want the stored %+v", got, first)
|
||||
}
|
||||
if n := f.count(t, c.ID); n != 1 {
|
||||
t.Fatalf("history has %d messages, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendOnceTakesOverExpiredKey(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")
|
||||
expire(t)
|
||||
next := f.newMessage(t, c.ID, alice)
|
||||
if got := f.appendOnce(t, next, "k1"); got.ID != next.ID {
|
||||
t.Fatalf("expired key returned %v, want the new message %v", got.ID, next.ID)
|
||||
}
|
||||
if n := f.count(t, c.ID); n != 2 {
|
||||
t.Fatalf("history has %d messages, want 2", n)
|
||||
}
|
||||
if target := keyTarget(t, "k1"); target != next.ID {
|
||||
t.Fatalf("key points to %v, want %v", target, next.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// A cleaner batch holds the expired key row; the request waits for it and,
|
||||
// once the row is gone, inserts its message under the now free key.
|
||||
func TestAppendOnceWaitsForCleanerThenInserts(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")
|
||||
expire(t)
|
||||
|
||||
tx, err := db.Pool.Begin(f.ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tx.Rollback(f.ctx)
|
||||
if _, err := tx.Exec(f.ctx, `SELECT 1 FROM message_idempotency_keys WHERE key = 'k1' FOR UPDATE`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
next := f.newMessage(t, c.ID, alice)
|
||||
type result struct {
|
||||
m chat.Message
|
||||
err error
|
||||
}
|
||||
done := make(chan result, 1)
|
||||
go func() {
|
||||
m, err := f.messages.AppendOnce(f.ctx, next, "k1", keyTTL)
|
||||
done <- result{m, err}
|
||||
}()
|
||||
select {
|
||||
case r := <-done:
|
||||
t.Fatalf("AppendOnce did not wait for the locked key: %+v", r)
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
if _, err := tx.Exec(f.ctx, `DELETE FROM message_idempotency_keys WHERE key = 'k1'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(f.ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case r := <-done:
|
||||
if r.err != nil || r.m.ID != next.ID {
|
||||
t.Fatalf("after the cleaner: %+v, %v; want the new message %v", r.m, r.err, next.ID)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("AppendOnce did not finish after the cleaner committed")
|
||||
}
|
||||
}
|
||||
|
||||
// A request holding a key row must not make the cleaner wait: it skips the
|
||||
// row and deletes it on a later run.
|
||||
func TestCleanerSkipsRowLockedByRequest(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")
|
||||
expire(t)
|
||||
|
||||
tx, err := db.Pool.Begin(f.ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tx.Exec(f.ctx, `SELECT 1 FROM message_idempotency_keys WHERE key = 'k1' FOR UPDATE`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := time.Now()
|
||||
n, err := f.messages.DeleteExpiredKeys(f.ctx, keyTTL, 1000)
|
||||
if err != nil || n != 0 {
|
||||
t.Fatalf("cleaner over a locked row: deleted %d, %v; want 0", n, err)
|
||||
}
|
||||
if waited := time.Since(start); waited > time.Second {
|
||||
t.Fatalf("cleaner waited %v for the locked row", waited)
|
||||
}
|
||||
if err := tx.Rollback(f.ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := f.messages.DeleteExpiredKeys(f.ctx, keyTTL, 1000); err != nil || n != 1 {
|
||||
t.Fatalf("cleaner after release: deleted %d, %v; want 1", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteExpiredKeysOnlyExpiredAndUpToLimit(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
for _, k := range []string{"a", "b", "c"} {
|
||||
f.appendOnce(t, f.newMessage(t, c.ID, alice), k)
|
||||
}
|
||||
expire(t)
|
||||
f.appendOnce(t, f.newMessage(t, c.ID, alice), "fresh")
|
||||
|
||||
if n, err := f.messages.DeleteExpiredKeys(f.ctx, keyTTL, 2); err != nil || n != 2 {
|
||||
t.Fatalf("first batch deleted %d, %v; want 2", n, err)
|
||||
}
|
||||
if n, err := f.messages.DeleteExpiredKeys(f.ctx, keyTTL, 2); err != nil || n != 1 {
|
||||
t.Fatalf("second batch deleted %d, %v; want 1", n, err)
|
||||
}
|
||||
var left int
|
||||
if err := db.Pool.QueryRow(f.ctx, `SELECT count(*) FROM message_idempotency_keys`).Scan(&left); err != nil || left != 1 {
|
||||
t.Fatalf("%d keys left, %v; want only the fresh one", left, err)
|
||||
}
|
||||
if n := f.count(t, c.ID); n != 4 {
|
||||
t.Fatalf("cleanup removed messages: %d left, want 4", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Every request brings its own new message under one key; exactly one is
|
||||
// stored and all of them get it back. This also proves the key row and the
|
||||
// message it references are written by one statement.
|
||||
func TestConcurrentAppendOnceSameKeyStoresOneMessage(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
const requests = 20
|
||||
ids := make(chan uuid.UUID, requests)
|
||||
var wg sync.WaitGroup
|
||||
for range requests {
|
||||
m := f.newMessage(t, c.ID, alice)
|
||||
wg.Go(func() {
|
||||
got, err := f.messages.AppendOnce(f.ctx, m, "same", keyTTL)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
ids <- got.ID
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(ids)
|
||||
seen := map[uuid.UUID]int{}
|
||||
for id := range ids {
|
||||
seen[id]++
|
||||
}
|
||||
if len(seen) != 1 {
|
||||
t.Fatalf("requests got %d different messages, want 1: %v", len(seen), seen)
|
||||
}
|
||||
if n := f.count(t, c.ID); n != 1 {
|
||||
t.Fatalf("history has %d messages, want 1", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// Package store holds the repository implementations of the chats module.
|
||||
//
|
||||
// Keyset pages use `id > COALESCE($after, nil uuid)`: every UUIDv7 is
|
||||
// greater than the nil UUID, so one query serves the first page and the
|
||||
// following ones, and the condition stays a range the index can scan. Ids
|
||||
// are UUIDv7 and created_at derives from them, so ordering by id is the
|
||||
// contract order (created_at, id). Errors pass through postgres.Classify, so
|
||||
// an unreachable database surfaces as unavailability.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/internal/attachment"
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/postgres"
|
||||
)
|
||||
|
||||
type Chats struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
var _ chat.ChatRepository = (*Chats)(nil)
|
||||
|
||||
func NewChats(pool *pgxpool.Pool) *Chats {
|
||||
return &Chats{pool: pool}
|
||||
}
|
||||
|
||||
func (r *Chats) Create(ctx context.Context, c chat.Chat, memberIDs []uuid.UUID) error {
|
||||
return postgres.Classify(pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||
c.ID, c.Title, c.CreatedAt); err != nil {
|
||||
return fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO chat_members (chat_id, user_id) SELECT $1, unnest($2::uuid[])`,
|
||||
c.ID, memberIDs); err != nil {
|
||||
return fmt.Errorf("insert chat members: %w", err)
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
}
|
||||
|
||||
func (r *Chats) GetForMember(ctx context.Context, chatID, userID uuid.UUID) (chat.ChatWithMembers, error) {
|
||||
row := r.pool.QueryRow(ctx, `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
|
||||
FROM chats c
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID)
|
||||
c, err := scanChat(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return chat.ChatWithMembers{}, chat.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return chat.ChatWithMembers{}, fmt.Errorf("select chat: %w", postgres.Classify(err))
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (r *Chats) IsMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) {
|
||||
var ok bool
|
||||
err := r.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID).Scan(&ok)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check membership: %w", postgres.Classify(err))
|
||||
}
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (r *Chats) ListByMember(ctx context.Context, userID uuid.UUID, after *uuid.UUID, limit int) ([]chat.ChatWithMembers, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
|
||||
FROM chat_members own
|
||||
JOIN chats c ON c.id = own.chat_id
|
||||
WHERE own.user_id = $1
|
||||
AND own.chat_id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)
|
||||
ORDER BY own.chat_id
|
||||
LIMIT $3`,
|
||||
userID, after, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select chats: %w", postgres.Classify(err))
|
||||
}
|
||||
chats, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (chat.ChatWithMembers, error) {
|
||||
return scanChat(row)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read chats: %w", postgres.Classify(err))
|
||||
}
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
func scanChat(row pgx.Row) (chat.ChatWithMembers, error) {
|
||||
var c chat.ChatWithMembers
|
||||
if err := row.Scan(&c.ID, &c.Title, &c.CreatedAt, &c.MemberIDs); err != nil {
|
||||
return chat.ChatWithMembers{}, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type Messages struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
var _ chat.MessageRepository = (*Messages)(nil)
|
||||
|
||||
func NewMessages(pool *pgxpool.Pool) *Messages {
|
||||
return &Messages{pool: pool}
|
||||
}
|
||||
|
||||
// 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)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (user_id, chat_id, key) DO UPDATE
|
||||
SET message_id = EXCLUDED.message_id, created_at = now()
|
||||
WHERE k.created_at < now() - $5::interval
|
||||
RETURNING message_id)
|
||||
INSERT INTO messages (chat_id, id, sender_id, text, created_at)
|
||||
SELECT $2, message_id, $1, $6, $7 FROM claimed`
|
||||
|
||||
// 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) {
|
||||
var stored chat.Message
|
||||
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{}, 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[attachment.FileStatus])
|
||||
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 != attachment.FileReady {
|
||||
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) {
|
||||
tag, err := r.pool.Exec(ctx, `
|
||||
DELETE FROM message_idempotency_keys
|
||||
WHERE (user_id, chat_id, key) IN (
|
||||
SELECT user_id, chat_id, key FROM message_idempotency_keys
|
||||
WHERE created_at < now() - $1::interval
|
||||
ORDER BY created_at
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED)`,
|
||||
interval(olderThan), limit)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete expired keys: %w", postgres.Classify(err))
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
// interval renders d for a ::interval parameter.
|
||||
func interval(d time.Duration) string {
|
||||
return fmt.Sprintf("%d milliseconds", d.Milliseconds())
|
||||
}
|
||||
|
||||
// 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 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)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select messages: %w", postgres.Classify(err))
|
||||
}
|
||||
messages, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (chat.Message, error) {
|
||||
return scanMessage(row)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read messages: %w", postgres.Classify(err))
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/chat/store"
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/testenv"
|
||||
"messenger/internal/user"
|
||||
userstore "messenger/internal/user/store"
|
||||
)
|
||||
|
||||
var db *testenv.DB
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
var err error
|
||||
db, err = testenv.StartPostgres(context.Background())
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
code := m.Run()
|
||||
db.Close()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
type fixture struct {
|
||||
ctx context.Context
|
||||
chats *store.Chats
|
||||
messages *store.Messages
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T) fixture {
|
||||
t.Helper()
|
||||
db.Reset(t)
|
||||
return fixture{ctx: context.Background(), chats: store.NewChats(db.Pool), messages: store.NewMessages(db.Pool)}
|
||||
}
|
||||
|
||||
// mustUser stores a user row: chats and messages reference users by FK.
|
||||
func (f fixture) mustUser(t *testing.T) uuid.UUID {
|
||||
t.Helper()
|
||||
id := ident.New()
|
||||
u, err := user.New(id, "u"+id.String()[24:], "User")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u.PasswordHash = "x"
|
||||
if err := userstore.NewUsers(db.Pool).Create(f.ctx, u); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func (f fixture) mustChat(t *testing.T, members ...uuid.UUID) chat.Chat {
|
||||
t.Helper()
|
||||
c, err := chat.NewChat(ident.New(), "title")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.chats.Create(f.ctx, c, members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (f fixture) newMessage(t *testing.T, chatID, sender uuid.UUID) chat.Message {
|
||||
t.Helper()
|
||||
m, err := chat.NewMessage(ident.New(), chatID, sender, "text")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// appendErr stores m under a key of its own, as every send now carries one.
|
||||
func (f fixture) appendErr(m chat.Message) error {
|
||||
_, err := f.messages.AppendOnce(f.ctx, m, m.ID.String(), time.Hour)
|
||||
return err
|
||||
}
|
||||
|
||||
func TestChatCreateThenGetForMember(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice, bob := f.mustUser(t), f.mustUser(t)
|
||||
c := f.mustChat(t, alice, bob)
|
||||
|
||||
got, err := f.chats.GetForMember(f.ctx, c.ID, bob)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Chat != c || len(got.MemberIDs) != 2 || got.MemberIDs[0] != alice || got.MemberIDs[1] != bob {
|
||||
t.Fatalf("GetForMember = %+v, want %+v with members [alice bob]", got, c)
|
||||
}
|
||||
if _, err := f.chats.GetForMember(f.ctx, c.ID, f.mustUser(t)); !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("outsider must get ErrNotFound, got %v", err)
|
||||
}
|
||||
for who, want := range map[uuid.UUID]bool{alice: true, bob: true, ident.New(): false} {
|
||||
ok, err := f.chats.IsMember(f.ctx, c.ID, who)
|
||||
if err != nil || ok != want {
|
||||
t.Fatalf("IsMember(%s) = %v, %v; want %v", who, ok, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The chat row and its members are written in one transaction: a failing
|
||||
// member insert must leave no chat behind.
|
||||
func TestCreateRollsBackWhenMemberInsertFails(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c, err := chat.NewChat(ident.New(), "half-made")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.chats.Create(f.ctx, c, []uuid.UUID{alice, ident.New()}); err == nil {
|
||||
t.Fatal("Create with an unknown member must fail")
|
||||
}
|
||||
var chats, members int
|
||||
if err := db.Pool.QueryRow(f.ctx, `SELECT (SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members)`).Scan(&chats, &members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if chats != 0 || members != 0 {
|
||||
t.Fatalf("chats = %d, members = %d after a failed create; want 0 and 0", chats, members)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatUnknownID(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
if _, err := f.chats.GetForMember(f.ctx, ident.New(), ident.New()); !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("GetForMember err = %v, want ErrNotFound", err)
|
||||
}
|
||||
if ok, err := f.chats.IsMember(f.ctx, ident.New(), ident.New()); err != nil || ok {
|
||||
t.Fatalf("IsMember on unknown chat = %v, %v; want false, nil", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListByMemberFiltersOrdersAndPages(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice, bob := f.mustUser(t), f.mustUser(t)
|
||||
var mine []chat.Chat
|
||||
for range 5 {
|
||||
c, err := chat.NewChat(ident.New(), "title")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mine = append(mine, c)
|
||||
// A chat without alice must never show up in her listing.
|
||||
f.mustChat(t, bob)
|
||||
}
|
||||
// Insert the oldest chat last to prove the store sorts, not appends.
|
||||
for _, c := range append(mine[1:], mine[0]) {
|
||||
if err := f.chats.Create(f.ctx, c, []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
page, err := f.chats.ListByMember(f.ctx, alice, nil, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page) != 3 || page[0].ID != mine[0].ID || page[2].ID != mine[2].ID {
|
||||
t.Fatalf("first page mismatch: %v", page)
|
||||
}
|
||||
if len(page[0].MemberIDs) != 2 || page[0].MemberIDs[0] != alice {
|
||||
t.Fatalf("listing must carry members in id order: %+v", page[0])
|
||||
}
|
||||
last := page[2].ID
|
||||
rest, err := f.chats.ListByMember(f.ctx, alice, &last, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rest) != 2 || rest[0].ID != mine[3].ID || rest[1].ID != mine[4].ID {
|
||||
t.Fatalf("second page mismatch: %v", rest)
|
||||
}
|
||||
none, err := f.chats.ListByMember(f.ctx, ident.New(), nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if none == nil || len(none) != 0 {
|
||||
t.Fatalf("unknown member must get an empty non-nil slice, got %#v", none)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListByChatUnknownChatIsEmpty(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
got, err := f.messages.ListByChat(f.ctx, ident.New(), nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got == nil || len(got) != 0 {
|
||||
t.Fatalf("want empty non-nil slice, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendOutOfOrderIsListedByID(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
first, second, third := f.newMessage(t, c.ID, alice), f.newMessage(t, c.ID, alice), f.newMessage(t, c.ID, alice)
|
||||
for _, m := range []chat.Message{third, first, second} {
|
||||
if err := f.appendErr(m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, err := f.messages.ListByChat(f.ctx, c.ID, nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPagingWalksWholeHistoryWithoutGapsOrDuplicates(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
const total = 250
|
||||
var expected []uuid.UUID
|
||||
for range total {
|
||||
m := f.newMessage(t, c.ID, alice)
|
||||
expected = append(expected, m.ID)
|
||||
if err := f.appendErr(m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Another chat's history must not leak into this one.
|
||||
other := f.mustChat(t, alice)
|
||||
if err := f.appendErr(f.newMessage(t, other.ID, alice)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, limit := range []int{1, 7, 100} {
|
||||
var seen []uuid.UUID
|
||||
var after *uuid.UUID
|
||||
for {
|
||||
page, err := f.messages.ListByChat(f.ctx, c.ID, after, limit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
}
|
||||
if len(page) > limit {
|
||||
t.Fatalf("limit %d: page has %d items", limit, len(page))
|
||||
}
|
||||
for _, m := range page {
|
||||
seen = append(seen, m.ID)
|
||||
}
|
||||
last := page[len(page)-1].ID
|
||||
after = &last
|
||||
}
|
||||
if len(seen) != total {
|
||||
t.Fatalf("limit %d: walked %d messages, want %d", limit, len(seen), total)
|
||||
}
|
||||
for i := range seen {
|
||||
if seen[i] != expected[i] {
|
||||
t.Fatalf("limit %d: position %d has %s, want %s", limit, i, seen[i], expected[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAfterUnknownIDStartsAtNextGreater(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
a := f.newMessage(t, c.ID, alice)
|
||||
gap := ident.New() // never stored, but sorts between a and b
|
||||
b := f.newMessage(t, c.ID, alice)
|
||||
for _, m := range []chat.Message{a, b} {
|
||||
if err := f.appendErr(m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, err := f.messages.ListByChat(f.ctx, c.ID, &gap, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].ID != b.ID {
|
||||
t.Fatalf("want only b after the gap id, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentAppendsKeepEveryMessage(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
alice := f.mustUser(t)
|
||||
c := f.mustChat(t, alice)
|
||||
const clients, perClient = 10, 10
|
||||
var wg sync.WaitGroup
|
||||
for range clients {
|
||||
wg.Go(func() {
|
||||
for range perClient {
|
||||
if err := f.appendErr(f.newMessage(t, c.ID, alice)); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
got, err := f.messages.ListByChat(f.ctx, c.ID, nil, clients*perClient+1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != clients*perClient {
|
||||
t.Fatalf("stored %d messages, want %d", len(got), clients*perClient)
|
||||
}
|
||||
for i := 1; i < len(got); i++ {
|
||||
if bytes.Compare(got[i-1].ID[:], got[i].ID[:]) >= 0 {
|
||||
t.Fatalf("history out of order at %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user