Skip to content

Conversation

NumberFour8
Copy link
Contributor

This commit introduces support for an explicit path routing feature that allows users to specify paths directly. Updates include changes to session configuration and error handling to manage explicit paths when the feature is enabled.

Dependencies and version numbers in Cargo files were also adjusted to reflect this new capability.

Closes #6617

This commit introduces support for an explicit path routing feature that allows users to specify paths directly. Updates include changes to session configuration and error handling to manage explicit paths when the feature is enabled.

Dependencies and version numbers in Cargo files were also adjusted to reflect this new capability.

Closes #6617
@NumberFour8 NumberFour8 self-assigned this Nov 11, 2024
Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes involve updates to the Cargo.toml files for both the hoprd and hoprd-api packages, introducing a new feature called explicit-path. The hoprd-api version is incremented from 3.5.2 to 3.6.0. Additionally, modifications to the send_message function and session management structures in the session.rs file enhance error handling and validation based on the explicit-path feature, allowing for more flexible routing options.

Changes

File Change Summary
hoprd/hoprd/Cargo.toml - Added feature explicit-path with dependency hoprd-api/explicit-path.
- Commented out transport-quic feature.
- Corrected comment on prof feature.
hoprd/rest-api/Cargo.toml - Updated version from 3.5.2 to 3.6.0.
- Added feature explicit-path as an empty array.
hoprd/rest-api/src/messages.rs - Enhanced error handling in send_message function based on explicit-path feature.
- Improved error messages for destination and options.
hoprd/rest-api/src/session.rs - Added optional field path to SessionWebsocketClientQueryRequest.
- Updated logic in into_protocol_session_config to handle new path field.
- Added validation in SessionClientRequest for path based on feature flags.

Assessment against linked issues

Objective Addressed Explanation
Allow to specify the path on websocket connection (#6617)

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • Teebor-Choka

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.

@NumberFour8 NumberFour8 requested a review from a team November 11, 2024 11:11
@github-actions github-actions bot added dependencies Pull requests that update a dependency file crate:hoprd-api crate:hoprd labels Nov 11, 2024
@NumberFour8 NumberFour8 marked this pull request as ready for review November 11, 2024 11:12
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)
hoprd/rest-api/src/messages.rs (1)

Line range hint 174-211: Consider enhancing error handling for path resolution.

While the overall validation is good, the error handling for path resolution could be more specific. When path resolution fails, the error message "Failed to fulfill path" doesn't provide enough context about which peer in the path failed to resolve.

Consider modifying the error handling to include the problematic peer ID:

- .map_err(|e: ApiErrorStatus| {
-     (
-         StatusCode::UNPROCESSABLE_ENTITY,
-         ApiErrorStatus::UnknownFailure(format!("Failed to fulfill path: {e}")),
-     )
-         .into_response()
- })?
+ .map_err(|e: ApiErrorStatus| {
+     (
+         StatusCode::UNPROCESSABLE_ENTITY,
+         ApiErrorStatus::UnknownFailure(format!(
+             "Failed to resolve peer in path: {}",
+             e
+         )),
+     )
+         .into_response()
+ })?
hoprd/rest-api/src/session.rs (3)

114-116: Add documentation for the path field

Consider adding documentation comments (///) to the path field in SessionWebsocketClientQueryRequest to explain its purpose and how it overrides the hops parameter when the explicit-path feature is enabled.


135-150: Avoid variable shadowing of path_options

The variable path_options is initially assigned at line 135 and then potentially shadowed at line 138 within the #[cfg(feature = "explicit-path")] block. To improve code clarity and prevent confusion, consider avoiding variable shadowing by modifying the code.

Apply this diff to avoid variable shadowing:

 let mut path_options = RoutingOptions::Hops((self.hops as u32).try_into()?);

 #[cfg(feature = "explicit-path")]
 if let Some(path) = self.path {
     // Explicit `path` will override `hops`
-    let path_options = RoutingOptions::IntermediatePath(
+    path_options = RoutingOptions::IntermediatePath(
         path.split(',')
             .map(PeerId::from_str)
             .collect::<Result<Vec<PeerId>, _>>()
             .map_err(|e| HoprLibError::GeneralError(format!("invalid peer id on path: {e}")))?
             .try_into()?,
     );
 }

314-318: Review the necessity of runtime checks for explicit-path feature

The runtime check for RoutingOptions::IntermediatePath within the #[cfg(not(feature = "explicit-path"))] block may be redundant because IntermediatePath should not be constructed when the explicit-path feature is disabled. Consider verifying whether this check is necessary.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e2ee0db and eb830c2.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • hoprd/hoprd/Cargo.toml (2 hunks)
  • hoprd/rest-api/Cargo.toml (2 hunks)
  • hoprd/rest-api/src/messages.rs (1 hunks)
  • hoprd/rest-api/src/session.rs (3 hunks)
🔇 Additional comments (6)
hoprd/rest-api/Cargo.toml (2)

22-22: LGTM! The explicit-path feature is well-implemented.

The empty feature flag implementation aligns with Rust's feature flag best practices and matches the PR objectives for enabling explicit path routing functionality.


3-3: Please clarify the version bump strategy.

The version increment from 3.5.2 to 3.6.2 (skipping 3.6.0 and 3.6.1) seems unusual. While the bump is appropriate for a new feature according to semver, could you explain why we're jumping directly to 3.6.2?

hoprd/hoprd/Cargo.toml (2)

50-50: LGTM! Clean feature definition.

The feature declaration correctly links to the corresponding hoprd-api feature, following Rust's feature flag best practices.


18-18: Consider making explicit-path an opt-in feature initially.

Adding explicit-path to default features means all builds will include this capability by default. While this aligns with the PR objectives, consider making it opt-in initially to:

  • Allow gradual adoption
  • Prevent potential disruption to existing deployments
  • Enable easier rollback if issues are discovered

Let's check if this feature is used in other parts of the codebase:

✅ Verification successful

Keep explicit-path as a default feature - safe to proceed

The code analysis shows that the explicit-path feature is well-contained and properly guarded:

  • It only adds an optional path field to session configuration
  • Has appropriate feature gates to handle both enabled and disabled states
  • Includes proper error handling when the feature is disabled
  • Does not introduce breaking changes to existing functionality as it's additive

The implementation follows a safe pattern where:

  1. When enabled: Allows optional path specification while preserving existing hop-based routing
  2. When disabled: Maintains current behavior with clear error messages
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for cfg attributes related to explicit-path feature
rg '#\[cfg.*explicit-path' 

# Search for feature-gated code blocks
rg 'cfg_if.*explicit-path'

Length of output: 348


Script:

#!/bin/bash
# Let's examine the actual code changes in the files where explicit-path is used
rg -B 2 -A 2 '#\[cfg.*explicit-path' hoprd/rest-api/src/messages.rs hoprd/rest-api/src/session.rs

# Check if there are any tests or examples using this feature
fd -e rs | xargs rg 'explicit-path'

# Look for any documentation or comments about this feature
rg -i 'explicit.?path' -g '*.{md,rs,toml}'

Length of output: 4979

hoprd/rest-api/src/messages.rs (2)

167-173: LGTM: Appropriate feature flag handling.

The conditional compilation block correctly prevents the use of explicit paths when the feature is disabled, with a clear error message.


Line range hint 5-6: Verify the explicit path routing implementation.

The implementation looks solid, but since this is a new routing feature, we should verify:

  1. That all API clients are updated to handle the new path-based routing
  2. That the feature flag is consistently checked across all entry points

Let's verify the implementation:

Also applies to: 167-211

✅ Verification successful

The explicit path routing feature is properly implemented and gated

Based on the verification results:

  1. The feature is consistently gated behind the explicit-path feature flag in both session.rs and messages.rs
  2. Proper validation is in place to reject explicit paths when the feature is not enabled
  3. The websocket API tests show that both old and new path-based routing implementations are tested
  4. The feature is properly integrated with the session management and routing infrastructure

The implementation maintains backward compatibility while properly handling the new path-based routing feature.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for other endpoints that might need the explicit-path feature flag
echo "Checking for other routing-related endpoints..."
rg -l "RoutingOptions::" --type rust

# Check for potential API clients
echo "Checking for API clients..."
fd -e ts -e js -e py -e rs "api" -x rg -l "websocket|messages"

Length of output: 656


Script:

#!/bin/bash
# Let's check the usage of explicit path routing feature flag across the codebase
echo "Checking feature flag usage..."
rg -A 5 "explicit-path" --type rust

# Let's examine the routing-related code in the identified files
echo "Checking routing implementations..."
for file in "transport/session/src/initiation.rs" "transport/session/src/manager.rs" "transport/api/src/lib.rs" "hoprd/rest-api/src/messages.rs" "hoprd/rest-api/src/session.rs"; do
    echo "=== $file ==="
    rg -A 10 "Route|route" "$file"
done

# Let's check the websocket test implementation
echo "=== Checking websocket test implementation ==="
cat "tests/test_websocket_api.py"

Length of output: 16173

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 (2)
hoprd/rest-api/src/session.rs (2)

135-150: Consider adding input validation for path

While the implementation is solid, consider adding validation for:

  1. Empty path string
  2. Maximum number of allowed hops to prevent excessive routing chains
 #[cfg(feature = "explicit-path")]
 let path_options = if let Some(path) = self.path {
+    // Validate path is not empty
+    if path.trim().is_empty() {
+        return Err(HoprLibError::GeneralError("path cannot be empty".into()));
+    }
+    
+    let peers: Vec<PeerId> = path.split(',')
+        .map(PeerId::from_str)
+        .collect::<Result<Vec<PeerId>, _>>()
+        .map_err(|e| HoprLibError::GeneralError(format!("invalid peer id on path: {e}")))?;
+    
+    // Validate maximum hops
+    const MAX_HOPS: usize = 10; // Adjust this value based on your requirements
+    if peers.len() > MAX_HOPS {
+        return Err(HoprLibError::GeneralError(format!("path exceeds maximum allowed hops: {}", MAX_HOPS)));
+    }
+    
     RoutingOptions::IntermediatePath(
-        path.split(',')
-            .map(PeerId::from_str)
-            .collect::<Result<Vec<PeerId>, _>>()
-            .map_err(|e| HoprLibError::GeneralError(format!("invalid peer id on path: {e}")))?
+        peers
             .try_into()?,
     )

Feature flag implementation needs test coverage

The explicit-path feature flag is properly defined in Cargo.toml and consistently used across the codebase with proper cfg attributes. However, there are no specific test cases covering the explicit path routing functionality. Current tests in session.rs and messages.rs only cover basic functionality.

Required actions:

  • Add test cases in hoprd/rest-api/src/session.rs to verify the behavior when explicit-path feature is enabled
  • Add test cases in hoprd/rest-api/src/messages.rs to verify message routing with explicit paths
  • Consider adding integration tests to verify the end-to-end routing behavior with explicit paths
🔗 Analysis chain

Line range hint 1-1: Verify feature flag consistency and test coverage

Let's verify the consistent usage of the explicit-path feature flag and ensure proper test coverage.


Let me gather more information about the test coverage specifically for our codebase, excluding vendor files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for consistent feature flag usage
echo "Checking feature flag usage..."
rg --type rust "explicit-path|explicit_path" -C 2

# Check for related test coverage
echo "Checking test coverage..."
rg --type rust "test.*explicit.*path|test.*path.*routing" -C 2

Length of output: 5384


Script:

#!/bin/bash
# Check for test modules and test cases in our codebase
echo "Checking test modules in hoprd..."
fd -e rs test hoprd/

echo -e "\nChecking test cases for routing and paths..."
rg --type rust "mod\s+tests|#\[test\]" -C 2 hoprd/rest-api/src/session.rs hoprd/rest-api/src/messages.rs

echo -e "\nChecking feature flag definitions..."
fd Cargo.toml -x cat {} | grep -A 5 -B 5 "explicit-path"

Length of output: 2320

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eb830c2 and c13430a.

📒 Files selected for processing (1)
  • hoprd/rest-api/src/session.rs (3 hunks)
🔇 Additional comments (2)
hoprd/rest-api/src/session.rs (2)

114-116: LGTM: Path field properly implemented

The new path field is correctly implemented with proper feature gating and documentation.


315-318: LGTM: Proper feature flag validation

The validation correctly prevents the use of explicit paths when the feature is disabled, maintaining consistency with the feature flag system.

Copy link
Contributor

@Teebor-Choka Teebor-Choka left a comment

Choose a reason for hiding this comment

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

The revert of quic-v1 should happen as a separate PR.

@Teebor-Choka Teebor-Choka added this to the 2.2.0-rc.1 milestone Nov 12, 2024
@NumberFour8 NumberFour8 added this pull request to the merge queue Nov 12, 2024
github-merge-queue bot pushed a commit that referenced this pull request Nov 12, 2024
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Nov 12, 2024
@NumberFour8 NumberFour8 added this pull request to the merge queue Nov 12, 2024
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to no response for status checks Nov 12, 2024
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 (1)
hoprd/rest-api/src/session.rs (1)

138-150: Consider using multiple path parameters instead of comma-separated values

While the implementation works, using comma-separated values for peer IDs in URLs might cause issues with some clients. Based on previous discussions, consider using multiple path parameters (e.g., path=peer1&path=peer2) which is more URL-compliant.

-            path.split(',')
+            path.split('&')
+                .filter_map(|param| param.strip_prefix("path="))
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between db14e9f and cf6f7ed.

📒 Files selected for processing (1)
  • hoprd/rest-api/src/session.rs (3 hunks)
🔇 Additional comments (2)
hoprd/rest-api/src/session.rs (2)

114-116: LGTM! Field addition follows best practices

The new path field is properly feature-gated and maintains backward compatibility by being optional.


325-328: LGTM! Proper feature validation

The validation logic correctly prevents the use of explicit paths when the feature is disabled, with a clear error message.

@NumberFour8 NumberFour8 merged commit 460bc1b into master Nov 12, 2024
28 checks passed
@NumberFour8 NumberFour8 deleted the lukas/add-fixed-path-feature branch November 12, 2024 18:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
crate:hoprd crate:hoprd-api dependencies Pull requests that update a dependency file
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Allow to specify the path on websocket connection
3 participants