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(sdk): fix client tls connections #2223

Merged
merged 6 commits into from
Oct 8, 2024

Conversation

QuantumExplorer
Copy link
Member

@QuantumExplorer QuantumExplorer commented Oct 8, 2024

Issue being fixed or feature implemented

Tls connections for clients were no longer working, this now fixes things.

What was done?

Added tls explicit configuration.

How Has This Been Tested?

Verified it was working

Breaking Changes

Fixes issues.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for the transport client, providing more contextual information during failures.
    • Improved error propagation when creating PlatformGrpcClient.
  • Bug Fixes

    • Refined error reporting for transport errors, offering better specificity.
  • Refactor

    • Updated method signatures to return results for improved error management.
    • Modified the get_or_create method to support error handling during item creation.
  • Chores

    • Adjusted dependency configuration for better integration with dapi-grpc, now including specific features.

Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

Walkthrough

The pull request introduces changes to the rs-dapi-client package, focusing on dependency adjustments and method signature modifications for enhanced error handling. The Cargo.toml file is updated to refine the dapi-grpc dependency, while the get_or_create method in the ConnectionPool is modified to return a Result, allowing for better error management during item creation. Additionally, error handling improvements are made in the DapiClient implementation, enhancing specificity in error reporting.

Changes

File Path Change Summary
packages/rs-dapi-client/Cargo.toml Updated backon dependency to version 1.2, disabling default features and enabling tokio-sleep. Updated dapi-grpc dependency to include core, platform, and client features while disabling default features.
packages/rs-dapi-client/src/connection_pool.rs Modified get_or_create method to return Result<PoolItem, E> instead of PoolItem, allowing for error handling during item creation.
packages/rs-dapi-client/src/dapi_client.rs Enhanced error handling in the execute method of DapiRequestExecutor trait by introducing map_err to transform errors into DapiClientError::Transport, including the address that caused the error.

Suggested labels

enhancement, js-sdk

Suggested reviewers

  • pshenmic
  • QuantumExplorer

Poem

🐰 In the code where rabbits play,
Error handling leads the way.
With each new feature, we hop and cheer,
Ensuring our paths are safe and clear.
Dependencies now dance with glee,
As we build our future, wild and free! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b400b0e and 20f84ce.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • packages/rs-dapi-client/Cargo.toml (1 hunks)
  • packages/rs-dapi-client/src/dapi_client.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/rs-dapi-client/Cargo.toml
  • packages/rs-dapi-client/src/dapi_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.

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.

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

🧹 Outside diff range and nitpick comments (2)
packages/rs-sdk/src/platform/types/evonode.rs (1)

77-86: Improved error handling for client creation.

The changes enhance the robustness of the execute_transport method by explicitly handling potential errors during client creation. This is a good improvement that ensures errors are properly propagated.

However, consider using the ? operator for more concise error handling:

let mut client = Self::Client::with_uri_and_settings(uri.clone(), settings, &pool)
    .map_err(|e| async move { Err(e) }.boxed())?;

This achieves the same result with slightly more idiomatic Rust code.

packages/rs-dapi-client/src/dapi_client.rs (1)

202-208: Improved error handling for transport client creation.

The changes enhance error reporting by wrapping the transport error in a DapiClientError::Transport variant, which includes the address that caused the error. This improvement aligns well with the PR objective of fixing client TLS connections by providing more context for connection-related errors.

For consistency with the error handling in the execute_transport call, consider using a closure for the map_err operation:

.map_err(|e| {
    DapiClientError::<<R::Client as TransportClient>::Error>::Transport(
        e,
        address.clone(),
    )
})?;

This minor change would make the error handling style uniform throughout the method.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5e996ed and 2f60720.

📒 Files selected for processing (6)
  • packages/rs-dapi-client/Cargo.toml (1 hunks)
  • packages/rs-dapi-client/src/connection_pool.rs (1 hunks)
  • packages/rs-dapi-client/src/dapi_client.rs (1 hunks)
  • packages/rs-dapi-client/src/transport.rs (1 hunks)
  • packages/rs-dapi-client/src/transport/grpc.rs (2 hunks)
  • packages/rs-sdk/src/platform/types/evonode.rs (2 hunks)
🧰 Additional context used
🔇 Additional comments (12)
packages/rs-dapi-client/Cargo.toml (1)

23-23: LGTM! Verify build success with updated dependency.

The change to the dapi-grpc dependency looks good. It explicitly enables the "client" feature while disabling default features, which should help reduce the dependency footprint and ensure only necessary functionality is included.

Potential impacts:

  1. Reduced compilation time and binary size.
  2. Only client-related functionality from dapi-grpc will be available.

Please ensure that the build still succeeds with this change, as disabling default features could potentially break the build if any were implicitly relied upon. Run the following command to verify:

packages/rs-dapi-client/src/transport.rs (2)

58-61: Consistent error handling improvement in with_uri_and_settings method.

The change to return Result<Self, Self::Error> instead of Self aligns with the modification made to the with_uri method. This consistency in error handling across related methods is commendable.

Please ensure that all implementations of the TransportClient trait have been updated to match this new signature. Run the following script to verify:

#!/bin/bash
# Description: Check for implementations of TransportClient::with_uri_and_settings

# Test: Search for implementations of with_uri_and_settings. Expect: All implementations should return Result<Self, Self::Error>
rg --type rust -e 'fn\s+with_uri_and_settings.*->.*Result<Self,\s*Self::Error>' -e 'impl.*TransportClient.*for'

54-54: Improved error handling in with_uri method.

The change from returning Self to Result<Self, Self::Error> enhances error handling capabilities during client creation. This is a good practice in Rust and allows for more robust client initialization.

Please ensure that all implementations of the TransportClient trait have been updated to match this new signature. Run the following script to verify:

✅ Verification successful

Verified TransportClient::with_uri method signatures.

All implementations of the TransportClient trait (PlatformGrpcClient and CoreGrpcClient) have been updated to return Result<Self, Self::Error>.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for implementations of TransportClient::with_uri

# Test: Search for implementations of with_uri. Expect: All implementations should return Result<Self, Self::Error>
rg --type rust -e 'fn\s+with_uri.*->.*Result<Self,\s*Self::Error>' -e 'impl.*TransportClient.*for'

Length of output: 293


Script:

#!/bin/bash
# Description: Extract TransportClient::with_uri method signatures from grpc.rs

# Extract 'with_uri' function signatures from grpc.rs
rg --type rust 'impl\s+TransportClient\s+for\s+\w+\s+\{[^}]*fn\s+with_uri[^}]*\}' packages/rs-dapi-client/src/transport/grpc.rs

Length of output: 129


Script:

#!/bin/bash
# Description: Extract TransportClient::with_uri method signatures and their return types from grpc.rs

# Find all 'fn with_uri' definitions and display their return types
rg --type rust 'fn\s+with_uri\s*\([^)]*\)\s*->\s*Result<Self,\s*Self::Error>' packages/rs-dapi-client/src/transport/grpc.rs

Length of output: 285

packages/rs-sdk/src/platform/types/evonode.rs (2)

13-13: LGTM: New import for error handling.

The addition of DapiClientError to the import list is appropriate for the enhanced error handling in the execute_transport method.


Line range hint 1-118: Summary: Improved error handling in EvoNode implementation.

The changes in this file focus on enhancing error handling in the execute_transport method of the EvoNode struct. The modifications improve the robustness of the code by explicitly handling potential errors during client creation. These changes align well with the PR objective of fixing client TLS connections.

Key points:

  1. No changes were made to public interfaces or exported entities, maintaining backwards compatibility.
  2. The overall structure and functionality of the EvoNode struct remain intact.
  3. The error handling improvements make the code more resilient to potential failures.

These changes contribute positively to the stability and reliability of the SDK.

packages/rs-dapi-client/src/connection_pool.rs (2)

70-76: Enhanced error handling in get_or_create method

The updated method signature of get_or_create now returns a Result<PoolItem, T>, allowing for proper error propagation when creating a new pool item. This change improves the robustness and reliability of the connection pool.


82-84: ⚠️ Potential issue

Incorrect arguments in self.put method call

In the call to self.put on line 83, the prefix argument is incorrectly included. The put method expects parameters uri, settings, and value (the PoolItem), but not prefix. Including prefix here will cause a compilation error due to mismatched parameters.

Apply the following diff to fix the error:

-                self.put(prefix, uri, settings, cli.clone());
+                self.put(uri, settings, cli.clone());

Likely invalid or redundant comment.

packages/rs-dapi-client/src/transport/grpc.rs (5)

21-37: Enhanced error propagation in create_channel function

The create_channel function now returns a Result<Channel, Error>, allowing for proper error propagation during channel creation. This change enhances error handling and improves the robustness of the client initialization process.


43-54: Improved error handling in with_uri method of PlatformGrpcClient

The with_uri method has been updated to return Result<Self, Self::Error>, correctly handling potential errors during channel creation. This ensures that any issues encountered while establishing the channel are properly propagated and can be managed by the caller.


61-75: Improved error handling in with_uri_and_settings method of PlatformGrpcClient

The method now returns Result<Self, Self::Error> and handles errors appropriately when creating the channel with specific settings. This modification enhances robustness by ensuring that any failures during channel creation are accurately reported.


82-93: Improved error handling in with_uri method of CoreGrpcClient

The with_uri method now returns Result<Self, Self::Error>, properly handling potential errors during channel creation for the Core client. This change ensures that the initialization process is robust and errors are effectively communicated.


100-114: Improved error handling in with_uri_and_settings method of CoreGrpcClient

The method has been updated to return Result<Self, Self::Error> and now handles errors appropriately when creating the channel with applied settings. This enhances the client's resilience by allowing error propagation.

Comment on lines +54 to +61
fn with_uri(uri: Uri, pool: &ConnectionPool) -> Result<Self, Self::Error>;

/// Build client using node's url and [AppliedRequestSettings].
fn with_uri_and_settings(
uri: Uri,
settings: &AppliedRequestSettings,
pool: &ConnectionPool,
) -> Self;
) -> Result<Self, Self::Error>;
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Unhandled Result types detected in TransportClient method calls.

The recent changes to with_uri and with_uri_and_settings methods introduce Result<Self, Self::Error> returns, enhancing error handling capabilities. However, several usages of these methods do not handle the Result, which could lead to unhandled errors and potential application instability.

Please address the following instances to ensure proper error handling:

  • packages/rs-sdk/src/platform/types/evonode.rs: let client_result = Self::Client::with_uri_and_settings(uri.clone(), settings, &pool);
  • packages/rs-dapi-client/src/dapi_client.rs: let mut transport_client = R::Client::with_uri_and_settings(
  • packages/rs-dapi-client/src/transport/grpc.rs: fn with_uri(uri: Uri, pool: &ConnectionPool) -> Result<Self, Self::Error> {
  • packages/rs-dapi-client/src/transport/grpc.rs: fn with_uri_and_settings(
  • packages/rs-dapi-client/src/transport/grpc.rs: fn with_uri(uri: Uri, pool: &ConnectionPool) -> Result<Self, Self::Error> {
  • packages/rs-dapi-client/src/transport/grpc.rs: fn with_uri_and_settings(

Ensure that each method call appropriately handles the Result using the ? operator, match statements, or other suitable error handling mechanisms.

🔗 Analysis chain

Potential breaking changes and testing recommendation.

The modifications to both with_uri and with_uri_and_settings methods improve error handling, which aligns with the PR objective of fixing client TLS connections. However, these changes may be breaking if not all implementations and usages have been updated accordingly.

  1. Ensure that all implementations of TransportClient have been updated to match the new signatures.
  2. Verify that all code using these methods now handles the Result return type correctly.
  3. Update and run all relevant tests to ensure the changes don't introduce regressions.

Run the following script to find potential usage of these methods that might need updating:

Please confirm that comprehensive testing has been performed to validate these changes across the entire codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find potential usages of TransportClient methods that might need updating

# Test: Search for usages of with_uri and with_uri_and_settings. 
# Expect: All usages should handle the Result return type
rg --type rust -e 'with_uri\s*\(' -e 'with_uri_and_settings\s*\('

Length of output: 923


Script:

#!/bin/bash
# Description: Identify TransportClient method calls that do not handle the Result properly

# Test: Search for usages of with_uri and with_uri_and_settings without proper error handling
# Expect: All calls should handle the Result using '?' operator, 'match', or other error handling constructs

# Search for 'with_uri(' or 'with_uri_and_settings(' not followed by '?' or within a 'match' statement
rg --type rust -e 'with_uri\s*\(' -e 'with_uri_and_settings\s*\(' -A 2 | grep -B 2 -vE '\?|\bmatch\b'

Length of output: 2254

Comment on lines 25 to 29
let mut builder = Channel::builder(uri).tls_config(
ClientTlsConfig::new()
.with_native_roots()
.with_webpki_roots(),
)?;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Redundant TLS root certificates configuration

In the create_channel function, both with_native_roots() and with_webpki_roots() are called on the TLS configuration. These methods set the root certificate store, and calling both may lead to unintended behavior as they might overwrite each other. To ensure the TLS configuration is set correctly, consider using only one of these methods based on the desired root certificates source.

Apply this diff to fix the redundancy:

         ClientTlsConfig::new()
-            .with_native_roots()
             .with_webpki_roots(),
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let mut builder = Channel::builder(uri).tls_config(
ClientTlsConfig::new()
.with_native_roots()
.with_webpki_roots(),
)?;
let mut builder = Channel::builder(uri).tls_config(
ClientTlsConfig::new()
.with_webpki_roots(),
)?;

Comment on lines +47 to +52
Ok(channel) => Ok(Self::new(channel).into()),
Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
"Channel creation failed: {}",
e
))),
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Review the use of gRPC status code for error handling

When handling errors from create_channel, the code wraps the error using Status::failed_precondition. The FAILED_PRECONDITION status code indicates that the system is in an invalid state for the operation to execute. Since channel creation failure might be due to connectivity issues or misconfigurations, consider whether Status::unavailable or Status::internal might more accurately represent the error type.

Apply this diff if you decide to change the status code:

                         Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
-                            "Channel creation failed: {}",
+                            "Channel is unavailable: {}",
                             e
                         ))),

Committable suggestion was skipped due to 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

🧹 Outside diff range and nitpick comments (4)
packages/rs-dapi-client/src/transport/grpc.rs (4)

25-30: LGTM: Improved TLS configuration and channel creation

The changes enhance the security of the gRPC connections by adding TLS configuration. However, there's a minor redundancy in the TLS configuration that should be addressed.

Consider removing the redundant with_native_roots() call as mentioned in a previous review:

     let mut builder = Channel::builder(uri).tls_config(
         ClientTlsConfig::new()
-            .with_native_roots()
             .with_webpki_roots()
             .assume_http2(true),
     )?;

This change will ensure that only the WebPKI roots are used, avoiding any potential conflicts or unintended behavior.

Also applies to: 38-38


44-55: LGTM: Improved error handling in with_uri method

The changes enhance error handling in the with_uri method, properly propagating errors from channel creation. This improvement allows for better error management in the calling code.

Consider using a more specific error status for channel creation failures. The current failed_precondition might not accurately represent all possible error scenarios. A more appropriate status might be unavailable for network-related issues or internal for unexpected errors:

-                    Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
+                    Err(e) => Err(dapi_grpc::tonic::Status::unavailable(format!(
                         "Channel creation failed: {}",
                         e
                     ))),

This change would provide more accurate error information to the caller.


62-76: LGTM: Consistent error handling in with_uri_and_settings method

The changes in the with_uri_and_settings method are consistent with those in the with_uri method, providing improved error handling and propagation.

As suggested for the with_uri method, consider using a more specific error status for channel creation failures:

-                    Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
+                    Err(e) => Err(dapi_grpc::tonic::Status::unavailable(format!(
                         "Channel creation failed: {}",
                         e
                     ))),

This change would provide more accurate error information and maintain consistency with the with_uri method.


83-115: LGTM: Consistent updates to CoreGrpcClient implementation

The changes to the CoreGrpcClient implementation are consistent with those made to PlatformGrpcClient, ensuring uniform error handling and connection management across both client types.

For consistency with the suggested changes in PlatformGrpcClient, consider updating the error status in both with_uri and with_uri_and_settings methods:

-                    Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
+                    Err(e) => Err(dapi_grpc::tonic::Status::unavailable(format!(
                         "Channel creation failed: {}",
                         e
                     ))),

This change would provide more accurate error information and maintain consistency across all client implementations.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2f60720 and 01282fb.

📒 Files selected for processing (1)
  • packages/rs-dapi-client/src/transport/grpc.rs (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
packages/rs-dapi-client/src/transport/grpc.rs (2)

11-11: LGTM: Improved error handling in create_channel function

The changes to the import statement and the create_channel function signature enhance error handling. Returning a Result type allows for better error propagation and handling in the calling code.

Also applies to: 21-24


Line range hint 1-115: Overall assessment: Improved error handling and TLS configuration

The changes in this file significantly enhance the robustness of the gRPC transport layer by improving error handling and TLS configuration. The modifications are consistent across both PlatformGrpcClient and CoreGrpcClient, ensuring uniform behavior.

Key improvements:

  1. Better error propagation in the create_channel function and client methods.
  2. Enhanced TLS configuration for secure connections.
  3. Consistent use of the connection pool for efficient channel management.

Minor suggestions have been made to further refine error handling and remove redundant TLS configuration. Overall, these changes represent a solid improvement to the codebase.

Copy link
Member

@shumkov shumkov left a comment

Choose a reason for hiding this comment

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

Tests aren't passing

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.

3 participants