Files
mtusi2026lab2/internal/storage/memory/store.go
T
2026-10-01 12:59:06 +03:00

145 lines
2.8 KiB
Go

package memory
import (
"cmp"
"slices"
"sync"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
)
type Clock interface {
Now() time.Time
}
type IDGenerator interface {
NewID() uuid.UUID
}
type systemClock struct{}
func (systemClock) Now() time.Time {
return time.Now().UTC()
}
type randomIDGenerator struct{}
func (randomIDGenerator) NewID() uuid.UUID {
return uuid.New()
}
type options struct {
clock Clock
ids IDGenerator
}
type Option func(*options)
func WithClock(clock Clock) Option {
return func(o *options) {
if clock != nil {
o.clock = clock
}
}
}
func WithIDGenerator(ids IDGenerator) Option {
return func(o *options) {
if ids != nil {
o.ids = ids
}
}
}
type Store struct {
clock Clock
ids IDGenerator
mu sync.RWMutex
usersByID map[uuid.UUID]domain.User
usersByUsername map[string]uuid.UUID
chatsByID map[uuid.UUID]domain.Chat
chatsOrdered []domain.Chat
messagesByChat map[uuid.UUID][]domain.Message
users *UserRepository
chats *ChatRepository
messages *MessageRepository
}
func NewStore(opts ...Option) *Store {
cfg := options{clock: systemClock{}, ids: randomIDGenerator{}}
for _, opt := range opts {
opt(&cfg)
}
store := &Store{
clock: cfg.clock,
ids: cfg.ids,
usersByID: make(map[uuid.UUID]domain.User),
usersByUsername: make(map[string]uuid.UUID),
chatsByID: make(map[uuid.UUID]domain.Chat),
messagesByChat: make(map[uuid.UUID][]domain.Message),
}
store.users = &UserRepository{store: store}
store.chats = &ChatRepository{store: store}
store.messages = &MessageRepository{store: store}
return store
}
func (s *Store) Users() *UserRepository { return s.users }
func (s *Store) Chats() *ChatRepository { return s.chats }
func (s *Store) Messages() *MessageRepository { return s.messages }
func compareKeyset(aCreatedAt time.Time, aID uuid.UUID, bCreatedAt time.Time, bID uuid.UUID) int {
if c := aCreatedAt.Compare(bCreatedAt); c != 0 {
return c
}
return cmp.Compare(aID.String(), bID.String())
}
func paginate[T any](
items []T,
scope uuid.UUID,
key func(T) (time.Time, uuid.UUID),
after *domain.Cursor,
limit int,
) domain.Page[T] {
start := 0
if after != nil {
start, _ = slices.BinarySearchFunc(items, *after, func(item T, target domain.Cursor) int {
createdAt, id := key(item)
if compareKeyset(createdAt, id, target.CreatedAt, target.ID) > 0 {
return 1
}
return -1
})
}
rest := items[start:]
page := domain.Page[T]{Items: make([]T, 0, min(len(rest), limit))}
if len(rest) <= limit {
page.Items = append(page.Items, rest...)
return page
}
page.Items = append(page.Items, rest[:limit]...)
createdAt, id := key(page.Items[limit-1])
page.Next = &domain.Cursor{Scope: scope, CreatedAt: createdAt, ID: id}
return page
}