-
Notifications
You must be signed in to change notification settings - Fork 873
Helper files for the flatKV cache implementation #3072
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cody-littley
wants to merge
2
commits into
main
Choose a base branch
from
cjl/cache-auxilery-2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| package dbcache | ||
|
|
||
| import ( | ||
| "github.com/sei-protocol/sei-chain/sei-db/db_engine/types" | ||
| ) | ||
|
|
||
| // Cache describes a cache capable of being used by a FlatKV store. | ||
| type Cache interface { | ||
|
|
||
| // Get returns the value for the given key, or (nil, false) if not found. | ||
| Get( | ||
| // The entry to fetch. | ||
| key []byte, | ||
| // If true, the LRU queue will be updated. If false, the LRU queue will not be updated. | ||
| // Useful for when an operation is performed multiple times in close succession on the same key, | ||
| // since it requires non-zero overhead to do so with little benefit. | ||
| updateLru bool, | ||
| ) ([]byte, bool, error) | ||
|
|
||
| // Perform a batch read operation. Given a map of keys to read, performs the reads and updates the | ||
| // map with the results. | ||
| // | ||
| // It is not thread safe to read or mutate the map while this method is running. | ||
| BatchGet(keys map[string]types.BatchGetResult) error | ||
|
|
||
| // Set sets the value for the given key. | ||
| Set(key []byte, value []byte) | ||
|
|
||
| // Delete deletes the value for the given key. | ||
| Delete(key []byte) | ||
|
|
||
| // BatchSet applies the given updates to the cache. | ||
| BatchSet(updates []CacheUpdate) error | ||
| } | ||
|
|
||
| // CacheUpdate describes a single key-value mutation to apply to the cache. | ||
| type CacheUpdate struct { | ||
| // The key to update. | ||
| Key []byte | ||
| // The value to set. If nil, the key will be deleted. | ||
| Value []byte | ||
| } | ||
|
|
||
| // IsDelete returns true if the update is a delete operation. | ||
| func (u *CacheUpdate) IsDelete() bool { | ||
| return u.Value == nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| package dbcache | ||
|
|
||
| import ( | ||
| "fmt" | ||
|
|
||
| "github.com/sei-protocol/sei-chain/sei-db/db_engine/types" | ||
| ) | ||
|
|
||
| // cachedBatch wraps a types.Batch and applies pending mutations to the cache | ||
| // after a successful commit. | ||
| type cachedBatch struct { | ||
| inner types.Batch | ||
| cache Cache | ||
| pending []CacheUpdate | ||
| } | ||
|
|
||
| var _ types.Batch = (*cachedBatch)(nil) | ||
|
|
||
| func newCachedBatch(inner types.Batch, cache Cache) *cachedBatch { | ||
| return &cachedBatch{inner: inner, cache: cache} | ||
| } | ||
|
|
||
| func (cb *cachedBatch) Set(key, value []byte) error { | ||
| cb.pending = append(cb.pending, CacheUpdate{Key: key, Value: value}) | ||
| return cb.inner.Set(key, value) | ||
| } | ||
|
|
||
| func (cb *cachedBatch) Delete(key []byte) error { | ||
| cb.pending = append(cb.pending, CacheUpdate{Key: key, Value: nil}) | ||
| return cb.inner.Delete(key) | ||
| } | ||
|
|
||
| func (cb *cachedBatch) Commit(opts types.WriteOptions) error { | ||
| if err := cb.inner.Commit(opts); err != nil { | ||
| return err | ||
| } | ||
| if err := cb.cache.BatchSet(cb.pending); err != nil { | ||
| return fmt.Errorf("failed to update cache after commit: %w", err) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if inner.Commit() succeeds but cache.BatchSet() fails, the method returns an error. Would that cause any confusion to the caller since the data is already persisted? Is cache update best-effort? If so maybe we just return nil but log the error? |
||
| } | ||
| cb.pending = nil | ||
| return nil | ||
| } | ||
|
|
||
| func (cb *cachedBatch) Len() int { | ||
| return cb.inner.Len() | ||
| } | ||
|
|
||
| func (cb *cachedBatch) Reset() { | ||
| cb.inner.Reset() | ||
| cb.pending = nil | ||
| } | ||
|
|
||
| func (cb *cachedBatch) Close() error { | ||
| return cb.inner.Close() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| package dbcache | ||
|
|
||
| import ( | ||
| "errors" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
|
|
||
| "github.com/sei-protocol/sei-chain/sei-db/db_engine/types" | ||
| ) | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // mock batch | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| type mockBatch struct { | ||
| sets []CacheUpdate | ||
| deletes [][]byte | ||
| committed bool | ||
| closed bool | ||
| resetCount int | ||
| commitErr error | ||
| } | ||
|
|
||
| func (m *mockBatch) Set(key, value []byte) error { | ||
| m.sets = append(m.sets, CacheUpdate{Key: key, Value: value}) | ||
| return nil | ||
| } | ||
|
|
||
| func (m *mockBatch) Delete(key []byte) error { | ||
| m.deletes = append(m.deletes, key) | ||
| return nil | ||
| } | ||
|
|
||
| func (m *mockBatch) Commit(opts types.WriteOptions) error { | ||
| if m.commitErr != nil { | ||
| return m.commitErr | ||
| } | ||
| m.committed = true | ||
| return nil | ||
| } | ||
|
|
||
| func (m *mockBatch) Len() int { | ||
| return len(m.sets) + len(m.deletes) | ||
| } | ||
|
|
||
| func (m *mockBatch) Reset() { | ||
| m.sets = nil | ||
| m.deletes = nil | ||
| m.committed = false | ||
| m.resetCount++ | ||
| } | ||
|
|
||
| func (m *mockBatch) Close() error { | ||
| m.closed = true | ||
| return nil | ||
| } | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // mock cache | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| type mockCache struct { | ||
| data map[string][]byte | ||
| batchSetErr error | ||
| } | ||
|
|
||
| func newMockCache() *mockCache { | ||
| return &mockCache{data: make(map[string][]byte)} | ||
| } | ||
|
|
||
| func (mc *mockCache) Get(key []byte, _ bool) ([]byte, bool, error) { | ||
| v, ok := mc.data[string(key)] | ||
| return v, ok, nil | ||
| } | ||
|
|
||
| func (mc *mockCache) BatchGet(keys map[string]types.BatchGetResult) error { | ||
| for k := range keys { | ||
| v, ok := mc.data[k] | ||
| if ok { | ||
| keys[k] = types.BatchGetResult{Value: v} | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func (mc *mockCache) Set(key, value []byte) { | ||
| mc.data[string(key)] = value | ||
| } | ||
|
|
||
| func (mc *mockCache) Delete(key []byte) { | ||
| delete(mc.data, string(key)) | ||
| } | ||
|
|
||
| func (mc *mockCache) BatchSet(updates []CacheUpdate) error { | ||
| if mc.batchSetErr != nil { | ||
| return mc.batchSetErr | ||
| } | ||
| for _, u := range updates { | ||
| if u.IsDelete() { | ||
| delete(mc.data, string(u.Key)) | ||
| } else { | ||
| mc.data[string(u.Key)] = u.Value | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // tests | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| func TestCachedBatchCommitUpdatesCacheOnSuccess(t *testing.T) { | ||
| inner := &mockBatch{} | ||
| cache := newMockCache() | ||
| cb := newCachedBatch(inner, cache) | ||
|
|
||
| require.NoError(t, cb.Set([]byte("a"), []byte("1"))) | ||
| require.NoError(t, cb.Set([]byte("b"), []byte("2"))) | ||
| require.NoError(t, cb.Commit(types.WriteOptions{})) | ||
|
|
||
| require.True(t, inner.committed) | ||
| v, ok := cache.data["a"] | ||
| require.True(t, ok) | ||
| require.Equal(t, []byte("1"), v) | ||
| v, ok = cache.data["b"] | ||
| require.True(t, ok) | ||
| require.Equal(t, []byte("2"), v) | ||
| } | ||
|
|
||
| func TestCachedBatchCommitDoesNotUpdateCacheOnInnerFailure(t *testing.T) { | ||
| inner := &mockBatch{commitErr: errors.New("disk full")} | ||
| cache := newMockCache() | ||
| cb := newCachedBatch(inner, cache) | ||
|
|
||
| require.NoError(t, cb.Set([]byte("a"), []byte("1"))) | ||
| err := cb.Commit(types.WriteOptions{}) | ||
|
|
||
| require.Error(t, err) | ||
| require.Contains(t, err.Error(), "disk full") | ||
| _, ok := cache.data["a"] | ||
| require.False(t, ok, "cache should not be updated when inner commit fails") | ||
| } | ||
|
|
||
| func TestCachedBatchCommitReturnsCacheError(t *testing.T) { | ||
| inner := &mockBatch{} | ||
| cache := newMockCache() | ||
| cache.batchSetErr = errors.New("cache broken") | ||
| cb := newCachedBatch(inner, cache) | ||
|
|
||
| require.NoError(t, cb.Set([]byte("a"), []byte("1"))) | ||
| err := cb.Commit(types.WriteOptions{}) | ||
|
|
||
| require.Error(t, err) | ||
| require.Contains(t, err.Error(), "cache broken") | ||
| require.True(t, inner.committed, "inner batch should have committed") | ||
| } | ||
|
|
||
| func TestCachedBatchDeleteMarksKeyForRemoval(t *testing.T) { | ||
| inner := &mockBatch{} | ||
| cache := newMockCache() | ||
| cache.Set([]byte("x"), []byte("old")) | ||
| cb := newCachedBatch(inner, cache) | ||
|
|
||
| require.NoError(t, cb.Delete([]byte("x"))) | ||
| require.NoError(t, cb.Commit(types.WriteOptions{})) | ||
|
|
||
| _, ok := cache.data["x"] | ||
| require.False(t, ok, "key should be deleted from cache") | ||
| } | ||
|
|
||
| func TestCachedBatchResetClearsPending(t *testing.T) { | ||
| inner := &mockBatch{} | ||
| cache := newMockCache() | ||
| cb := newCachedBatch(inner, cache) | ||
|
|
||
| require.NoError(t, cb.Set([]byte("a"), []byte("1"))) | ||
| require.NoError(t, cb.Set([]byte("b"), []byte("2"))) | ||
| cb.Reset() | ||
|
|
||
| require.NoError(t, cb.Commit(types.WriteOptions{})) | ||
|
|
||
| require.Empty(t, cache.data, "cache should have no entries after reset + commit") | ||
| } | ||
|
|
||
| func TestCachedBatchLenDelegatesToInner(t *testing.T) { | ||
| inner := &mockBatch{} | ||
| cache := newMockCache() | ||
| cb := newCachedBatch(inner, cache) | ||
|
|
||
| require.Equal(t, 0, cb.Len()) | ||
| require.NoError(t, cb.Set([]byte("a"), []byte("1"))) | ||
| require.NoError(t, cb.Delete([]byte("b"))) | ||
| require.Equal(t, 2, cb.Len()) | ||
| } | ||
|
|
||
| func TestCachedBatchCloseDelegatesToInner(t *testing.T) { | ||
| inner := &mockBatch{} | ||
| cache := newMockCache() | ||
| cb := newCachedBatch(inner, cache) | ||
|
|
||
| require.NoError(t, cb.Close()) | ||
| require.True(t, inner.closed) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Set and Delete append CacheUpdate{Key: key, Value: value} directly using the caller's slices. If the caller reuses or mutates those byte slices after calling Set/Delete but before Commit, the pending updates will contain corrupted data?