Skip to content
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

add inflight quote cache #2963

Merged
merged 5 commits into from
Jul 30, 2024
Merged

add inflight quote cache #2963

merged 5 commits into from
Jul 30, 2024

Conversation

trajan0x
Copy link
Contributor

@trajan0x trajan0x commented Jul 30, 2024

Description

addresses #2962

Summary by CodeRabbit

  • New Features

    • Introduced an inFlightManager for efficient and thread-safe management of in-flight quotes.
    • Added functionality for caching and retrieving quotes with a configurable time-to-live (TTL) to ensure data freshness.
  • Improvements

    • Enhanced balance management with clearer control mechanisms for refreshing balances and bypassing database caching.
    • Improved performance by integrating quote management directly into the inventory management process.

Copy link
Contributor

coderabbitai bot commented Jul 30, 2024

Warning

Rate limit exceeded

@trajan0x has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 39 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 3d62a40 and 6843979.

Walkthrough

The recent changes streamline the quote management system by introducing an inFlightManager, which efficiently caches in-flight quotes for improved performance and thread safety. The inventoryManagerImpl now leverages this manager to enhance balance fetching, with clearer control over refreshing logic. Overall, these updates optimize quote retrieval, refine caching mechanisms, and improve the structure and readability of the code.

Changes

Files Change Summary
services/rfq/relayer/inventory/inflight.go, services/rfq/relayer/inventory/manager.go Introduced inFlightManager for managing in-flight quotes, updated balance fetching logic, and clarified balance refresh options.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant QuoterManager
    participant InventoryManager
    participant InFlightManager

    User->>QuoterManager: SubmitAllQuotes()
    QuoterManager->>InventoryManager: GetCommittableBalances()
    InventoryManager->>InFlightManager: GetInFlightQuotes()
    InFlightManager-->>InventoryManager: Return In-Flight Quotes
    InventoryManager-->>QuoterManager: Return Committable Balances
    QuoterManager-->>User: Submit Confirmation
Loading

🐇 "In flight we hop, quotes in the air,
With caches to keep, we handle with care.
Balances refreshed, options now clear,
A structure that's strong, let's give a cheer!
In the world of code, we bounce and we play,
Optimized paths, brightening the day!" 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added go Pull requests that update Go code size/s labels Jul 30, 2024
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Summary

The pull request introduces an in-flight quote cache to optimize performance by reducing the frequency of database queries.

  • New Cache Mechanism: Added services/rfq/relayer/inventory/inflight.go to manage in-flight quotes with a caching mechanism.
  • Manager Integration: Modified services/rfq/relayer/inventory/manager.go to integrate the in-flight quote cache into the inventoryManagerImpl struct.
  • Balance Fetching Options: Updated services/rfq/relayer/inventory/options.go to include ShouldRefreshBalances and SkipDBCache options for more granular control.
  • Quote Submission Optimization: Adjusted services/rfq/relayer/quoter/quoter.go to use the new cache mechanism in the SubmitAllQuotes method.

These changes aim to address performance issues by caching frequently called SQL query results, reducing latency, and optimizing resource usage.

4 file(s) reviewed, 10 comment(s)
Edit PR Review Bot Settings

return quoter
}

func (q *inFlightManager) GetInFlightQuotes(ctx context.Context, skipCache bool) (quotes []reldb.QuoteRequest, err error) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Consider adding logging for cache hits and misses to aid in debugging and performance monitoring.

}

func (q *inFlightManager) GetInFlightQuotes(ctx context.Context, skipCache bool) (quotes []reldb.QuoteRequest, err error) {
if skipCache || q.shouldRefresh() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Ensure that the database query handles large datasets efficiently to avoid performance bottlenecks.

return q.entry.quotes, nil
}

func (q *inFlightManager) shouldRefresh() bool {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Potential race condition if shouldRefresh is called concurrently with GetInFlightQuotes. Ensure proper locking.

@@ -79,6 +79,8 @@ type inventoryManagerImpl struct {
meter metric.Meter
// balanceGauge is the histogram for balance
balanceGauge metric.Float64ObservableGauge
// inFlightQuoteManager is the cache for in flight quotes
inFlightQuoteManager *inFlightManager
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Ensure cache invalidation logic is robust to prevent stale data issues.

// get db first
// Add other committed, but incomplete statuses here
// TODO: clean me up: you can do this by having a IsLiquidityCommitted() method on the type.
inFlightQuotes, err := i.db.GetQuoteResultsByStatus(ctx, reldb.CommittedPending, reldb.CommittedConfirmed, reldb.RelayStarted)
inFlightQuotes, err := i.inFlightQuoteManager.GetInFlightQuotes(ctx, reqOptions.skipDBCache)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider adding error handling for cache retrieval failures.

var wg sync.WaitGroup
wg.Add(len(i.tokens))

gasBalances := make(map[int]*big.Int)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Pre-allocate gasBalances map with known chain IDs to improve performance.

Comment on lines +13 to +17
// ShouldRefreshBalances allows someone fetching balance(s) to skip the cache.
func ShouldRefreshBalances() BalanceFetchArgOption {
return func(options *balanceFetchOptions) {
options.skipCache = true
options.shouldRefreshBalances = true
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Ensure that forcing a balance refresh does not lead to race conditions or inconsistent state.

Comment on lines +21 to +23
func SkipDBCache() BalanceFetchArgOption {
return func(options *balanceFetchOptions) {
options.skipDBCache = true
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Skipping the DB cache might lead to increased load on the database; monitor performance.

@@ -239,7 +239,7 @@ func (m *Manager) SubmitAllQuotes(ctx context.Context) (err error) {
metrics.EndSpanWithErr(span, err)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Ensure inventory.SkipDBCache() does not introduce inconsistencies in balance retrieval.

@@ -239,7 +239,7 @@ func (m *Manager) SubmitAllQuotes(ctx context.Context) (err error) {
metrics.EndSpanWithErr(span, err)
}()

inv, err := m.inventoryManager.GetCommittableBalances(ctx)
inv, err := m.inventoryManager.GetCommittableBalances(ctx, inventory.SkipDBCache())
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Consider the impact of skipping the DB cache on performance and data consistency.

Copy link

cloudflare-workers-and-pages bot commented Jul 30, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 6843979
Status: ✅  Deploy successful!
Preview URL: https://b05e7719.sanguine-fe.pages.dev
Branch Preview URL: https://fix-manager-cache.sanguine-fe.pages.dev

View logs

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9f5bdc2 and e36ee43.

Files selected for processing (4)
  • services/rfq/relayer/inventory/inflight.go (1 hunks)
  • services/rfq/relayer/inventory/manager.go (5 hunks)
  • services/rfq/relayer/inventory/options.go (1 hunks)
  • services/rfq/relayer/quoter/quoter.go (1 hunks)
Additional comments not posted (15)
services/rfq/relayer/inventory/options.go (3)

5-6: Fields added to balanceFetchOptions.

The new fields shouldRefreshBalances and skipDBCache are correctly added to the balanceFetchOptions struct.


13-18: Function ShouldRefreshBalances correctly implemented.

The function sets the shouldRefreshBalances field to true, aligning with the new naming convention.


20-23: Function SkipDBCache correctly implemented.

The function sets the skipDBCache field to true, providing an option to bypass database caching.

services/rfq/relayer/inventory/inflight.go (6)

13-18: inFlightManager struct correctly defined.

The struct fields for TTL, database service, mutex, and cache entry are correctly defined.


20-24: inFlightQuoteCacheEntry struct correctly defined.

The struct fields for creation time and quotes are correctly defined.


29-34: Function WithTTL correctly implemented.

The function sets the TTL for the inFlightManager.


38-51: Function newInflightManager correctly implemented.

The function initializes the inFlightManager with default TTL and applies the given options.


53-68: Function GetInFlightQuotes correctly implemented.

The function retrieves in-flight quotes from the database if the cache is skipped or needs refreshing, and updates the cache entry.


70-75: Function shouldRefresh correctly implemented.

The function checks if the cache needs refreshing based on the TTL and cache entry creation time.

services/rfq/relayer/quoter/quoter.go (1)

242-244: Ensure the correctness of SkipDBCache usage.

The inclusion of inventory.SkipDBCache() ensures that the balances fetched are current and not influenced by stale data. Verify that this change does not introduce unintended side effects.

Verification successful

Ensure the correctness of SkipDBCache usage.

The inclusion of inventory.SkipDBCache() ensures that the balances fetched are current and not influenced by stale data. The GetCommittableBalances function correctly respects the skipDBCache option by conditionally refreshing balances based on the provided options.

  • services/rfq/relayer/inventory/manager.go: Implementation of GetCommittableBalances respects the skipDBCache option.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `SkipDBCache` in the codebase.

# Test: Search for the function usage. Expect: Correct usage of `SkipDBCache`.
rg --type go -A 5 $'SkipDBCache'

Length of output: 964


Script:

#!/bin/bash
# Description: Verify the implementation of `GetCommittableBalances` to ensure it respects `skipDBCache`.

# Test: Search for the definition and usage of `GetCommittableBalances`.
rg --type go -A 10 'GetCommittableBalances'

Length of output: 6493

services/rfq/relayer/inventory/manager.go (5)

82-83: Addition of inFlightQuoteManager field looks good.

The new field inFlightQuoteManager has been added to the struct inventoryManagerImpl to manage in-flight quotes.


111-115: Updated condition for refreshing balances looks good.

The condition for refreshing balances has been updated to check reqOptions.shouldRefreshBalances instead of reqOptions.skipCache.


201-209: Initialization of inFlightQuoteManager looks good.

The inFlightQuoteManager is now initialized in the NewInventoryManager constructor.


629-630: Introduction of local variable gasBalances looks good.

The local variable gasBalances has been introduced to handle gas token balances within the refreshBalances method.


119-121: Usage of inFlightQuoteManager looks good.

The retrieval of in-flight quotes now uses i.inFlightQuoteManager.GetInFlightQuotes, which leverages the new cache mechanism.

However, ensure that the GetInFlightQuotes method handles errors and edge cases appropriately.

Verification successful

The GetInFlightQuotes method handles errors and edge cases appropriately.

The method implementation includes error handling for database fetch operations and leverages a cache mechanism to optimize performance.

  • Location: services/rfq/relayer/inventory/inflight.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the `GetInFlightQuotes` method in `inFlightQuoteManager`.

# Test: Search for the method implementation. Expect: Proper error handling and edge case management.
ast-grep --lang go --pattern $'func (i *inFlightManager) GetInFlightQuotes($_, $_) {
  $$$
}'

Length of output: 94


Script:

#!/bin/bash
# Description: Search for the `GetInFlightQuotes` method in the codebase, regardless of the struct it belongs to.

# Test: Search for the method implementation. Expect: Proper error handling and edge case management.
rg 'func .*GetInFlightQuotes' -A 20

Length of output: 1574

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Summary

(updates since last review)

The pull request introduces an in-flight quote cache to optimize performance by reducing the frequency of database queries.

  • New Cache Mechanism: Added services/rfq/relayer/inventory/inflight.go to manage in-flight quotes with a caching mechanism.
  • Manager Integration: Modified services/rfq/relayer/inventory/manager.go to integrate the in-flight quote cache into the inventoryManagerImpl struct.
  • Balance Fetching Options: Updated services/rfq/relayer/inventory/options.go to include ShouldRefreshBalances and SkipDBCache options for more granular control.
  • Quote Submission Optimization: Adjusted services/rfq/relayer/quoter/quoter.go to use the new cache mechanism in the SubmitAllQuotes method.

1 file(s) reviewed, 3 comment(s)
Edit PR Review Bot Settings

if err != nil {
return nil, fmt.Errorf("could not get in flight quotes: %w", err)
}
q.mux.Lock()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider moving the defer statement to immediately after acquiring the lock to ensure it is always released.

return inFlightQuotes, nil
}

q.mux.RLock()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Ensure that the read lock is held for the shortest time possible to minimize contention.

return q.entry.quotes, nil
}

func (q *inFlightManager) shouldRefresh() bool {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Potential race condition if shouldRefresh is called concurrently with GetInFlightQuotes. Ensure proper locking.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e36ee43 and 66d4355.

Files selected for processing (1)
  • services/rfq/relayer/inventory/inflight.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • services/rfq/relayer/inventory/inflight.go

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Summary

(updates since last review)

The pull request introduces an in-flight quote cache to optimize performance by reducing the frequency of database queries.

  • New Cache Mechanism: Added services/rfq/relayer/inventory/inflight.go to manage in-flight quotes with a caching mechanism.
  • Manager Integration: Modified services/rfq/relayer/inventory/manager.go to integrate the in-flight quote cache into the inventoryManagerImpl struct.
  • Balance Fetching Options: Updated services/rfq/relayer/inventory/options.go to include ShouldRefreshBalances and SkipDBCache options for more granular control.
  • Quote Submission Optimization: Adjusted services/rfq/relayer/quoter/quoter.go to use the new cache mechanism in the SubmitAllQuotes method.

2 file(s) reviewed, 8 comment(s)
Edit PR Review Bot Settings

const defaultTTL = 250 * time.Millisecond

// newInflightManager creates a new inFlightManager with the given options.
func newInflightManager(db reldb.Service, options ...QuoterOption) *inFlightManager {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Consider dependency injection for the database service to facilitate testing and flexibility.

}

func (q *inFlightManager) GetInFlightQuotes(ctx context.Context, skipCache bool) (quotes []reldb.QuoteRequest, err error) {
if skipCache || q.shouldRefresh() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Ensure that the database query handles large datasets efficiently to avoid performance bottlenecks.

if err != nil {
return nil, fmt.Errorf("could not get in flight quotes: %w", err)
}
q.mux.Lock()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider moving the defer statement to immediately after acquiring the lock to ensure it is always released.

return inFlightQuotes, nil
}

q.mux.RLock()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Ensure that the read lock is held for the shortest time possible to minimize contention.

return q.entry.quotes, nil
}

func (q *inFlightManager) shouldRefresh() bool {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Potential race condition if shouldRefresh is called concurrently with GetInFlightQuotes. Ensure proper locking.

cfg: cfg,
chainClient: clientFetcher,
txSubmitter: txSubmitter,
rebalanceManagers: rebalanceManagers,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider adding error handling for the new inFlightManager initialization.

// get db first
// Add other committed, but incomplete statuses here
// TODO: clean me up: you can do this by having a IsLiquidityCommitted() method on the type.
inFlightQuotes, err := i.db.GetQuoteResultsByStatus(ctx, reldb.CommittedPending, reldb.CommittedConfirmed, reldb.RelayStarted)
inFlightQuotes, err := i.inFlightQuoteManager.GetInFlightQuotes(ctx, reqOptions.skipDBCache)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Ensure inFlightQuoteManager.GetInFlightQuotes handles cache retrieval failures gracefully.

@@ -106,14 +108,15 @@ func (i *inventoryManagerImpl) GetCommittableBalance(ctx context.Context, chainI
func (i *inventoryManagerImpl) GetCommittableBalances(ctx context.Context, options ...BalanceFetchArgOption) (res map[int]map[common.Address]*big.Int, err error) {
reqOptions := makeOptions(options)
// TODO: hard fail if cache skip breaks
if reqOptions.skipCache {
if reqOptions.shouldRefreshBalances {
// TODO; no need for this if refresh already in flight
_ = i.refreshBalances(ctx)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Avoid redundant balance refreshes if a refresh is already in progress.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 66d4355 and 11c6450.

Files selected for processing (2)
  • services/rfq/relayer/inventory/inflight.go (1 hunks)
  • services/rfq/relayer/inventory/manager.go (5 hunks)
Files skipped from review as they are similar to previous changes (2)
  • services/rfq/relayer/inventory/inflight.go
  • services/rfq/relayer/inventory/manager.go

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Summary

(updates since last review)

The pull request introduces an in-flight quote cache to optimize performance by reducing the frequency of database queries.

  • New Cache Mechanism: Added services/rfq/relayer/inventory/inflight.go to manage in-flight quotes with a caching mechanism.
  • TTL Adjustment: Increased default TTL for the cache from 250 milliseconds to 2 seconds.
  • Cache Logic: Updated GetInFlightQuotes method to include logic for skipping and refreshing the cache.
  • Performance Improvement: Aims to address performance bottlenecks in GetCommittableBalances by reducing SQL query frequency.

1 file(s) reviewed, 5 comment(s)
Edit PR Review Bot Settings

}
}

const defaultTTL = 2 * time.Second
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Increasing the default TTL to 2 seconds may reduce database load but could lead to stale data. Monitor for any issues.

}

func (q *inFlightManager) GetInFlightQuotes(ctx context.Context, skipCache bool) (quotes []reldb.QuoteRequest, err error) {
if skipCache || q.shouldRefresh() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Ensure that the database query handles large datasets efficiently to avoid performance bottlenecks.

if err != nil {
return nil, fmt.Errorf("could not get in flight quotes: %w", err)
}
q.mux.Lock()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider moving the defer statement to immediately after acquiring the lock to ensure it is always released.

return inFlightQuotes, nil
}

q.mux.RLock()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Ensure that the read lock is held for the shortest time possible to minimize contention.

return q.entry.quotes, nil
}

func (q *inFlightManager) shouldRefresh() bool {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Potential race condition if shouldRefresh is called concurrently with GetInFlightQuotes. Ensure proper locking.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 11c6450 and 4787a25.

Files selected for processing (1)
  • services/rfq/relayer/inventory/inflight.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • services/rfq/relayer/inventory/inflight.go

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Summary

(updates since last review)

The pull request introduces an in-flight quote cache to optimize performance by reducing the frequency of database queries.

  • New Cache Mechanism: Added services/rfq/relayer/inventory/inflight.go to manage in-flight quotes with a caching mechanism.
  • TTL Adjustment: Increased default TTL for the cache from 250 milliseconds to 2 seconds.
  • Cache Logic: Updated services/rfq/relayer/inventory/manager.go to include logic for skipping and refreshing the cache.
  • Performance Improvement: Aims to address performance bottlenecks in GetCommittableBalances by reducing SQL query frequency.

1 file(s) reviewed, 3 comment(s)
Edit PR Review Bot Settings

@@ -106,14 +108,15 @@ func (i *inventoryManagerImpl) GetCommittableBalance(ctx context.Context, chainI
func (i *inventoryManagerImpl) GetCommittableBalances(ctx context.Context, options ...BalanceFetchArgOption) (res map[int]map[common.Address]*big.Int, err error) {
reqOptions := makeOptions(options)
// TODO: hard fail if cache skip breaks
if reqOptions.skipCache {
if reqOptions.shouldRefreshBalances {
// TODO; no need for this if refresh already in flight
_ = i.refreshBalances(ctx)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Avoid redundant balance refreshes if a refresh is already in progress.

// get db first
// Add other committed, but incomplete statuses here
// TODO: clean me up: you can do this by having a IsLiquidityCommitted() method on the type.
inFlightQuotes, err := i.db.GetQuoteResultsByStatus(ctx, reldb.CommittedPending, reldb.CommittedConfirmed, reldb.RelayStarted)
inFlightQuotes, err := i.inFlightQuoteManager.GetInFlightQuotes(ctx, reqOptions.skipDBCache)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Ensure inFlightQuoteManager.GetInFlightQuotes handles cache retrieval failures gracefully.

cfg: cfg,
chainClient: clientFetcher,
txSubmitter: txSubmitter,
rebalanceManagers: rebalanceManagers,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider adding error handling for the new inFlightManager initialization.

@trajan0x trajan0x force-pushed the fix/manager-cache branch from 3d62a40 to 6843979 Compare July 30, 2024 14:16
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4787a25 and 3d62a40.

Files selected for processing (1)
  • services/rfq/relayer/inventory/manager.go (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • services/rfq/relayer/inventory/manager.go

@trajan0x trajan0x merged commit 93aa8e4 into master Jul 30, 2024
10 checks passed
@trajan0x trajan0x deleted the fix/manager-cache branch July 30, 2024 14:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
go Pull requests that update Go code size/s
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant