Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions internal/kv/kv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,11 +225,11 @@ func TestDistributedKVReplication(t *testing.T) {
// Read from node2. Since it left no data should be replicated.
value, err = node2.Get("test-key2")
if err == nil {
t.Fatalf("we should no have be able to read the data from a node that left the cluster: %v", err)
t.Fatalf("we should not be able to read the data from a node that left the cluster: %v", err)
}

if string(value) == "test-value2" {
t.Errorf("we read the data from a node not in the cluser")
t.Errorf("we read the data from a node not in the cluster")
}

}
38 changes: 16 additions & 22 deletions internal/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,51 +13,45 @@ type Storer interface {
}

type Store struct {
db map[string][]byte
mu sync.RWMutex
m sync.Map
}

func New() *Store {
return &Store{db: map[string][]byte{}}
return &Store{}
}

func (s *Store) Get(key string) ([]byte, error) {
s.mu.RLock()
defer s.mu.RUnlock()
value, ok := s.db[key]
value, ok := s.m.Load(key)
if !ok {
return nil, errors.New("not found")
}
return value, nil

bytes, ok := value.([]byte)
if !ok {
return nil, errors.New("value is not of type []byte")
}
return bytes, nil
}

func (s *Store) Set(key string, value []byte) error {
s.mu.Lock()
defer s.mu.Unlock()
s.db[key] = value
s.m.Store(key, value)
return nil
}

func (s *Store) Delete(key string) error {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.db[key]
if !ok {
return errors.New("not found")
}
delete(s.db, key)
s.m.Delete(key)
return nil
}

func (s *Store) List() <-chan []byte {
c := make(chan []byte)
s.mu.RLock()
go func() {
defer s.mu.RUnlock()
defer close(c)
for _, val := range s.db {
c <- val
}
s.m.Range(func(key any, val any) bool {
bytes, _ := val.([]byte)
c <- bytes
return true
})
}()
return c
}