fail on bad cache options

This commit is contained in:
Umputun
2018-06-18 16:21:39 -05:00
parent db774c2874
commit e751bb8678
4 changed files with 26 additions and 4 deletions
+3 -2
View File
@@ -27,7 +27,7 @@ func NewMemoryCache(options ...Option) (LoadingCache, error) {
}
for _, opt := range options {
if err := opt(&res); err != nil {
log.Printf("[WARN] failed to set cache option, %v", err)
return nil, errors.Wrap(err, "failed to set cache option")
}
}
@@ -42,7 +42,8 @@ func NewMemoryCache(options ...Option) (LoadingCache, error) {
return nil, errors.Wrap(err, "failed to make cache")
}
log.Printf("[DEBUG] create lru cache, maxKeys=%d, maxValueSize=%d", res.maxKeys, res.maxValueSize)
log.Printf("[DEBUG] create lru cache, maxKeys=%d, maxValueSize=%d, maxCacheSize=%d",
res.maxKeys, res.maxValueSize, res.maxCacheSize)
return &res, nil
}
+11
View File
@@ -297,3 +297,14 @@ func TestMemoryCache_FlushFailed(t *testing.T) {
lc.Flush("invalid-composite")
assert.Equal(t, 1, lc.(*memoryCache).bytesCache.Len())
}
func TestMemoryCache_BadOptions(t *testing.T) {
_, err := NewMemoryCache(MaxCacheSize(-1))
assert.EqualError(t, err, "failed to set cache option: negative size or MaxCacheSize, -1")
_, err = NewMemoryCache(MaxKeys(-1))
assert.EqualError(t, err, "failed to set cache option: negative size for MaxKeys, -1")
_, err = NewMemoryCache(MaxValSize(-1))
assert.EqualError(t, err, "failed to set cache option: negative size for MaxValSize, -1")
}
+11
View File
@@ -1,5 +1,7 @@
package cache
import "github.com/pkg/errors"
// Option func type
type Option func(lc *memoryCache) error
@@ -8,6 +10,9 @@ type Option func(lc *memoryCache) error
func MaxValSize(max int) Option {
return func(lc *memoryCache) error {
lc.maxValueSize = max
if max <= 0 {
return errors.Errorf("negative size for MaxValSize, %d", max)
}
return nil
}
}
@@ -17,6 +22,9 @@ func MaxValSize(max int) Option {
func MaxKeys(max int) Option {
return func(lc *memoryCache) error {
lc.maxKeys = max
if max <= 0 {
return errors.Errorf("negative size for MaxKeys, %d", max)
}
return nil
}
}
@@ -26,6 +34,9 @@ func MaxKeys(max int) Option {
func MaxCacheSize(max int64) Option {
return func(lc *memoryCache) error {
lc.maxCacheSize = max
if max <= 0 {
return errors.Errorf("negative size or MaxCacheSize, %d", max)
}
return nil
}
}
+1 -2
View File
@@ -62,8 +62,7 @@ func (s *DataStore) SetPin(locator store.Locator, commentID string, status bool)
func (s *DataStore) Vote(locator store.Locator, commentID string, userID string, val bool) (comment store.Comment, err error) {
cLock := s.getsScopedLocks(locator.URL) // get lock for URL scope
cLock.Lock()
cLock.Lock() // prevents race on voting
defer cLock.Unlock()
comment, err = s.Get(locator, commentID)