Skip to content

Commit

Permalink
add mutex to the in-memory favorites manager
Browse files Browse the repository at this point in the history
  • Loading branch information
David Christofas committed Oct 5, 2021
1 parent fd072d3 commit d042c03
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions pkg/storage/favorite/favorite.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package favorite

import (
"context"
"sync"

user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
Expand All @@ -37,17 +38,20 @@ type Manager interface {

// NewInMemoryManager returns an instance of the in-memory favorites manager.
func NewInMemoryManager() Manager {
return InMemoryManager{favorites: make(map[string]map[string]*provider.ResourceId)}
return &InMemoryManager{favorites: make(map[string]map[string]*provider.ResourceId)}
}

// InMemoryManager implements the Manager interface to manage favorites using an in-memory storage.
// This should not be used in production but can be used for tests.
type InMemoryManager struct {
mux sync.RWMutex
favorites map[string]map[string]*provider.ResourceId
}

// ListFavorites returns all resources that were favorited by a user.
func (m InMemoryManager) ListFavorites(ctx context.Context, userID *user.UserId) ([]*provider.ResourceId, error) {
func (m *InMemoryManager) ListFavorites(ctx context.Context, userID *user.UserId) ([]*provider.ResourceId, error) {
m.mux.RLock()
defer m.mux.RUnlock()
favorites := make([]*provider.ResourceId, 0, len(m.favorites[userID.OpaqueId]))
for _, id := range m.favorites[userID.OpaqueId] {
favorites = append(favorites, id)
Expand All @@ -56,7 +60,9 @@ func (m InMemoryManager) ListFavorites(ctx context.Context, userID *user.UserId)
}

// SetFavorite marks a resource as favorited by a user.
func (m InMemoryManager) SetFavorite(_ context.Context, userID *user.UserId, resourceID *provider.ResourceId) error {
func (m *InMemoryManager) SetFavorite(_ context.Context, userID *user.UserId, resourceID *provider.ResourceId) error {
m.mux.Lock()
defer m.mux.Unlock()
if m.favorites[userID.OpaqueId] == nil {
m.favorites[userID.OpaqueId] = make(map[string]*provider.ResourceId)
}
Expand All @@ -65,7 +71,9 @@ func (m InMemoryManager) SetFavorite(_ context.Context, userID *user.UserId, res
}

// UnsetFavorite unmarks a resource as favorited by a user.
func (m InMemoryManager) UnsetFavorite(_ context.Context, userID *user.UserId, resourceID *provider.ResourceId) error {
func (m *InMemoryManager) UnsetFavorite(_ context.Context, userID *user.UserId, resourceID *provider.ResourceId) error {
m.mux.Lock()
defer m.mux.Unlock()
delete(m.favorites[userID.OpaqueId], resourceID.OpaqueId)
return nil
}

0 comments on commit d042c03

Please sign in to comment.