189 lines
5.1 KiB
Go
189 lines
5.1 KiB
Go
// 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]) })
|
|
}
|