forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
package memory
|
||||
|
||||
import "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
|
||||
// Conservative logical charges, not measurements of Go allocations or RSS.
|
||||
// The budget includes record metadata and index entries; HTTP buffers are separate.
|
||||
const (
|
||||
userRecordOverheadBytes = 256
|
||||
chatRecordOverheadBytes = 256
|
||||
messageRecordOverheadBytes = 256
|
||||
chatMemberIndexBytes = 128
|
||||
usernameIndexCopies = 2
|
||||
)
|
||||
|
||||
// userCost calculates the logical storage charge for a user and its index entries.
|
||||
func userCost(user dto.UserDTO) int {
|
||||
return userRecordOverheadBytes + len(user.Username)*usernameIndexCopies + len(user.DisplayName)
|
||||
}
|
||||
|
||||
// chatCost calculates the logical storage charge for a chat and its membership index.
|
||||
func chatCost(chat dto.ChatDTO) int {
|
||||
return chatRecordOverheadBytes + len(chat.Title) + chatMemberIndexBytes*len(chat.MemberIDs)
|
||||
}
|
||||
|
||||
// messageCost calculates the logical storage charge for a message.
|
||||
func messageCost(message dto.MessageDTO) int {
|
||||
return messageRecordOverheadBytes + len(message.Text)
|
||||
}
|
||||
|
||||
// reserve checks and charges capacity while the caller holds the write lock.
|
||||
// Callers must not perform a fallible operation after reserving this budget.
|
||||
func (s *Store) reserve(bytes int) bool {
|
||||
if bytes > s.limits.MaxStateBytes-s.usedBytes {
|
||||
return false
|
||||
}
|
||||
s.usedBytes += bytes
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"sort"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// copyChat copies the membership slice to keep stored chat state private.
|
||||
func copyChat(c dto.ChatDTO) dto.ChatDTO {
|
||||
c.MemberIDs = slices.Clone(c.MemberIDs)
|
||||
return c
|
||||
}
|
||||
|
||||
// CreateChat stores the chat and its member index atomically.
|
||||
func (s *Store) CreateChat(_ context.Context, c dto.ChatDTO) (dto.ChatDTO, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, id := range c.MemberIDs {
|
||||
if _, ok := s.users[id]; !ok {
|
||||
return dto.ChatDTO{}, store.ErrNotFound
|
||||
}
|
||||
}
|
||||
if len(s.chats) >= s.limits.MaxChats || !s.reserve(chatCost(c)) {
|
||||
return dto.ChatDTO{}, store.ErrCapacity
|
||||
}
|
||||
c.CreatedAt = s.timestamp()
|
||||
c = copyChat(c)
|
||||
s.chats[c.ID] = c
|
||||
for _, id := range c.MemberIDs {
|
||||
s.userChats[id] = append(s.userChats[id], c)
|
||||
}
|
||||
return copyChat(c), nil
|
||||
}
|
||||
|
||||
// Chat retrieves a defensive copy. Authorization belongs to the service.
|
||||
func (s *Store) Chat(_ context.Context, id uuid.UUID) (dto.ChatDTO, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
c, ok := s.chats[id]
|
||||
if !ok {
|
||||
return c, store.ErrNotFound
|
||||
}
|
||||
return copyChat(c), nil
|
||||
}
|
||||
|
||||
// Chats uses the per-member index and binary search, without scanning other chats.
|
||||
func (s *Store) Chats(_ context.Context, user uuid.UUID, p dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
all := s.userChats[user]
|
||||
i := sort.Search(len(all), func(i int) bool {
|
||||
return after(all[i].CreatedAt, all[i].ID, p)
|
||||
})
|
||||
end := min(len(all), i+limit)
|
||||
out := make([]dto.ChatDTO, 0, end-i)
|
||||
for _, c := range all[i:end] {
|
||||
out = append(out, copyChat(c))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// TestStore_CreateChat_RejectsWithoutMutation checks atomic rejection of invalid or excess chats.
|
||||
func TestStore_CreateChat_RejectsWithoutMutation(t *testing.T) {
|
||||
t.Run("Negative: chat capacity reached", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := config.Default().Memory
|
||||
cfg.MaxChats = 1
|
||||
repo := newTestStore(t, cfg)
|
||||
member := seedUser(t, repo, "alice")
|
||||
original := seedChat(t, repo, member.ID)
|
||||
input := dto.ChatDTO{ID: uuid.New(), Title: "Rejected", MemberIDs: []uuid.UUID{member.ID}}
|
||||
wantErr := store.ErrCapacity
|
||||
|
||||
previousBytes := repo.usedBytes
|
||||
|
||||
// Act.
|
||||
got, err := repo.CreateChat(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, wantErr) || got.ID != uuid.Nil {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, wantErr)
|
||||
}
|
||||
items, readErr := repo.Chats(t.Context(), member.ID, dto.PositionDTO{}, 10)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !reflect.DeepEqual(items, []dto.ChatDTO{original}) || len(repo.chats) != 1 || repo.usedBytes != previousBytes {
|
||||
t.Fatalf("rejected chat changed stored state: %v", items)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: member does not exist", func(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := config.Default().Memory
|
||||
cfg.MaxChats = 1
|
||||
repo := newTestStore(t, cfg)
|
||||
member := seedUser(t, repo, "alice")
|
||||
original := seedChat(t, repo, member.ID)
|
||||
input := dto.ChatDTO{ID: uuid.New(), Title: "Rejected", MemberIDs: []uuid.UUID{member.ID}}
|
||||
wantErr := store.ErrNotFound
|
||||
input.MemberIDs = append(input.MemberIDs, uuid.New())
|
||||
|
||||
previousBytes := repo.usedBytes
|
||||
|
||||
// Act.
|
||||
got, err := repo.CreateChat(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, wantErr) || got.ID != uuid.Nil {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, wantErr)
|
||||
}
|
||||
items, readErr := repo.Chats(t.Context(), member.ID, dto.PositionDTO{}, 10)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !reflect.DeepEqual(items, []dto.ChatDTO{original}) || len(repo.chats) != 1 || repo.usedBytes != previousBytes {
|
||||
t.Fatalf("rejected chat changed stored state: %v", items)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestStore_CreateChat_DefensiveCopy ensures callers cannot mutate membership through write boundaries.
|
||||
func TestStore_CreateChat_DefensiveCopy(t *testing.T) {
|
||||
t.Run("Positive: isolated input membership", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
member := seedUser(t, repo, "alice")
|
||||
input := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{member.ID}}
|
||||
_, err := repo.CreateChat(t.Context(), input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Act: a caller modifies the slice it owns after CreateChat returns.
|
||||
|
||||
input.MemberIDs[0] = uuid.New()
|
||||
|
||||
// Assert.
|
||||
stored, err := repo.Chat(t.Context(), input.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(stored.MemberIDs) != 1 || stored.MemberIDs[0] != member.ID {
|
||||
t.Fatalf("caller mutated stored membership: %+v", stored)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Positive: isolated result membership", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
member := seedUser(t, repo, "alice")
|
||||
input := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{member.ID}}
|
||||
created, err := repo.CreateChat(t.Context(), input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Act: a caller modifies the slice it owns after CreateChat returns.
|
||||
|
||||
created.MemberIDs[0] = uuid.New()
|
||||
|
||||
// Assert.
|
||||
stored, err := repo.Chat(t.Context(), input.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(stored.MemberIDs) != 1 || stored.MemberIDs[0] != member.ID {
|
||||
t.Fatalf("caller mutated stored membership: %+v", stored)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestStore_Chat_DefensiveCopy ensures a fetched detail cannot alter future reads.
|
||||
func TestStore_Chat_DefensiveCopy(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
member := seedUser(t, repo, "alice")
|
||||
original := seedChat(t, repo, member.ID)
|
||||
fetched, err := repo.Chat(t.Context(), original.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Act.
|
||||
fetched.MemberIDs[0] = uuid.New()
|
||||
|
||||
// Assert.
|
||||
stored, err := repo.Chat(t.Context(), original.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(stored, original) {
|
||||
t.Fatalf("read changed stored chat: %+v", stored)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// CreateMessage assigns ordering and publishes one complete message atomically.
|
||||
func (s *Store) CreateMessage(_ context.Context, m dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.chats[m.ChatID]; !ok {
|
||||
return dto.MessageDTO{}, store.ErrNotFound
|
||||
}
|
||||
if s.messageCount >= s.limits.MaxMessages || !s.reserve(messageCost(m)) {
|
||||
return dto.MessageDTO{}, store.ErrCapacity
|
||||
}
|
||||
m.CreatedAt = s.timestamp()
|
||||
s.messages[m.ChatID] = append(s.messages[m.ChatID], m)
|
||||
s.messageCount++
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Messages performs keyset pagination over an append-only ordered history.
|
||||
func (s *Store) Messages(_ context.Context, chat uuid.UUID, p dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
all := s.messages[chat]
|
||||
i := sort.Search(len(all), func(i int) bool {
|
||||
return after(all[i].CreatedAt, all[i].ID, p)
|
||||
})
|
||||
end := min(len(all), i+limit)
|
||||
out := make([]dto.MessageDTO, end-i)
|
||||
copy(out, all[i:end])
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// TestStore_CreateMessage_ByteCapacity preserves acknowledged history and accounting on rejection.
|
||||
func TestStore_CreateMessage_ByteCapacity(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := config.Default().Memory
|
||||
cfg.MaxStateBytes = 2048
|
||||
repo := newTestStore(t, cfg)
|
||||
member := seedUser(t, repo, "alice")
|
||||
chat := seedChat(t, repo, member.ID)
|
||||
original := seedMessage(t, repo, chat, "kept")
|
||||
input := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: member.ID, Text: strings.Repeat("x", 2000)}
|
||||
previousBytes := repo.usedBytes
|
||||
|
||||
// Act.
|
||||
got, err := repo.CreateMessage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, store.ErrCapacity) || !reflect.DeepEqual(got, dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
items, readErr := repo.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 10)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !reflect.DeepEqual(items, []dto.MessageDTO{original}) || repo.messageCount != 1 || repo.usedBytes != previousBytes {
|
||||
t.Fatalf("overflow changed history or accounting: %v", items)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStore_CreateMessage_ClockRollback preserves chronological append order after a clock rollback.
|
||||
func TestStore_CreateMessage_ClockRollback(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
member := seedUser(t, repo, "alice")
|
||||
chat := seedChat(t, repo, member.ID)
|
||||
repo.lastTime = time.Now().UTC().Add(time.Hour)
|
||||
first := seedMessage(t, repo, chat, "first")
|
||||
input := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: member.ID, Text: "second"}
|
||||
|
||||
// Act.
|
||||
second, err := repo.CreateMessage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !second.CreatedAt.After(first.CreatedAt) {
|
||||
t.Fatalf("second=%s must follow first=%s", second.CreatedAt, first.CreatedAt)
|
||||
}
|
||||
page, readErr := repo.Messages(t.Context(), chat.ID, dto.PositionDTO{CreatedAt: first.CreatedAt, ID: first.ID}, 10)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !reflect.DeepEqual(page, []dto.MessageDTO{second}) {
|
||||
t.Fatalf("continuation lost the later message: %v", page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
// timestamp is called under the write lock, keeping append order during clock rollback.
|
||||
func (s *Store) timestamp() time.Time {
|
||||
now := time.Now().UTC()
|
||||
if !now.After(s.lastTime) {
|
||||
now = s.lastTime.Add(time.Nanosecond)
|
||||
}
|
||||
s.lastTime = now
|
||||
return now
|
||||
}
|
||||
|
||||
// after compares a record with a keyset pagination position.
|
||||
func after(t time.Time, id uuid.UUID, p dto.PositionDTO) bool {
|
||||
return t.After(p.CreatedAt) || (t.Equal(p.CreatedAt) && bytes.Compare(id[:], p.ID[:]) > 0)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Package memory implements synchronized storage within one bounded process.
|
||||
package memory
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// Store owns all mutable state and its indexes under one lock.
|
||||
// Records are immutable once published; membership slices are copied on both
|
||||
// write and read boundaries. Its zero value is not usable; construct it with New.
|
||||
type Store struct {
|
||||
mu sync.RWMutex
|
||||
limits config.Memory
|
||||
users map[uuid.UUID]dto.UserDTO
|
||||
usernames map[string]uuid.UUID
|
||||
chats map[uuid.UUID]dto.ChatDTO
|
||||
userChats map[uuid.UUID][]dto.ChatDTO
|
||||
messages map[uuid.UUID][]dto.MessageDTO
|
||||
messageCount int
|
||||
usedBytes int
|
||||
lastTime time.Time
|
||||
}
|
||||
|
||||
var _ store.Interface = (*Store)(nil)
|
||||
|
||||
// New validates and copies capacity settings, then initializes an empty store.
|
||||
// It creates no files, goroutines or external connections.
|
||||
func New(cfg *config.Memory) (*Store, error) {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{
|
||||
limits: *cfg,
|
||||
users: make(map[uuid.UUID]dto.UserDTO),
|
||||
usernames: make(map[string]uuid.UUID),
|
||||
chats: make(map[uuid.UUID]dto.ChatDTO),
|
||||
userChats: make(map[uuid.UUID][]dto.ChatDTO),
|
||||
messages: make(map[uuid.UUID][]dto.MessageDTO),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
// TestStore_New rejects missing capacity settings.
|
||||
func TestStore_New(t *testing.T) {
|
||||
// Arrange.
|
||||
var cfg *config.Memory
|
||||
|
||||
// Act.
|
||||
repo, err := New(cfg)
|
||||
|
||||
// Assert.
|
||||
if err == nil || repo != nil {
|
||||
t.Fatalf("missing configuration accepted: %v, %v", repo, err)
|
||||
}
|
||||
}
|
||||
|
||||
// newTestStore creates independent storage for one scenario.
|
||||
func newTestStore(t *testing.T, cfg *config.Memory) *Store {
|
||||
t.Helper()
|
||||
repo, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return repo
|
||||
}
|
||||
|
||||
// seedUser creates a fixture user and checks preparation errors.
|
||||
func seedUser(t *testing.T, repo *Store, username string) dto.UserDTO {
|
||||
t.Helper()
|
||||
user, err := repo.CreateUser(t.Context(), dto.UserDTO{ID: uuid.New(), Username: username})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
// seedChat creates a fixture chat for an existing member.
|
||||
func seedChat(t *testing.T, repo *Store, member uuid.UUID) dto.ChatDTO {
|
||||
t.Helper()
|
||||
chat, err := repo.CreateChat(t.Context(), dto.ChatDTO{ID: uuid.New(), Title: "Fixture", MemberIDs: []uuid.UUID{member}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return chat
|
||||
}
|
||||
|
||||
// seedMessage creates an acknowledged fixture message.
|
||||
func seedMessage(t *testing.T, repo *Store, chat dto.ChatDTO, text string) dto.MessageDTO {
|
||||
t.Helper()
|
||||
message, err := repo.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: chat.MemberIDs[0], Text: text})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return message
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// CreateUser atomically enforces uniqueness and resource limits.
|
||||
func (s *Store) CreateUser(_ context.Context, u dto.UserDTO) (dto.UserDTO, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.usernames[u.Username]; ok {
|
||||
return dto.UserDTO{}, store.ErrConflict
|
||||
}
|
||||
if len(s.users) >= s.limits.MaxUsers || !s.reserve(userCost(u)) {
|
||||
return dto.UserDTO{}, store.ErrCapacity
|
||||
}
|
||||
u.CreatedAt = s.timestamp()
|
||||
s.users[u.ID] = u
|
||||
s.usernames[u.Username] = u.ID
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// User retrieves an immutable user.
|
||||
func (s *Store) User(_ context.Context, id uuid.UUID) (dto.UserDTO, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
u, ok := s.users[id]
|
||||
if !ok {
|
||||
return u, store.ErrNotFound
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// UsersExist checks the complete set under one read lock without loading user records.
|
||||
// Empty sets return true, and duplicate IDs do not affect the result.
|
||||
func (s *Store) UsersExist(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
for _, id := range ids {
|
||||
if _, exists := s.users[id]; !exists {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// TestStore_UsersExist checks all-members semantics on an independent store per case.
|
||||
func TestStore_UsersExist(t *testing.T) {
|
||||
t.Run("Positive: existing user", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
user := seedUser(t, repo, "alice")
|
||||
ids := []uuid.UUID{user.ID}
|
||||
want := true
|
||||
|
||||
// Act.
|
||||
got, err := repo.UsersExist(t.Context(), ids)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Positive: duplicate IDs", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
user := seedUser(t, repo, "alice")
|
||||
ids := []uuid.UUID{user.ID}
|
||||
want := true
|
||||
|
||||
ids = append(ids, user.ID)
|
||||
|
||||
// Act.
|
||||
got, err := repo.UsersExist(t.Context(), ids)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Positive: empty set", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
var ids []uuid.UUID
|
||||
want := true
|
||||
|
||||
// Act.
|
||||
got, err := repo.UsersExist(t.Context(), ids)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing member", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newTestStore(t, config.Default().Memory)
|
||||
user := seedUser(t, repo, "alice")
|
||||
ids := []uuid.UUID{user.ID}
|
||||
want := false
|
||||
|
||||
ids = append(ids, uuid.New())
|
||||
|
||||
// Act.
|
||||
got, err := repo.UsersExist(t.Context(), ids)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("UsersExist(%v)=%v, want=%v", ids, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestStore_CreateUser_Capacity checks that a refused user consumes no storage or username index.
|
||||
func TestStore_CreateUser_Capacity(t *testing.T) {
|
||||
// Arrange.
|
||||
cfg := config.Default().Memory
|
||||
cfg.MaxUsers = 1
|
||||
repo := newTestStore(t, cfg)
|
||||
original := seedUser(t, repo, "alice")
|
||||
rejected := dto.UserDTO{ID: uuid.New(), Username: "bob"}
|
||||
previousBytes := repo.usedBytes
|
||||
|
||||
// Act.
|
||||
got, err := repo.CreateUser(t.Context(), rejected)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, store.ErrCapacity) || got != (dto.UserDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
if len(repo.users) != 1 || repo.users[original.ID] != original || len(repo.usernames) != 1 || repo.usernames[original.Username] != original.ID || repo.usedBytes != previousBytes {
|
||||
t.Fatal("refused registration changed storage or indexes")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user