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

feat(rfq-relayer): add mutex on committable balance consumption #2994

Merged
merged 6 commits into from
Aug 16, 2024

Conversation

dwasse
Copy link
Collaborator

@dwasse dwasse commented Aug 8, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new locking mechanism for balance management to enhance concurrency control.
    • Added a mutex for balance requests in the relayer to synchronize access.
  • Improvements

    • Enhanced the QuoteRequestHandler with a mutex for thread-safe balance operations.
    • Improved documentation for mutex usage in the relayer struct for clarity.

Copy link
Contributor

coderabbitai bot commented Aug 8, 2024

Walkthrough

The changes enhance concurrency control in the relayer service's balance management. A new mutex locking mechanism has been introduced in the QuoteRequestHandler to ensure safe concurrent access to balance data, preventing race conditions during multiple requests. These modifications improve the robustness of the system and provide clearer documentation, effectively synchronizing balance requests and enhancing the overall integrity of the code structure.

Changes

Files Change Summary
services/rfq/relayer/service/handlers.go, services/rfq/relayer/service/statushandler.go Introduced mutex locks in QuoteRequestHandler for balance management, enhancing concurrency control. Added a new function for generating lock keys. Updated method signatures for consistency.
services/rfq/relayer/service/relayer.go Added a new mutex, balanceMtx, to the Relayer struct for granular control over balance requests. Updated the constructor to initialize this mutex.

Poem

In the meadow where rabbits play,
Mutexes hop in a clever way.
Safe and sound, our balances glide,
Concurrency’s friend, with joy and pride!
Hops and locks, a dance so fine,
Bouncing through code, all will align! 🐇✨


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/xs labels Aug 8, 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 PR introduces a mutex lock on committable balance consumption to prevent race conditions in the RFQ relayer service.

  • Added balanceMtx to Relayer struct in services/rfq/relayer/service/relayer.go for synchronizing balance requests.
  • Integrated balanceMtx into QuoteRequestHandler in services/rfq/relayer/service/statushandler.go to ensure thread-safe balance operations.
  • Implemented mutex lock in handleSeen method of QuoteRequestHandler in services/rfq/relayer/service/handlers.go to prevent concurrent balance consumption.
  • Introduced getBalanceMtxKey helper function in services/rfq/relayer/service/statushandler.go for generating mutex keys based on chainID and token address.

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

Copy link

cloudflare-workers-and-pages bot commented Aug 8, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 2d98795
Status: ✅  Deploy successful!
Preview URL: https://7647ae11.sanguine-fe.pages.dev
Branch Preview URL: https://feat-chain-mux.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 0f4939b and bfc0bb3.

Files selected for processing (3)
  • services/rfq/relayer/service/handlers.go (1 hunks)
  • services/rfq/relayer/service/relayer.go (2 hunks)
  • services/rfq/relayer/service/statushandler.go (2 hunks)
Additional comments not posted (6)
services/rfq/relayer/service/statushandler.go (3)

55-56: Concurrency control enhancement with balanceMtx.

The addition of balanceMtx to the QuoteRequestHandler struct enhances concurrency control for balance management.


90-90: Initialization of balanceMtx in requestToHandler.

The initialization of balanceMtx in QuoteRequestHandler ensures proper concurrency control setup.

Verify consistency of balanceMtx initialization.

Verification successful

Initialization of balanceMtx is consistent.

The balanceMtx is initialized consistently using mapmutex.NewStringMapMutex(), ensuring proper concurrency control across the codebase.

  • Location: services/rfq/relayer/service/relayer.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent initialization of `balanceMtx` in `QuoteRequestHandler`.

# Test: Search for `balanceMtx` initialization. Expect: Consistent initialization across the codebase.
rg --type go 'balanceMtx\s*:\s*mapmutex.NewStringMapMutex'

Length of output: 148


59-60: Correct implementation of getBalanceMtxKey.

The function correctly generates a unique key for balance mutexes using chainID and token.

Ensure consistent usage of this function across the codebase.

Verification successful

Limited usage of getBalanceMtxKey function.

The getBalanceMtxKey function is used in services/rfq/relayer/service/handlers.go. Ensure that this usage aligns with its intended purpose of generating unique keys for balance mutexes. If this is the only intended use, then the implementation is consistent. If more widespread usage is expected, consider reviewing other parts of the codebase.

  • Location of usage:
    • services/rfq/relayer/service/handlers.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of `getBalanceMtxKey` function across the codebase.

# Test: Search for the function usage. Expect: Consistent usage across the codebase.
rg --type go 'getBalanceMtxKey'

Length of output: 259

services/rfq/relayer/service/relayer.go (2)

66-67: Concurrency control enhancement with balanceMtx.

The addition of balanceMtx to the Relayer struct enhances concurrency control for balance management.


170-170: Initialization of balanceMtx in NewRelayer.

The initialization of balanceMtx in Relayer ensures proper concurrency control setup.

Verify consistency of balanceMtx initialization.

Verification successful

Initialization of balanceMtx is consistent.

The balanceMtx is consistently initialized using mapmutex.NewStringMapMutex() in the relayer.go file, ensuring proper concurrency control setup. No conflicting initializations were found elsewhere in the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent initialization of `balanceMtx` in `Relayer`.

# Test: Search for `balanceMtx` initialization. Expect: Consistent initialization across the codebase.
rg --type go 'balanceMtx\s*:\s*mapmutex.NewStringMapMutex'

Length of output: 148

services/rfq/relayer/service/handlers.go (1)

165-175: Mutex lock implementation in handleSeen.

The mutex lock implementation effectively manages concurrent access to balance data, preventing race conditions.

Ensure proper usage and handling of the lock across the codebase.

Verification successful

Let's search for the definition of the handleSeen function and its implementation to verify the usage of mutex locks.


Let's search for all function definitions in the services/rfq/relayer/service/handlers.go file to identify any potential candidates related to the mutex lock implementation.


Let's examine the handleSeen function for the usage of TryLock and Unlock to verify proper handling of mutex locks.


Mutex lock implementation in handleSeen is correct.

The handleSeen function in services/rfq/relayer/service/handlers.go uses a mutex lock to manage concurrent access to balance data effectively. The TryLock method is used to attempt acquiring the lock, and Unlock is deferred to ensure the lock is released properly. This implementation prevents race conditions during concurrent requests.

  • File: services/rfq/relayer/service/handlers.go
  • Function: handleSeen (starting at line 138)

The implementation appears to be correct and handles concurrent access appropriately. No further issues were found regarding mutex lock usage in this function.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify proper usage and handling of mutex locks in `handleSeen`.

# Test: Search for mutex lock usage in `handleSeen`. Expect: Proper usage and handling across the codebase.
rg --type go 'handleSeen' -A 10 | rg 'TryLock|Unlock'

Length of output: 53


Script:

#!/bin/bash
# Search for the definition and implementation of the `handleSeen` function in Go files.
ast-grep --lang go --pattern 'func handleSeen($$$) $$$'

Length of output: 57


Script:

#!/bin/bash
# List all function definitions in the `services/rfq/relayer/service/handlers.go` file.
fd 'handlers.go' --exec gawk '/^func / {print FILENAME ":" FNR ": " $0}' {}

Length of output: 2699


Script:

#!/bin/bash
# Extract the implementation of the `handleSeen` function to verify mutex lock usage.
ast-grep --lang go --pattern 'func (q *QuoteRequestHandler) handleSeen($_, $_, $_) ($_) { $$$ }'

Length of output: 7915

Copy link

codecov bot commented Aug 8, 2024

Codecov Report

Attention: Patch coverage is 0% with 27 lines in your changes missing coverage. Please review.

Project coverage is 25.29907%. Comparing base (0f4939b) to head (2d98795).
Report is 32 commits behind head on master.

Files Patch % Lines
services/rfq/relayer/service/handlers.go 0.00000% 23 Missing ⚠️
services/rfq/relayer/service/statushandler.go 0.00000% 3 Missing ⚠️
services/rfq/relayer/service/relayer.go 0.00000% 1 Missing ⚠️
Additional details and impacted files
@@                 Coverage Diff                 @@
##              master       #2994         +/-   ##
===================================================
- Coverage   25.30840%   25.29907%   -0.00933%     
===================================================
  Files            780         780                 
  Lines          56906       56927         +21     
  Branches          82          82                 
===================================================
  Hits           14402       14402                 
- Misses         41022       41043         +21     
  Partials        1482        1482                 
Flag Coverage Δ
opbot 0.48900% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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)

No major changes found since the last review.

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

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 bfc0bb3 and 9b0f267.

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

span.SetAttributes(attribute.Bool("locked", true))
return nil
}
defer unlocker.Unlock()
Copy link
Collaborator

Choose a reason for hiding this comment

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

In the case of forwarding, won't the lock be released only after the full cycle goes through? We could safely unlock once we update status to CommittedPending (aka spend the destination commitable balance)

Copy link
Collaborator

Choose a reason for hiding this comment

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

@dwasse by "full cycle" I mean the full status path Seen -> CommitPending -> CommittedConfirmed. I realised that it's not actually full, but still if that's the case we're keeping the lock longer than we should've

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah that makes sense, would still like to use defer to make this error resistant but can just add a helper function here

@github-actions github-actions bot added size/s and removed size/xs labels Aug 8, 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

(updates since last review)

The PR introduces a new locking mechanism for balance management to enhance concurrency control in the relayer service.

  • Added commitPendingBalance function in services/rfq/relayer/service/handlers.go for thread-safe balance operations.
  • Modified handleSeen function in services/rfq/relayer/service/handlers.go to incorporate the new mutex.
  • Enhanced documentation for mutex usage in the relayer struct for clarity.

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

services/rfq/relayer/service/handlers.go Show resolved Hide resolved
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 9b0f267 and 2d98795.

Files selected for processing (1)
  • services/rfq/relayer/service/handlers.go (3 hunks)
Additional comments not posted (3)
services/rfq/relayer/service/handlers.go (3)

165-179: Verify concurrency control and forwarding logic.

The handleSeen function now includes a call to commitPendingBalance. Ensure that the concurrency control and forwarding logic to handleCommitPending is robust and does not introduce race conditions.


Line range hint 182-213:
Verify error handling and synchronization with relayers.

The commitPendingBalance function introduces mutex locking and status updates. Ensure that error handling for unsupported chains and inventory checks is robust. Also, verify synchronization with other relayers to avoid reverts.

Verification successful

Error Handling and Synchronization Verified

The commitPendingBalance function effectively manages error handling and synchronization. It updates request statuses appropriately for unsupported chains and insufficient inventory. Synchronization with other relayers is achieved through an API acknowledgment mechanism, ensuring transactions are processed correctly. No issues found.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling and synchronization in `commitPendingBalance`.

# Test: Search for error handling and synchronization logic.
rg --type go -A 10 'func (q \*QuoteRequestHandler) commitPendingBalance'

Length of output: 74


Script:

#!/bin/bash
# Using ast-grep to locate the `commitPendingBalance` function definition and its context.
ast-grep --lang go --pattern 'func (q *QuoteRequestHandler) commitPendingBalance($_, $_, $_) $_'

Length of output: 5287


Line range hint 512-533:
Verify locking mechanism and status update logic.

The handleNotEnoughInventory function now acquires a balance lock. Ensure the locking mechanism is correctly implemented and that the logic for updating the request status is accurate.

Verification successful

Locking Mechanism and Status Update Logic Verified

The handleNotEnoughInventory function correctly implements the locking mechanism using balanceMtx.TryLock and updates the request status with UpdateQuoteRequestStatus. The relevant functions and methods are defined and used as expected in the codebase.

  • getBalanceMtxKey is defined in services/rfq/relayer/service/statushandler.go.
  • TryLock and GetCommittableBalance are used in services/rfq/relayer/service/handlers.go.
  • UpdateQuoteRequestStatus is defined in services/rfq/relayer/reldb/base/quote.go and used in handlers.go.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify locking mechanism and status update logic in `handleNotEnoughInventory`.

# Test: Search for the function usage and ensure proper locking and status update.
rg --type go -A 10 'func (q \*QuoteRequestHandler) handleNotEnoughInventory'

Length of output: 78


Script:

#!/bin/bash
# Search for the definition and usage of getBalanceMtxKey
rg --type go 'func getBalanceMtxKey'

# Search for the definition and usage of q.balanceMtx.TryLock
rg --type go 'TryLock' | grep 'balanceMtx'

# Search for the definition and usage of q.Inventory.GetCommittableBalance
rg --type go 'GetCommittableBalance' | grep 'Inventory'

# Search for the definition and usage of q.db.UpdateQuoteRequestStatus
rg --type go 'UpdateQuoteRequestStatus' | grep 'db'

Length of output: 3597

@trajan0x trajan0x merged commit 445b4fb into master Aug 16, 2024
29 of 31 checks passed
@trajan0x trajan0x deleted the feat/chain-mux branch August 16, 2024 10:30
dwasse added a commit that referenced this pull request Aug 19, 2024
trajan0x added a commit that referenced this pull request Aug 21, 2024
* Revert "revert(relayer): potential deadlock (#3036)" to reinstate #2994 

Co-authored-by: Daniel Wasserman <[email protected]>
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.

3 participants