[VAULT-4034] Only cache non-nil values (#12993)

* Only cache non-nil values

* Add changelog
This commit is contained in:
Pratyoy Mukhopadhyay 2021-11-01 13:47:45 -07:00 committed by GitHub
parent 00a1bf37eb
commit 0ea9285d77
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 49 additions and 2 deletions

3
changelog/12993.txt Normal file
View File

@ -0,0 +1,3 @@
```release-note:bug
sdk/physical: Fix to only populate cache with non-nil values
```

View File

@ -184,8 +184,10 @@ func (c *Cache) Get(ctx context.Context, key string) (*Entry, error) {
return nil, err
}
if ent != nil {
// Cache the result
c.lru.Add(key, ent)
}
return ent, nil
}

View File

@ -328,3 +328,45 @@ func TestCache_Refresh(t *testing.T) {
t.Fatalf("expected value baz, got %s", string(r.Value))
}
}
// TestCache_UpdateFromStorage fetches a nil value from cache, updates
// the underlying storage and checks the cache value on a subsequent lookup
func TestCache_UpdateFromStorage(t *testing.T) {
logger := logging.NewVaultLogger(log.Debug)
inm, err := NewInmem(nil, logger)
if err != nil {
t.Fatal(err)
}
cache := physical.NewCache(inm, 0, logger, &metrics.BlackholeSink{})
cache.SetEnabled(true)
ent := &physical.Entry{
Key: "foo",
Value: []byte("bar"),
}
// Read should return nil
out, err := cache.Get(context.Background(), "foo")
if err != nil {
t.Fatalf("err: %v", err)
}
if out != nil {
t.Fatalf("should not have key")
}
// Add data to the underlying backend
inm.Put(context.Background(), ent)
// Read should return data
out, err = cache.Get(context.Background(), "foo")
if err != nil {
t.Fatalf("err: %v", err)
}
if out == nil {
t.Fatalf("should have key")
}
if string(out.Value) != "bar" {
t.Fatalf("expected value bar, got %s", string(out.Value))
}
}