Перенести решение лабораторной 1 как основу для лабораторной 2
This commit is contained in:
@@ -0,0 +1,188 @@
|
||||
// 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]) })
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user