-
Notifications
You must be signed in to change notification settings - Fork 16
Add a cache for active orders #615
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
ValarDragon
wants to merge
2
commits into
v28.x
Choose a base branch
from
dev/add_active_order_cache
base: v28.x
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
package orderbookusecase | ||
|
||
import ( | ||
"fmt" | ||
"sync" | ||
|
||
lru "github.com/hashicorp/golang-lru/v2" | ||
orderbookdomain "github.com/osmosis-labs/sqs/domain/orderbook" | ||
) | ||
|
||
// cacheKey represents the composite key for the active orders cache | ||
type cacheKey struct { | ||
poolID uint64 | ||
userAddress string | ||
} | ||
|
||
// activeOrdersCacheEntry represents a single cache entry containing active orders | ||
type activeOrdersCacheEntry struct { | ||
Orders []orderbookdomain.Order | ||
} | ||
|
||
// activeOrdersCache is a thread-safe LRU cache for active orders | ||
type activeOrdersCache struct { | ||
cache *lru.Cache[cacheKey, activeOrdersCacheEntry] | ||
mu sync.RWMutex | ||
// poolEntries tracks which cache keys belong to which pool for bulk invalidation | ||
poolEntries map[uint64]map[string]struct{} | ||
} | ||
|
||
// newActiveOrdersCache creates a new active orders cache with the specified size | ||
func newActiveOrdersCache(size int) (*activeOrdersCache, error) { | ||
cache, err := lru.New[cacheKey, activeOrdersCacheEntry](size) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to create LRU cache: %w", err) | ||
} | ||
|
||
return &activeOrdersCache{ | ||
cache: cache, | ||
poolEntries: make(map[uint64]map[string]struct{}), | ||
}, nil | ||
} | ||
|
||
// get retrieves active orders for a given pool ID and user address | ||
func (c *activeOrdersCache) get(poolID uint64, userAddress string) (activeOrdersCacheEntry, bool) { | ||
c.mu.RLock() | ||
defer c.mu.RUnlock() | ||
|
||
key := cacheKey{poolID: poolID, userAddress: userAddress} | ||
return c.cache.Get(key) | ||
} | ||
|
||
// set stores active orders for a given pool ID and user address | ||
func (c *activeOrdersCache) set(poolID uint64, userAddress string, entry activeOrdersCacheEntry) { | ||
c.mu.Lock() | ||
defer c.mu.Unlock() | ||
|
||
key := cacheKey{poolID: poolID, userAddress: userAddress} | ||
|
||
// Track this key for the pool | ||
if _, exists := c.poolEntries[poolID]; !exists { | ||
c.poolEntries[poolID] = make(map[string]struct{}) | ||
} | ||
c.poolEntries[poolID][userAddress] = struct{}{} | ||
|
||
c.cache.Add(key, entry) | ||
} | ||
|
||
// invalidatePool removes all cached entries for a given pool ID | ||
func (c *activeOrdersCache) invalidatePool(poolID uint64) { | ||
c.mu.Lock() | ||
defer c.mu.Unlock() | ||
|
||
// Get all keys for this pool | ||
if keys, exists := c.poolEntries[poolID]; exists { | ||
// Remove each key from the cache | ||
for userAddress := range keys { | ||
key := cacheKey{poolID: poolID, userAddress: userAddress} | ||
c.cache.Remove(key) | ||
} | ||
// Remove the pool entry tracking | ||
delete(c.poolEntries, poolID) | ||
} | ||
} | ||
|
||
// clear removes all entries from the cache | ||
func (c *activeOrdersCache) clear() { | ||
c.mu.Lock() | ||
defer c.mu.Unlock() | ||
|
||
c.cache.Purge() | ||
c.poolEntries = make(map[uint64]map[string]struct{}) | ||
} |
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
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 |
---|---|---|
|
@@ -3,6 +3,7 @@ package orderbookusecase_test | |
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"sort" | ||
"strings" | ||
"testing" | ||
|
@@ -413,14 +414,15 @@ func (s *OrderbookUsecaseTestSuite) TestGetActiveOrdersStream() { | |
if tc.setupMocks != nil { | ||
tc.setupMocks(ctx, cancel, usecase, &orderbookrepositorysitory, &client, &poolsUsecase, &tokensusecase, &callcount) | ||
} | ||
usecase.DisableCache() | ||
|
||
// Call the method under test | ||
orders := usecase.GetActiveOrdersStream(ctx, tc.address) | ||
|
||
// Wait for the ticker to push the orders | ||
if tc.expectedCallCount > 1 { | ||
usecase.SetFetchActiveOrdersEveryDuration(tc.tickerDuration) | ||
time.Sleep(tc.tickerDuration) | ||
time.Sleep(tc.tickerDuration + time.Millisecond*10) | ||
} | ||
|
||
// Collect results from the stream | ||
|
@@ -549,7 +551,7 @@ func (s *OrderbookUsecaseTestSuite) TestGetActiveOrders() { | |
poolsUsecase.GetAllCanonicalOrderbookPoolIDsFunc = s.GetAllCanonicalOrderbookPoolIDsFunc( | ||
nil, | ||
s.NewCanonicalOrderBooksResult(1, "A"), | ||
s.NewCanonicalOrderBooksResult(1, "B"), | ||
s.NewCanonicalOrderBooksResult(2, "B"), | ||
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. Pre-existing error, started causing issue post-cache since cache is keyed by pool ID |
||
) | ||
|
||
grpcclient.GetActiveOrdersCb = func(ctx context.Context, contractAddress string, ownerAddress string) (orderbookdomain.Orders, uint64, error) { | ||
|
@@ -646,6 +648,10 @@ func (s *OrderbookUsecaseTestSuite) TestGetActiveOrders() { | |
sort.SliceStable(orders, func(i, j int) bool { | ||
return orders[i].OrderId < orders[j].OrderId | ||
}) | ||
orderDebug := []string{} | ||
for _, order := range orders { | ||
orderDebug = append(orderDebug, fmt.Sprintf("%s-%d", order.OrderbookAddress, order.OrderId)) | ||
} | ||
|
||
// Assert the results | ||
if tc.expectedError != nil { | ||
|
@@ -654,7 +660,7 @@ func (s *OrderbookUsecaseTestSuite) TestGetActiveOrders() { | |
} else { | ||
s.Assert().NoError(err) | ||
s.Assert().Equal(tc.expectedIsBestEffort, isBestEffort) | ||
s.Assert().Equal(tc.expectedOrders, orders) | ||
s.Assert().Equal(tc.expectedOrders, orders, orderDebug) | ||
} | ||
}) | ||
} | ||
|
@@ -697,7 +703,7 @@ func (s *OrderbookUsecaseTestSuite) TestProcessOrderBookActiveOrders() { | |
order: newLimitOrder().WithOrderbookAddress("A"), | ||
ownerAddress: "osmo1h5la3t4y8cljl34lsqdszklvcn053u4ryz9qr78v64rsxezyxwlsdelsdr", | ||
expectedError: nil, | ||
expectedOrders: nil, | ||
expectedOrders: []orderbookdomain.LimitOrder{}, | ||
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. ITs an internal method, so doesn't matter |
||
expectedIsBestEffort: false, | ||
}, | ||
{ | ||
|
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.
We always had a race condition here before