diff --git a/store/cache/cache.go b/store/cache/cache.go index 96790b7a..996d96e1 100644 --- a/store/cache/cache.go +++ b/store/cache/cache.go @@ -5,21 +5,34 @@ import ( "fmt" "github.com/micro/go-micro/v2/store" + "github.com/micro/go-micro/v2/store/memory" "github.com/pkg/errors" ) type cache struct { - stores []store.Store - options store.Options + stores []store.Store +} + +// Cache is a cpu register style cache for the store. +// It syncs between N stores in a faulting manner. +type Cache interface { + // Implements the store interface + store.Store } // NewCache returns a new store using the underlying stores, which must be already Init()ialised -func NewCache(stores ...store.Store) store.Store { - c := &cache{} - c.stores = make([]store.Store, len(stores)) - for i, s := range stores { - c.stores[i] = s +func NewCache(stores ...store.Store) Cache { + if len(stores) == 0 { + stores = []store.Store{ + memory.NewStore(), + } } + + // TODO: build in an in memory cache + c := &cache{ + stores: stores, + } + return c } @@ -27,15 +40,19 @@ func (c *cache) Close() error { return nil } -func (c *cache) Init(...store.Option) error { - if len(c.stores) < 2 { - return errors.New("cache requires at least 2 stores") +func (c *cache) Init(opts ...store.Option) error { + // pass to the stores + for _, store := range c.stores { + if err := store.Init(opts...); err != nil { + return err + } } return nil } func (c *cache) Options() store.Options { - return c.options + // return from first store + return c.stores[0].Options() } func (c *cache) String() string { diff --git a/store/cache/cache_test.go b/store/cache/cache_test.go index e58b2b0b..ddfa5494 100644 --- a/store/cache/cache_test.go +++ b/store/cache/cache_test.go @@ -15,13 +15,12 @@ func TestCache(t *testing.T) { assert := assert.New(t) - nonCache := NewCache(l0) - assert.NotNil(nonCache.Init(), "Expected a cache initialised with just 1 store to fail") + nonCache := NewCache(nil) + assert.Equal(len(nonCache.(*cache).stores), 1, "Expected a cache initialised with just 1 store to fail") // Basic functionality cachedStore := NewCache(l0, l1, l2) - assert.Nil(cachedStore.Init(), "Init should not error") - assert.Equal(cachedStore.Options(), store.Options{}, "Options on store/cache are nonsensical") + assert.Equal(cachedStore.Options(), l0.Options(), "Options on store/cache are nonsensical") expectedString := "cache [memory memory memory]" assert.Equal(cachedStore.String(), expectedString, "Cache couldn't describe itself as expected")