Перенести чаты и сообщения в PostgreSQL
This commit is contained in:
+1
-1
@@ -33,7 +33,7 @@ type Deps struct {
|
||||
|
||||
func New(d Deps) *App {
|
||||
users := user.NewService(userstore.NewUsers(d.DB))
|
||||
chats := chat.NewService(chatstore.NewInMemChats(), chatstore.NewInMemMessages(), users)
|
||||
chats := chat.NewService(chatstore.NewChats(d.DB), chatstore.NewMessages(d.DB), users)
|
||||
|
||||
engine := httpx.NewEngine(d.Log, d.MaxBodyBytes)
|
||||
probes := health.New()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Package chat is the chats module. Entities mirror future table rows and
|
||||
// Package chat is the chats module. Entities mirror table rows and
|
||||
// carry no behaviour; membership is a query rather than a field, and
|
||||
// ChatWithMembers is the projection the API renders. Both entities derive
|
||||
// CreatedAt from their UUIDv7 id, so the history order (created_at, id) is
|
||||
@@ -6,7 +6,9 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -48,7 +50,8 @@ func NewChat(id uuid.UUID, title string) (Chat, error) {
|
||||
}
|
||||
|
||||
// ValidateMembers checks the member list of a new chat and returns its own
|
||||
// copy in the original order.
|
||||
// copy ordered by id: members are a set, and this is the one order in which
|
||||
// every read returns them.
|
||||
func ValidateMembers(memberIDs []uuid.UUID, creator uuid.UUID) ([]uuid.UUID, error) {
|
||||
if len(memberIDs) == 0 {
|
||||
return nil, apperr.Invalid("member_ids must not be empty")
|
||||
@@ -69,5 +72,7 @@ func ValidateMembers(memberIDs []uuid.UUID, creator uuid.UUID) ([]uuid.UUID, err
|
||||
if _, ok := seen[creator]; !ok {
|
||||
return nil, apperr.Invalid("member_ids must include the creator")
|
||||
}
|
||||
return append([]uuid.UUID(nil), memberIDs...), nil
|
||||
members := slices.Clone(memberIDs)
|
||||
slices.SortFunc(members, func(a, b uuid.UUID) int { return bytes.Compare(a[:], b[:]) })
|
||||
return members, nil
|
||||
}
|
||||
|
||||
@@ -34,18 +34,20 @@ func TestNewChatValidatesTitle(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateMembersCopiesAndKeepsOrder(t *testing.T) {
|
||||
// Members come back in one canonical order (by id) whatever order the client
|
||||
// sent, so the created chat and every later read of it agree.
|
||||
func TestValidateMembersCopiesInCanonicalOrder(t *testing.T) {
|
||||
alice, bob := ident.New(), ident.New()
|
||||
input := []uuid.UUID{bob, alice}
|
||||
members, err := chat.ValidateMembers(input, alice)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateMembers error: %v", err)
|
||||
}
|
||||
if len(members) != 2 || members[0] != bob || members[1] != alice {
|
||||
t.Fatalf("order must be preserved, got %v", members)
|
||||
if len(members) != 2 || members[0] != alice || members[1] != bob {
|
||||
t.Fatalf("members must be ordered by id, got %v", members)
|
||||
}
|
||||
input[0] = ident.New()
|
||||
if members[0] != bob {
|
||||
input[1] = ident.New()
|
||||
if members[0] != alice {
|
||||
t.Fatal("result must not alias the input slice")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ import (
|
||||
|
||||
// ChatRepository stores chats and their membership. Membership is answered
|
||||
// by queries; the projection with members is assembled by the store in one
|
||||
// query, never by loading a member list into the entity.
|
||||
// query, never by loading a member list into the entity. Members are always
|
||||
// returned ordered by id.
|
||||
type ChatRepository interface {
|
||||
// Create stores the chat row and its members atomically.
|
||||
Create(ctx context.Context, chat Chat, memberIDs []uuid.UUID) error
|
||||
|
||||
@@ -3,6 +3,8 @@ package chat_test
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -13,50 +15,70 @@ import (
|
||||
"messenger/internal/chat/store"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/testenv"
|
||||
"messenger/internal/user"
|
||||
userstore "messenger/internal/user/store"
|
||||
)
|
||||
|
||||
// knownUsers doubles chat.UserLookup and counts calls to prove that member
|
||||
// checks are batched.
|
||||
type knownUsers struct {
|
||||
ids map[uuid.UUID]struct{}
|
||||
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)
|
||||
}
|
||||
|
||||
// countingUsers passes through to the real users service and counts the
|
||||
// lookups, which proves that member checks are batched.
|
||||
type countingUsers struct {
|
||||
*user.Service
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (k *knownUsers) ExistingIDs(_ context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
|
||||
k.calls.Add(1)
|
||||
out := make([]uuid.UUID, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if _, ok := k.ids[id]; ok {
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
func (c *countingUsers) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
|
||||
c.calls.Add(1)
|
||||
return c.Service.ExistingIDs(ctx, ids)
|
||||
}
|
||||
|
||||
type fixture struct {
|
||||
svc *chat.Service
|
||||
users *knownUsers
|
||||
users *countingUsers
|
||||
alice, bob uuid.UUID
|
||||
eve uuid.UUID
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func newFixture() fixture {
|
||||
alice, bob, eve := ident.New(), ident.New(), ident.New()
|
||||
users := &knownUsers{ids: map[uuid.UUID]struct{}{alice: {}, bob: {}, eve: {}}}
|
||||
func newFixture(t *testing.T) fixture {
|
||||
t.Helper()
|
||||
db.Reset(t)
|
||||
ctx := context.Background()
|
||||
users := &countingUsers{Service: user.NewService(userstore.NewUsers(db.Pool))}
|
||||
register := func(name string) uuid.UUID {
|
||||
u, err := users.Register(ctx, name, name, "correct-horse-battery")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return u.ID
|
||||
}
|
||||
return fixture{
|
||||
svc: chat.NewService(store.NewInMemChats(), store.NewInMemMessages(), users),
|
||||
svc: chat.NewService(store.NewChats(db.Pool), store.NewMessages(db.Pool), users),
|
||||
users: users,
|
||||
alice: alice,
|
||||
bob: bob,
|
||||
eve: eve,
|
||||
ctx: context.Background(),
|
||||
alice: register("alice"),
|
||||
bob: register("bob"),
|
||||
eve: register("eve"),
|
||||
ctx: ctx,
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatChecksMembersInOneCall(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "Проект", []uuid.UUID{f.alice, f.bob, f.eve})
|
||||
f := newFixture(t)
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "Проект", []uuid.UUID{f.eve, f.alice, f.bob})
|
||||
if err != nil {
|
||||
t.Fatalf("Create error: %v", err)
|
||||
}
|
||||
@@ -67,13 +89,16 @@ func TestCreateChatChecksMembersInOneCall(t *testing.T) {
|
||||
t.Fatalf("member existence must be checked with one batch call, got %d", got)
|
||||
}
|
||||
got, err := f.svc.Get(f.ctx, f.bob, c.ID)
|
||||
if err != nil || got.ID != c.ID || len(got.MemberIDs) != 3 {
|
||||
t.Fatalf("member Get = %+v, %v", got, err)
|
||||
if err != nil {
|
||||
t.Fatalf("member Get error: %v", err)
|
||||
}
|
||||
if fmt.Sprint(got.MemberIDs) != fmt.Sprint(c.MemberIDs) || !got.CreatedAt.Equal(c.CreatedAt) || got.Title != c.Title {
|
||||
t.Fatalf("Get = %+v, want what Create returned %+v", got, c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChatRejectsUnknownMember(t *testing.T) {
|
||||
f := newFixture()
|
||||
f := newFixture(t)
|
||||
_, err := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, ident.New()})
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Fatalf("kind = %v, want KindInvalid (%v)", apperr.KindOf(err), err)
|
||||
@@ -84,7 +109,7 @@ func TestCreateChatRejectsUnknownMember(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCreateChatRejectsInvalidInputBeforeAnyLookup(t *testing.T) {
|
||||
f := newFixture()
|
||||
f := newFixture(t)
|
||||
cases := map[string]struct {
|
||||
title string
|
||||
members []uuid.UUID
|
||||
@@ -105,8 +130,11 @@ func TestCreateChatRejectsInvalidInputBeforeAnyLookup(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGetHidesForeignAndUnknownChatsAlike(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, _ := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
f := newFixture(t)
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, foreign := f.svc.Get(f.ctx, f.eve, c.ID)
|
||||
_, unknown := f.svc.Get(f.ctx, f.eve, ident.New())
|
||||
if !errors.Is(foreign, chat.ErrNotFound) || !errors.Is(unknown, chat.ErrNotFound) {
|
||||
@@ -118,9 +146,9 @@ func TestGetHidesForeignAndUnknownChatsAlike(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestListPagesOnlyOwnChats(t *testing.T) {
|
||||
f := newFixture()
|
||||
f := newFixture(t)
|
||||
var mine []uuid.UUID
|
||||
for i := 0; i < 3; i++ {
|
||||
for range 3 {
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -154,9 +182,12 @@ func TestListPagesOnlyOwnChats(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSendChecksAccessBeforeValidation(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, _ := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
_, err := f.svc.Send(f.ctx, f.eve, c.ID, " ")
|
||||
f := newFixture(t)
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = f.svc.Send(f.ctx, f.eve, c.ID, " ")
|
||||
if !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("outsider with blank text: err = %v, want ErrNotFound", err)
|
||||
}
|
||||
@@ -171,8 +202,11 @@ func TestSendChecksAccessBeforeValidation(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestHistoryPagesAndHidesForeignChat(t *testing.T) {
|
||||
f := newFixture()
|
||||
c, _ := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
f := newFixture(t)
|
||||
c, err := f.svc.Create(f.ctx, f.alice, "t", []uuid.UUID{f.alice, f.bob})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, _ := f.svc.Send(f.ctx, f.alice, c.ID, "1")
|
||||
second, _ := f.svc.Send(f.ctx, f.bob, c.ID, "2")
|
||||
|
||||
@@ -180,14 +214,14 @@ func TestHistoryPagesAndHidesForeignChat(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 1 || page.Items[0].ID != first.ID || page.Next == nil || *page.Next != first.ID {
|
||||
if len(page.Items) != 1 || 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].ID != second.ID || rest.Next != nil {
|
||||
if len(rest.Items) != 1 || 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) {
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
// Package store holds the repository implementations of the chats module.
|
||||
// inmem.go is the in-process one: state lives only in this process and
|
||||
// disappears with it by design of the lab.
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
)
|
||||
|
||||
// InMemChats keeps chat rows, a per-chat member list and set, and a
|
||||
// per-member index of chat ids ordered by (created_at, id), which for UUIDv7
|
||||
// ids is plain id order. One read-write mutex guards all four maps.
|
||||
type InMemChats struct {
|
||||
mu sync.RWMutex
|
||||
rows map[uuid.UUID]chat.Chat
|
||||
members map[uuid.UUID][]uuid.UUID
|
||||
memberOf map[uuid.UUID]map[uuid.UUID]struct{}
|
||||
byMember map[uuid.UUID][]uuid.UUID
|
||||
}
|
||||
|
||||
var _ chat.ChatRepository = (*InMemChats)(nil)
|
||||
|
||||
func NewInMemChats() *InMemChats {
|
||||
return &InMemChats{
|
||||
rows: make(map[uuid.UUID]chat.Chat),
|
||||
members: make(map[uuid.UUID][]uuid.UUID),
|
||||
memberOf: make(map[uuid.UUID]map[uuid.UUID]struct{}),
|
||||
byMember: make(map[uuid.UUID][]uuid.UUID),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *InMemChats) Create(_ context.Context, c chat.Chat, memberIDs []uuid.UUID) error {
|
||||
members := append([]uuid.UUID(nil), memberIDs...)
|
||||
set := make(map[uuid.UUID]struct{}, len(members))
|
||||
for _, m := range members {
|
||||
set[m] = struct{}{}
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.rows[c.ID] = c
|
||||
r.members[c.ID] = members
|
||||
r.memberOf[c.ID] = set
|
||||
for _, m := range members {
|
||||
r.byMember[m] = insertSorted(r.byMember[m], c.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *InMemChats) GetForMember(_ context.Context, chatID, userID uuid.UUID) (chat.ChatWithMembers, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if _, ok := r.memberOf[chatID][userID]; !ok {
|
||||
return chat.ChatWithMembers{}, chat.ErrNotFound
|
||||
}
|
||||
return r.projection(chatID), nil
|
||||
}
|
||||
|
||||
func (r *InMemChats) IsMember(_ context.Context, chatID, userID uuid.UUID) (bool, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
_, ok := r.memberOf[chatID][userID]
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (r *InMemChats) ListByMember(_ context.Context, userID uuid.UUID, after *uuid.UUID, limit int) ([]chat.ChatWithMembers, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
ids := r.byMember[userID]
|
||||
start := firstAfter(ids, after)
|
||||
end := min(start+limit, len(ids))
|
||||
out := make([]chat.ChatWithMembers, 0, end-start)
|
||||
for _, id := range ids[start:end] {
|
||||
out = append(out, r.projection(id))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// projection copies the member list so callers never alias the store.
|
||||
func (r *InMemChats) projection(chatID uuid.UUID) chat.ChatWithMembers {
|
||||
return chat.ChatWithMembers{
|
||||
Chat: r.rows[chatID],
|
||||
MemberIDs: append([]uuid.UUID(nil), r.members[chatID]...),
|
||||
}
|
||||
}
|
||||
|
||||
// InMemMessages keeps one ordered history per chat. The outer lock only
|
||||
// guards the map of histories; each history has its own lock, so writers to
|
||||
// different chats never contend.
|
||||
type InMemMessages struct {
|
||||
mu sync.RWMutex
|
||||
byChat map[uuid.UUID]*history
|
||||
}
|
||||
|
||||
type history struct {
|
||||
mu sync.RWMutex
|
||||
items []chat.Message
|
||||
}
|
||||
|
||||
var _ chat.MessageRepository = (*InMemMessages)(nil)
|
||||
|
||||
func NewInMemMessages() *InMemMessages {
|
||||
return &InMemMessages{byChat: make(map[uuid.UUID]*history)}
|
||||
}
|
||||
|
||||
// Append inserts at the sorted position; ids are monotonic, so the usual
|
||||
// case is an append at the tail.
|
||||
func (r *InMemMessages) Append(_ context.Context, m chat.Message) error {
|
||||
h := r.historyFor(m.ChatID, true)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
n := len(h.items)
|
||||
if n == 0 || less(h.items[n-1].ID, m.ID) {
|
||||
h.items = append(h.items, m)
|
||||
return nil
|
||||
}
|
||||
i := sort.Search(n, func(k int) bool { return !less(h.items[k].ID, m.ID) })
|
||||
h.items = append(h.items, chat.Message{})
|
||||
copy(h.items[i+1:], h.items[i:])
|
||||
h.items[i] = m
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *InMemMessages) ListByChat(_ context.Context, chatID uuid.UUID, after *uuid.UUID, limit int) ([]chat.Message, error) {
|
||||
h := r.historyFor(chatID, false)
|
||||
if h == nil {
|
||||
return []chat.Message{}, nil
|
||||
}
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
start := 0
|
||||
if after != nil {
|
||||
start = sort.Search(len(h.items), func(k int) bool { return less(*after, h.items[k].ID) })
|
||||
}
|
||||
end := min(start+limit, len(h.items))
|
||||
out := make([]chat.Message, end-start)
|
||||
copy(out, h.items[start:end])
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *InMemMessages) historyFor(chatID uuid.UUID, create bool) *history {
|
||||
r.mu.RLock()
|
||||
h := r.byChat[chatID]
|
||||
r.mu.RUnlock()
|
||||
if h != nil || !create {
|
||||
return h
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if h = r.byChat[chatID]; h == nil {
|
||||
h = &history{}
|
||||
r.byChat[chatID] = h
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// less orders ids lexicographically, which for UUIDv7 is creation order.
|
||||
func less(a, b uuid.UUID) bool {
|
||||
return bytes.Compare(a[:], b[:]) < 0
|
||||
}
|
||||
|
||||
func insertSorted(ids []uuid.UUID, id uuid.UUID) []uuid.UUID {
|
||||
n := len(ids)
|
||||
if n == 0 || less(ids[n-1], id) {
|
||||
return append(ids, id)
|
||||
}
|
||||
i := sort.Search(n, func(k int) bool { return !less(ids[k], id) })
|
||||
ids = append(ids, uuid.Nil)
|
||||
copy(ids[i+1:], ids[i:])
|
||||
ids[i] = id
|
||||
return ids
|
||||
}
|
||||
|
||||
// firstAfter returns the index of the first id strictly greater than after,
|
||||
// or len(ids) when there is none; nil after means the start.
|
||||
func firstAfter(ids []uuid.UUID, after *uuid.UUID) int {
|
||||
if after == nil {
|
||||
return 0
|
||||
}
|
||||
return sort.Search(len(ids), func(k int) bool { return less(*after, ids[k]) })
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/chat/store"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
func mustChat(t *testing.T) chat.Chat {
|
||||
t.Helper()
|
||||
c, err := chat.NewChat(ident.New(), "title")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func mustMessage(t *testing.T, chatID uuid.UUID) chat.Message {
|
||||
t.Helper()
|
||||
m, err := chat.NewMessage(ident.New(), chatID, ident.New(), "text")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestChatCreateThenGetForMember(t *testing.T) {
|
||||
repo := store.NewInMemChats()
|
||||
ctx := context.Background()
|
||||
alice, bob := ident.New(), ident.New()
|
||||
c := mustChat(t)
|
||||
if err := repo.Create(ctx, c, []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := repo.GetForMember(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", got)
|
||||
}
|
||||
got.MemberIDs[0] = ident.New()
|
||||
again, _ := repo.GetForMember(ctx, c.ID, alice)
|
||||
if again.MemberIDs[0] != alice {
|
||||
t.Fatal("GetForMember must return a copy of the member list")
|
||||
}
|
||||
if _, err := repo.GetForMember(ctx, c.ID, ident.New()); !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 := repo.IsMember(ctx, c.ID, who)
|
||||
if err != nil || ok != want {
|
||||
t.Fatalf("IsMember(%s) = %v, %v; want %v", who, ok, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatUnknownID(t *testing.T) {
|
||||
repo := store.NewInMemChats()
|
||||
ctx := context.Background()
|
||||
if _, err := repo.GetForMember(ctx, ident.New(), ident.New()); !errors.Is(err, chat.ErrNotFound) {
|
||||
t.Fatalf("GetForMember err = %v, want ErrNotFound", err)
|
||||
}
|
||||
if ok, err := repo.IsMember(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) {
|
||||
repo := store.NewInMemChats()
|
||||
ctx := context.Background()
|
||||
alice, bob := ident.New(), ident.New()
|
||||
var mine []chat.Chat
|
||||
for i := 0; i < 5; i++ {
|
||||
mine = append(mine, mustChat(t))
|
||||
// A chat without alice must never show up in her listing.
|
||||
if err := repo.Create(ctx, mustChat(t), []uuid.UUID{bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Insert the oldest chat last to prove the store sorts, not appends.
|
||||
for _, c := range mine[1:] {
|
||||
if err := repo.Create(ctx, c, []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := repo.Create(ctx, mine[0], []uuid.UUID{alice, bob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
page, err := repo.ListByMember(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 {
|
||||
t.Fatalf("listing must carry members: %+v", page[0])
|
||||
}
|
||||
last := page[2].ID
|
||||
rest, err := repo.ListByMember(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 := repo.ListByMember(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) {
|
||||
got, err := store.NewInMemMessages().ListByChat(context.Background(), 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 TestAppendOutOfOrderIsSortedByID(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
first, second, third := mustMessage(t, chatID), mustMessage(t, chatID), mustMessage(t, chatID)
|
||||
for _, m := range []chat.Message{third, first, second} {
|
||||
if err := repo.Append(ctx, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, err := repo.ListByChat(ctx, chatID, nil, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 3 || got[0].ID != first.ID || got[1].ID != second.ID || got[2].ID != third.ID {
|
||||
t.Fatalf("history must be ordered by id, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPagingWalksWholeHistoryWithoutGapsOrDuplicates(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
const total = 250
|
||||
var expected []uuid.UUID
|
||||
for i := 0; i < total; i++ {
|
||||
m := mustMessage(t, chatID)
|
||||
expected = append(expected, m.ID)
|
||||
if err := repo.Append(ctx, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, limit := range []int{1, 7, 100} {
|
||||
var seen []uuid.UUID
|
||||
var after *uuid.UUID
|
||||
for {
|
||||
page, err := repo.ListByChat(ctx, chatID, 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) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
a := mustMessage(t, chatID)
|
||||
gap := ident.New() // never stored, but sorts between a and b
|
||||
b := mustMessage(t, chatID)
|
||||
_ = repo.Append(ctx, a)
|
||||
_ = repo.Append(ctx, b)
|
||||
got, _ := repo.ListByChat(ctx, chatID, &gap, 10)
|
||||
if len(got) != 1 || got[0].ID != b.ID {
|
||||
t.Fatalf("want only b after the gap id, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListByChatReturnsCopy(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
_ = repo.Append(ctx, mustMessage(t, chatID))
|
||||
page, _ := repo.ListByChat(ctx, chatID, nil, 10)
|
||||
page[0].Text = "mutated"
|
||||
again, _ := repo.ListByChat(ctx, chatID, nil, 10)
|
||||
if again[0].Text != "text" {
|
||||
t.Fatal("ListByChat must not expose internal storage")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentAppendsKeepEveryMessageOrdered(t *testing.T) {
|
||||
repo := store.NewInMemMessages()
|
||||
ctx := context.Background()
|
||||
chatID := ident.New()
|
||||
const clients, perClient = 10, 10
|
||||
var wg sync.WaitGroup
|
||||
for c := 0; c < clients; c++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < perClient; i++ {
|
||||
if err := repo.Append(ctx, mustMessage(t, chatID)); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
got, err := repo.ListByChat(ctx, chatID, 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)
|
||||
}
|
||||
unique := make(map[uuid.UUID]struct{}, len(got))
|
||||
for i, m := range got {
|
||||
unique[m.ID] = struct{}{}
|
||||
if i > 0 && bytes.Compare(got[i-1].ID[:], m.ID[:]) >= 0 {
|
||||
t.Fatalf("history out of order at %d", i)
|
||||
}
|
||||
}
|
||||
if len(unique) != clients*perClient {
|
||||
t.Fatalf("%d unique ids, want %d", len(unique), clients*perClient)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// 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).
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/internal/chat"
|
||||
)
|
||||
|
||||
type Chats struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
var _ chat.ChatRepository = (*Chats)(nil)
|
||||
|
||||
func NewChats(pool *pgxpool.Pool) *Chats {
|
||||
return &Chats{pool: pool}
|
||||
}
|
||||
|
||||
// chatWithMembers selects the projection from a chats row aliased c.
|
||||
const chatWithMembers = `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)`
|
||||
|
||||
func (r *Chats) Create(ctx context.Context, c chat.Chat, memberIDs []uuid.UUID) error {
|
||||
return 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 `+chatWithMembers+`
|
||||
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", 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", 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 `+chatWithMembers+`
|
||||
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", 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", 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
|
||||
}
|
||||
c.CreatedAt = c.CreatedAt.UTC()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type Messages struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
var _ chat.MessageRepository = (*Messages)(nil)
|
||||
|
||||
func NewMessages(pool *pgxpool.Pool) *Messages {
|
||||
return &Messages{pool: pool}
|
||||
}
|
||||
|
||||
func (r *Messages) Append(ctx context.Context, m chat.Message) error {
|
||||
_, err := r.pool.Exec(ctx,
|
||||
`INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||
m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListByChat is the history query; scripts/explain-history.sql runs the same
|
||||
// statement for the EXPLAIN evidence.
|
||||
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)
|
||||
ORDER BY id
|
||||
LIMIT $3`,
|
||||
chatID, after, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select messages: %w", 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)
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
return m, err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read messages: %w", err)
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"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
|
||||
}
|
||||
|
||||
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.messages.Append(f.ctx, 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 || got[0] != first || got[1] != second || 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.messages.Append(f.ctx, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Another chat's history must not leak into this one.
|
||||
other := f.mustChat(t, alice)
|
||||
if err := f.messages.Append(f.ctx, 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.messages.Append(f.ctx, 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.messages.Append(f.ctx, 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