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

Rate limit requests #267

Merged
merged 26 commits into from
May 30, 2024
Merged

Rate limit requests #267

merged 26 commits into from
May 30, 2024

Conversation

devbugging
Copy link
Contributor

@devbugging devbugging commented May 27, 2024

Closes: #265

Description

Rate limit the requests on both HTTP and WebSockets. Unfortunately, this couldn't be a simple HTTP middleware since this wouldn't capture WS requests, if we wanted to make it handle all requests over WS we would have to have access to the connection created, but unfortunately, that is not exposed on the go-Ethereum server implementation so we have to explicitly call it on all the handlers.


For contributor use:

  • Targeted PR against master branch
  • Linked to Github issue with discussion and accepted design OR link to spec that describes this work.
  • Code follows the standards mentioned here.
  • Updated relevant documentation
  • Re-reviewed Files changed in the Github PR explorer
  • Added appropriate labels

Summary by CodeRabbit

  • New Features

    • Introduced rate limiting for API requests to enhance system stability and prevent abuse.
    • Added a configuration option for setting request rate limits.
  • Bug Fixes

    • Fixed potential issues with high request volumes by implementing rate limiting logic.
  • Tests

    • Added new test cases to ensure rate limiting is correctly enforced and behaves as expected.

@devbugging devbugging self-assigned this May 27, 2024
Copy link
Contributor

coderabbitai bot commented May 27, 2024

Warning

Rate limit exceeded

@sideninja has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 57 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 84059b3 and 49d6409.

Walkthrough

The recent updates introduce rate-limiting capabilities to the API endpoints by integrating github.com/sethvargo/go-limiter. This enhancement affects several methods in the BlockChainAPI, PullAPI, and StreamAPI structs, adding rate-limiting logic to manage request flow. Configuration changes now allow setting rate limits, and new test cases verify the rate-limiting functionality.

Changes

File(s) Change Summary
api/api.go, api/pull.go, api/stream.go Added limiter.Store field to structs and updated methods to include rate-limiting logic.
api/errors/errors.go Introduced ErrRateLimit error to handle rate limit breaches.
api/ratelimiter.go Added rateLimit function for enforcing rate limits.
bootstrap/bootstrap.go Initialized rate limiter using memorystore.New and integrated it into API initializations.
config/config.go Added RateLimit field to Config struct and a corresponding flag in the FromFlags function.
tests/e2e_web3js_test.go Added test case for rate-limiting behavior in TestWeb3_E2E function.
tests/helpers.go Updated servicesSetup to include RateLimit configuration.
tests/web3js/eth_rate_limit_test.js Introduced a test case to verify rate-limiting using Web3.js.

Sequence Diagram(s) (Beta)

Silently ignored as it doesn't make sense for the given changes.

Assessment against linked issues

Objective (Issue #265) Addressed Explanation
Configure rate-limiting over websockets.

Poem

In the land of code, where bytes do flow,
A rabbit hops, and limits grow.
With rate controls, requests do slow,
Ensuring balance, a steady glow.
APIs now, with care bestow,
A smoother path for all to know.
🐇✨


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 Configration 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.

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: 4

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 21a0600 and 53c49ed.
Files ignored due to path filters (4)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum
  • tests/go.mod is excluded by !**/*.mod
  • tests/go.sum is excluded by !**/*.sum
Files selected for processing (10)
  • api/api.go (24 hunks)
  • api/errors/errors.go (1 hunks)
  • api/pull.go (9 hunks)
  • api/ratelimiter.go (1 hunks)
  • api/server.go (1 hunks)
  • api/stream.go (5 hunks)
  • bootstrap/bootstrap.go (4 hunks)
  • config/config.go (2 hunks)
  • tests/e2e_web3js_test.go (1 hunks)
  • tests/web3js/eth_rate_limit_test.js (1 hunks)
Files skipped from review due to trivial changes (2)
  • api/errors/errors.go
  • api/server.go
Additional Context Used
Biome (3)
tests/web3js/eth_rate_limit_test.js (3)

7-7: This let declares a variable that is only assigned once.


9-9: This let declares a variable that is only assigned once.


12-12: This let declares a variable that is only assigned once.

Additional comments not posted (10)
api/ratelimiter.go (1)

13-34: The implementation of the rate limiting function looks good.

The function properly uses the limiter to control request rates and logs appropriately when the limit is reached. Good use of context and structured logging.

tests/web3js/eth_rate_limit_test.js (1)

5-45: The test logic for rate limiting is correctly implemented.

The test effectively checks the rate limiting functionality by ensuring the number of successful and failed requests matches the expected values after hitting the rate limit. Good use of assertions to validate the behavior.

tests/e2e_web3js_test.go (1)

44-46: The addition of the rate-limit test case is appropriate.

The new test case for rate-limiting is correctly added to the suite of end-to-end tests. This ensures that the rate-limiting functionality is tested in a real-world scenario.

bootstrap/bootstrap.go (1)

234-253: The initialization and integration of the rate limiter in the API setup are correctly implemented.

The rate limiter is properly initialized with the configuration values and correctly passed to the API constructors (blockchainAPI, streamAPI, pullAPI). This ensures that rate limiting is enforced across the API.

config/config.go (1)

Line range hint 67-105: The updates to the configuration structure and parsing are correctly implemented.

The addition of the RateLimit field to the Config struct and its parsing from the command-line flags are correctly done. This allows for easy configuration of rate limits through command-line parameters, enhancing the flexibility of the application.

api/stream.go (1)

Line range hint 16-61: The integration of the rate limiter into the StreamAPI and its usage in the newSubscription method are correctly implemented.

The rate limiter is appropriately integrated into the StreamAPI struct and is effectively used in the newSubscription method to enforce rate limits before creating new subscriptions. This ensures that the streaming API respects the configured rate limits, enhancing the robustness of the system.

api/pull.go (2)

139-139: Ensure proper initialization of ratelimiter in PullAPI.

The addition of the ratelimiter field to the PullAPI struct aligns with the PR's objective to implement rate limiting. Ensure that the ratelimiter is properly initialized and configured before being used in API methods.


Line range hint 148-157: Check error handling during PullAPI initialization.

Ensure that all potential errors during the initialization of PullAPI are handled appropriately, especially since the ratelimiter is now part of the initialization parameters.

api/api.go (2)

60-60: Properly integrate limiter in BlockChainAPI.

The integration of the limiter field in the BlockChainAPI struct is crucial for implementing rate limiting at the blockchain API level. Ensure that the limiter is correctly configured and utilized in all relevant methods.


Line range hint 71-89: Validate error handling during BlockChainAPI initialization.

Ensure that errors are properly handled during the initialization of BlockChainAPI, especially with the addition of the ratelimiter parameter.

Comment on lines +174 to +176
if err := rateLimit(ctx, api.ratelimiter, api.logger); err != nil {
return "", err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Standardize error handling in rate limiting checks.

- if err := rateLimit(ctx, api.ratelimiter, api.logger); err != nil {
-     return "", err
- }
+ if err := rateLimit(ctx, api.ratelimiter, api.logger); err != nil {
+     return rpc.ID(""), fmt.Errorf("rate limit exceeded: %w", err)
+ }

Consider standardizing the error messages across all methods when the rate limit is exceeded. This will improve the consistency and clarity of error handling in the API.

Also applies to: 202-204, 248-249, 288-289, 340-341


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
if err := rateLimit(ctx, api.ratelimiter, api.logger); err != nil {
return "", err
}
if err := rateLimit(ctx, api.ratelimiter, api.logger); err != nil {
return rpc.ID(""), fmt.Errorf("rate limit exceeded: %w", err)
}

Comment on lines +22 to +25
remote := core.MetadataFromContext(ctx).Remote
if remote == "NA" {
return nil // if no client identifier disable limit
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider handling the case where remote is "NA" more securely.

Bypassing rate limiting based on a client identifier being "NA" could be a security risk if not handled properly elsewhere in the application. It's recommended to ensure that this condition is either necessary or handled with additional security checks.

api/api.go Outdated
Comment on lines 99 to 101
if err := rateLimit(ctx, b.limiter, b.logger); err != nil {
return nil, err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Refine error messages for rate limiting.

- if err := rateLimit(ctx, b.limiter, b.logger); err != nil {
-     return nil, err
- }
+ if err := rateLimit(ctx, b.limiter, b.logger); err != nil {
+     return nil, fmt.Errorf("rate limit exceeded: %w", err)
+ }

Enhance the clarity and consistency of error messages across all methods in BlockChainAPI when the rate limit is exceeded. This will help in better error tracking and user feedback.

Also applies to: 108-110, 127-129, 154-156, 173-175, 188-190, 210-212, 239-241, 268-270, 296-298, 320-322, 334-336, 363-365, 395-397, 434-436, 452-454, 481-483, 517-519, 574-576, 618-620, 650-652


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
if err := rateLimit(ctx, b.limiter, b.logger); err != nil {
return nil, err
}
if err := rateLimit(ctx, b.limiter, b.logger); err != nil {
return nil, fmt.Errorf("rate limit exceeded: %w", err)
}


remote := core.MetadataFromContext(ctx).Remote
if remote == "NA" {
return nil // if no client identifier disable limit
Copy link
Contributor

Choose a reason for hiding this comment

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

is this controlable by the user (e.g. by manipulating headers)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It's assigned from the request, so it should be fine, but this actually made me think about the issue with proxy setup.

@@ -1,6 +1,8 @@
module github.com/onflow/flow-evm-gateway

go 1.20
go 1.22
Copy link
Contributor

Choose a reason for hiding this comment

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

is this necessary? it's a good practice to do this sort of upgrade separately from a feature change in case you have to rollback.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

wasn't aware this was done, will revert

@devbugging
Copy link
Contributor Author

@sjonpaulbrown how do we have envoy setup to forward the origin IP address? I can see this documentation https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/other_features/ip_transparency
I will need this to correctly determine the request source IP.
cc @peterargue

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 UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 53c49ed and fcf0208.
Files selected for processing (1)
  • tests/helpers.go (1 hunks)
Additional comments not posted (1)
tests/helpers.go (1)

148-148: Verify the hardcoded RateLimit value.

@peterargue
Copy link
Contributor

@sjonpaulbrown how do we have envoy setup to forward the origin IP address? I can see this documentation envoyproxy.io/docs/envoy/latest/intro/arch_overview/other_features/ip_transparency I will need this to correctly determine the request source IP. cc @peterargue

Envoy is configured with use_remote_address=true which should cause it to forward the original client's IP via the x-forwarded-for header

return nil, err
}

return (*hexutil.Big)(b.config.EVMNetworkID), nil
Copy link
Collaborator

Choose a reason for hiding this comment

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

Does it make sense to rate limit a simple endpoint such as this? It only returns a value which is stored in a config object, does not make any DB interactions.
And I assume it is a frequently called endpoint, needed for transaction signing etc.

api/api.go Outdated
if err := rateLimit(ctx, b.limiter, b.logger); err != nil {
return nil, err
}

return (*hexutil.Big)(b.config.GasPrice), nil
Copy link
Collaborator

Choose a reason for hiding this comment

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

Same here, that's a fairly cheap and simple endpoint. No DB interactions.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I can remove on the simple ones.

api/api.go Outdated
if err := rateLimit(ctx, b.limiter, b.logger); err != nil {
return common.Address{}, err
}

return b.config.Coinbase, nil
Copy link
Collaborator

Choose a reason for hiding this comment

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

Same here, that's a fairly cheap and simple endpoint. No DB interactions.

go.mod Outdated
go 1.20
go 1.22

toolchain go1.22.3
Copy link
Collaborator

Choose a reason for hiding this comment

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

I am not sure how this one gets in 😅

@@ -1,6 +1,8 @@
module github.com/onflow/flow-evm-gateway/integration

go 1.20
go 1.22
Copy link
Collaborator

Choose a reason for hiding this comment

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

We probably don't want these changes to go in. Including the line:

toolchain go1.22.3

Copy link
Contributor Author

@devbugging devbugging May 30, 2024

Choose a reason for hiding this comment

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

The rate limiter library I use requires v1.22.

Copy link
Collaborator

@m-Peter m-Peter left a comment

Choose a reason for hiding this comment

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

LGTM!

Left some comments about a couple JSON-RPC endpoints that IMHO don't justify rate limiting.

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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between fcf0208 and 96c186c.

Files selected for processing (5)
  • api/api.go (24 hunks)
  • api/server.go (1 hunks)
  • bootstrap/bootstrap.go (4 hunks)
  • tests/helpers.go (2 hunks)
  • tests/web3js/eth_rate_limit_test.js (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • api/server.go
  • bootstrap/bootstrap.go
  • tests/helpers.go
Additional context used
Biome
tests/web3js/eth_rate_limit_test.js

[error] 7-7: This let declares a variable that is only assigned once.


[error] 13-13: This let declares a variable that is only assigned once.


[error] 16-16: This let declares a variable that is only assigned once.

Additional comments not posted (4)
api/api.go (4)

Line range hint 71-89: The initialization of BlockChainAPI with rate limiting is correctly implemented.


98-103: Rate limiting implementation in ChainId function is correct and efficient.


126-130: Proper implementation of rate limiting in the Syncing function.


154-157: Correct application of rate limiting in SendRawTransaction.

it('rate limit after X requests', async function () {
this.timeout(0)
setTimeout(() => process.exit(0), 5000) // make sure the process exits
let ws = new Web3("ws://127.0.0.1:8545")
Copy link
Contributor

Choose a reason for hiding this comment

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

Use const for variables that are only assigned once.

- let ws = new Web3("ws://127.0.0.1:8545")
+ const ws = new Web3("ws://127.0.0.1:8545")

- let requestLimit = 50
+ const requestLimit = 50

- let requests = 60
+ const requests = 60

This change ensures that these variables, which do not change after their initial assignment, are declared as const for better code clarity and to prevent accidental reassignments.

Also applies to: 13-13, 16-16

Committable suggestion was skipped due low confidence.

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 UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 96c186c and 84059b3.

Files selected for processing (1)
  • api/api.go (23 hunks)
Additional comments not posted (5)
api/api.go (5)

18-18: Added import for github.com/sethvargo/go-limiter.

This import is necessary for the rate limiting functionality being added across various methods in this file.


60-60: Added limiter field to BlockChainAPI struct.

This is essential for storing the rate limiter instance that will be used across various API methods to enforce rate limits.


Line range hint 71-89: Modified NewBlockChainAPI to accept a limiter.Store and return an error.

This change is crucial for initializing the BlockChainAPI with a rate limiter. The error return is appropriate to handle potential issues during initialization.


98-100: The ChainId method now accepts a context.Context and returns an error.

This modification aligns with the need to incorporate rate limiting and error handling in the method.


114-116: Rate limiting applied to various methods.

The consistent application of rate limiting across these methods ensures that the API can handle high traffic gracefully by limiting the number of requests per second.

Also applies to: 133-135, 160-162, 185-187, 207-209, 236-238, 265-267, 293-295, 322-324, 351-353, 383-385, 422-424, 440-442, 469-471, 505-507, 562-564, 606-608, 638-640

@devbugging devbugging merged commit 07405ba into main May 30, 2024
2 checks passed
@m-Peter m-Peter deleted the gregor/rate-limit-work branch July 29, 2024 16:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

Websocket rate-limiting
3 participants