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: add keepalive to Torii client gRPC connections #2690

Merged
merged 3 commits into from
Nov 14, 2024

Conversation

edisontim
Copy link
Collaborator

@edisontim edisontim commented Nov 14, 2024

Description

Allows grpc subscriptions to survive network issues by introducing a keepalive parameter, the Some value represents the delay between keepalive checks between the grpc client and server.

Tests

  • Yes
  • No, because they aren't needed
  • No, because I need help

Added to documentation?

  • README.md
  • Dojo Book
  • No documentation needed

Checklist

  • I've formatted my code (scripts/prettier.sh, scripts/rust_fmt.sh, scripts/cairo_fmt.sh)
  • I've linted my code (scripts/clippy.sh, scripts/docs.sh)
  • I've commented my code
  • I've requested a review after addressing the comments

Summary by CodeRabbit

  • New Features

    • Introduced an optional keepalive parameter for enhanced TCP keepalive configuration in the gRPC client.
  • Bug Fixes

    • Preserved existing functionality while adding new features, ensuring stability of the client.

Copy link

coderabbitai bot commented Nov 14, 2024

Walkthrough

Ohayo, sensei! The changes introduce a new optional parameter, keepalive, of type Option<Duration>, to the new method of the WorldClient struct in the gRPC client. This allows for the configuration of TCP keepalive settings. The method signature is updated accordingly, and a call to set the keepalive duration is added during the creation of the Endpoint, but only if the target architecture is not wasm32. The overall functionality and error handling remain unchanged.

Changes

File Path Change Summary
crates/torii/grpc/src/client.rs Updated new method signature to include keepalive: Option<Duration>. Added TCP keepalive logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant WorldClient
    participant Endpoint

    Client->>WorldClient: new(dst, world_address, keepalive)
    WorldClient->>Endpoint: create with dst
    alt Not wasm32
        Endpoint->>Endpoint: tcp_keepalive(Some(Duration::from_secs(60)))
    end
    WorldClient->>Client: Return Result
Loading

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 756027b and 1138d8b.

📒 Files selected for processing (1)
  • crates/torii/grpc/src/client.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/torii/grpc/src/client.rs

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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

@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

🧹 Outside diff range and nitpick comments (3)
crates/torii/client/src/client/mod.rs (1)

44-46: Consider adding documentation for the keepalive parameter, sensei!

The optional keepalive parameter is well-designed, but it would benefit from documentation explaining:

  • The purpose of the keepalive parameter
  • The expected duration range
  • What happens when None is provided

Add this documentation above the parameter:

     pub async fn new(
         torii_url: String,
         rpc_url: String,
         relay_url: String,
         world: Felt,
+        /// Duration between keepalive checks for maintaining gRPC connection resilience.
+        /// When None is provided, the default gRPC keepalive settings are used.
         keepalive: Option<Duration>,
     ) -> Result<Self, Error> {
crates/torii/grpc/src/client.rs (2)

53-57: Ohayo sensei! Please add documentation for the keepalive parameter.

The new keepalive parameter would benefit from documentation explaining:

  • Its purpose in maintaining connection resilience
  • Expected duration values
  • When to use it (e.g., in unstable network conditions)

Example doc comment:

/// Creates a new WorldClient instance.
/// 
/// # Arguments
/// * `dst` - The destination URL for the gRPC connection
/// * `world_address` - The Felt address of the world
/// * `keepalive` - Optional duration between keepalive checks. Use this in unstable network conditions
///                 to maintain connection resilience. Recommended values: 10-30 seconds.

58-60: Consider validating keepalive duration values.

While the implementation is correct, consider adding validation for the keepalive duration to prevent potential issues with very short intervals.

 let endpoint = Endpoint::from_shared(dst.clone())
     .map_err(|e| Error::Endpoint(e.to_string()))?
+    .tcp_keepalive(keepalive.and_then(|d| {
+        if d.as_secs() < 5 {
+            None // Ignore too short intervals
+        } else {
+            Some(d)
+        }
+    }));
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 51d80cf and 51894b3.

📒 Files selected for processing (2)
  • crates/torii/client/src/client/mod.rs (2 hunks)
  • crates/torii/grpc/src/client.rs (2 hunks)
🔇 Additional comments (4)
crates/torii/client/src/client/mod.rs (2)

4-4: Ohayo! Clean import addition, sensei!

The Duration import is properly placed with other std imports and correctly supports the new keepalive functionality.


47-48: Verify WorldClient implementation, sensei!

The keepalive parameter is correctly passed to WorldClient::new, but let's verify the implementation.

✅ Verification successful

Keepalive implementation is properly handled, sensei!

The WorldClient::new implementation correctly:

  • Takes the keepalive parameter as Option<Duration>
  • Applies it to the endpoint configuration via tcp_keepalive(keepalive)
  • Properly handles errors during connection setup
  • Has appropriate cfg-gated implementations for both native and wasm targets
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check WorldClient implementation and error handling

# Find WorldClient::new implementation
ast-grep --pattern 'impl WorldClient {
  $$$
  async fn new($$$) {
    $$$
  }
  $$$
}'

# Check for any keepalive-related error handling
rg -A 5 'tcp_keepalive|keep_alive' 

Length of output: 646


Script:

#!/bin/bash
# Let's check the full WorldClient implementation to understand the keepalive handling

# Find the complete WorldClient implementation
ast-grep --pattern 'impl WorldClient {
  $$$
}'

# Also check for any keepalive-related struct fields or types
rg -B 2 -A 2 'struct WorldClient'

Length of output: 15610

crates/torii/grpc/src/client.rs (2)

3-3: Ohayo! Clean import addition.

The Duration import is properly placed and necessary for the keepalive functionality.


53-60: Verify impact on existing client code.

The addition of the keepalive parameter requires updates to all existing WorldClient::new calls.

Copy link

codecov bot commented Nov 14, 2024

Codecov Report

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

Project coverage is 57.23%. Comparing base (c364d13) to head (1138d8b).
Report is 47 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/grpc/src/client.rs 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2690      +/-   ##
==========================================
- Coverage   57.46%   57.23%   -0.23%     
==========================================
  Files         400      408       +8     
  Lines       49963    51792    +1829     
==========================================
+ Hits        28709    29644     +935     
- Misses      21254    22148     +894     

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

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Thanks for this @edisontim!

Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
let endpoint = Endpoint::from_shared(dst.clone())
.map_err(|e| Error::Endpoint(e.to_string()))?
.tcp_keepalive(Some(Duration::from_secs(30)));
Copy link
Collaborator

Choose a reason for hiding this comment

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

On what this value is based @edisontim? Something arbitrary that should work, or it's a value that is expected to work in most cases?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It was an arbitrary value but after a quick research the recommended time is from 45-60 secs.

I'll set it to 60 secs as to not spam the server

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants