Skip to content

Conversation

NumberFour8
Copy link
Contributor

@NumberFour8 NumberFour8 commented Dec 4, 2024

The PR introduces a special target, which makes the Exit node to perform loopback of data received on a session back to it.

This is especially useful for the CT, so that no special echo service needs to be set up and the CT operation can be done from a single socket per each node.

This loopback service has ID 0, thus for target, the user specifies "target": {"Service": 0} in the REST API endpoint (instead of usual "Plain": ...)

The PR introduces a special target, which makes the Exit node to perform loopback of data received on a session back to it.

This is especially useful for the CT, so that no special echo service needs to be set up.

This loopback service has ID 0, thus for `target`, the user specifies `"target": {"Service": 0}` in the REST API endpoint (instead of usual ``"Plain": ...`)
@NumberFour8 NumberFour8 added this to the 2.2.0-rc.1 milestone Dec 4, 2024
@NumberFour8 NumberFour8 requested a review from a team December 4, 2024 14:26
@NumberFour8 NumberFour8 self-assigned this Dec 4, 2024
Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several modifications across various files in the HOPR codebase. Key changes include the addition of a new type ServiceId to enhance service identification within the transport layer, modifications to session management to accommodate this new type, and updates to existing structures and methods to improve functionality and clarity. The changes do not significantly alter existing logic or control flow but focus on enhancing the public interface and internal handling of session targets.

Changes

File Path Change Summary
hopr/hopr-lib/src/lib.rs Added new exported type ServiceId to the hopr_transport module.
hoprd/hoprd/src/exit.rs Enhanced HoprServerIpForwardingReactor to handle ExitNode with a new constant SERVICE_ID_LOOPBACK. Updated process method to log and manage loopback sessions.
hoprd/rest-api/src/session.rs Added new enum variant Service(ServiceId) to SessionTargetSpec. Updated Display and FromStr implementations to handle the new variant. Introduced into_target method for conversion logic.
tests/hopr.py Updated session_client method to include a new parameter service for handling Exit node services.
tests/test_session.py Added new test function test_session_communication_with_udp_loopback_service for UDP communication.
transport/api/src/lib.rs Added ServiceId to the exported types from hopr_transport_session::types.
transport/session/src/lib.rs Consolidated target_protocol and target fields into a single target field of type SessionTarget in SessionClientConfig.
transport/session/src/manager.rs Updated SessionManager to directly use SessionTarget in SessionClientConfig, simplifying target assignment.
transport/session/src/types.rs Introduced type alias ServiceId as pub type ServiceId = u32; and updated ExitNode variant to use ServiceId.

Possibly related PRs

Suggested labels

dependencies

Suggested reviewers

  • Teebor-Choka

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6378f89 and 1fc4595.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • hoprd/rest-api/Cargo.toml (1 hunks)
  • transport/api/Cargo.toml (1 hunks)
  • transport/session/Cargo.toml (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • transport/api/Cargo.toml
  • transport/session/Cargo.toml
  • hoprd/rest-api/Cargo.toml

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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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 marked this pull request as ready for review December 8, 2024 20:26
@github-actions github-actions bot added the testing Related to tests label Dec 8, 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 (8)
hoprd/rest-api/src/session.rs (1)

84-89: Ensure robust error handling in FromStr implementation

When parsing the service ID, consider providing more informative error messages or logging the original input that caused the parse failure. This can aid in debugging.

transport/session/src/lib.rs (1)

75-76: Update documentation for SessionClientConfig

The documentation comment for the target field mentions "Contains target protocol and optionally encrypted target of the session." Since SessionTarget now encapsulates both protocol and target, consider rephrasing the comment for clarity. For example:

-    /// Contains target protocol and optionally encrypted target of the session.
+    /// Specifies the session target, including protocol and destination details.
hoprd/hoprd/src/exit.rs (1)

191-194: Improved error variable naming

Renaming the error variable from e to error enhances code readability and clarity in log messages.

tests/hopr.py (2)

462-462: Line exceeds maximum length

Line 462 exceeds the maximum allowed line length (156 > 120). To enhance readability and comply with style guidelines, consider breaking the function signature across multiple lines.

Apply this diff to fix the line length:

-    async def session_client(self, destination: str, path: str, protocol: str, target: str, listen_on: str = "127.0.0.1:0", capabilities=None, sealed_target=False, service=False):
+    async def session_client(
+        self,
+        destination: str,
+        path: str,
+        protocol: str,
+        target: str,
+        listen_on: str = "127.0.0.1:0",
+        capabilities=None,
+        sealed_target=False,
+        service=False,
+    ):
🧰 Tools
🪛 Ruff (0.8.0)

462-462: Line too long (156 > 120)

(E501)


477-477: Simplify conditional logic for actual_target assignment

The nested ternary operators in the assignment of actual_target can reduce readability. Refactoring to a clearer conditional structure would improve maintainability.

Apply this diff to simplify the logic:

-            actual_target = {
-                "Sealed": base64.b64encode(seal_with_peerid(destination, bytes(target,'utf-8'), 50)).decode('ascii')
-            } if sealed_target else { "Service": int(target) } if service else { "Plain": target }
+            if sealed_target:
+                actual_target = {
+                    "Sealed": base64.b64encode(
+                        seal_with_peerid(destination, bytes(target, 'utf-8'), 50)
+                    ).decode('ascii')
+                }
+            elif service:
+                actual_target = { "Service": int(target) }
+            else:
+                actual_target = { "Plain": target }
tests/test_session.py (3)

380-382: Enhance docstring to describe loopback service functionality.

The current docstring focuses on buffer size which is common to all UDP tests. Consider adding information about the loopback service being tested and its purpose.

-    """
-    HOPR UDP socket buffers are set to 462 bytes to mimic the underlying MTU of the HOPR protocol.
-    """
+    """
+    Tests the UDP loopback service (Service ID: 0) which allows the Exit node to send data
+    received on a session back to itself, eliminating the need for a separate echo service.
+    
+    Note: HOPR UDP socket buffers are set to 462 bytes to mimic the underlying MTU of the HOPR protocol.
+    """

394-401: Fix string formatting and remove stale comment.

Two minor issues to address:

  1. The f-string for target doesn't need string interpolation
  2. The commented logging line references an undefined variable dst_sock_port
-    src_sock_port = await src_peer.api.session_client(dest_peer.peer_id, path={"Hops": 0}, protocol='udp',
-                                                      target=f"0", service=True)
+    src_sock_port = await src_peer.api.session_client(dest_peer.peer_id, path={"Hops": 0}, protocol='udp',
+                                                      target="0", service=True)

-    #logging.info(f"session to {dst_sock_port} opened successfully")
+    #logging.info("session opened successfully")
🧰 Tools
🪛 Ruff (0.8.0)

397-397: f-string without any placeholders

Remove extraneous f prefix

(F541)


403-426: Fix line length issue.

The code logic is correct, but there's a line that exceeds the maximum length of 120 characters.

-    assert await src_peer.api.session_close_client(protocol='udp', bound_ip='127.0.0.1', bound_port=src_sock_port) is True
+    assert await src_peer.api.session_close_client(
+        protocol='udp',
+        bound_ip='127.0.0.1',
+        bound_port=src_sock_port
+    ) is True
🧰 Tools
🪛 Ruff (0.8.0)

425-425: Line too long (122 > 120)

(E501)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4708a45 and 5573726.

📒 Files selected for processing (9)
  • hopr/hopr-lib/src/lib.rs (1 hunks)
  • hoprd/hoprd/src/exit.rs (4 hunks)
  • hoprd/rest-api/src/session.rs (5 hunks)
  • tests/hopr.py (2 hunks)
  • tests/test_session.py (1 hunks)
  • transport/api/src/lib.rs (1 hunks)
  • transport/session/src/lib.rs (2 hunks)
  • transport/session/src/manager.rs (7 hunks)
  • transport/session/src/types.rs (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.0)
tests/test_session.py

397-397: f-string without any placeholders

Remove extraneous f prefix

(F541)


425-425: Line too long (122 > 120)

(E501)

tests/hopr.py

462-462: Line too long (156 > 120)

(E501)

🔇 Additional comments (15)
hoprd/rest-api/src/session.rs (4)

61-61: Introduction of Service variant in SessionTargetSpec

The addition of the Service(ServiceId) variant to the SessionTargetSpec enum enhances flexibility by allowing service targets to be specified.


96-116: Efficient conversion logic in into_target method

The new into_target method cleanly maps SessionTargetSpec variants to SessionTarget types based on the protocol. The match arms handle all cases appropriately.


171-171: Consistent use of into_target in SessionWebsocketClientQueryRequest

Updating the code to utilize self.target.into_target(self.protocol)? streamlines the conversion process and maintains consistency.


358-358: Consistent use of into_target in SessionClientRequest

The change to use self.target.into_target(target_protocol)? ensures that target conversion is handled uniformly across the codebase.

hoprd/hoprd/src/exit.rs (2)

42-43: Definition of loopback service constant

Defining SERVICE_ID_LOOPBACK with a value of 0 clearly identifies the loopback service and improves code readability.


205-226: Successful implementation of loopback service handling

The new match arm for SessionTarget::ExitNode(SERVICE_ID_LOOPBACK) correctly implements the loopback functionality. The use of tokio::io::copy to bridge the session ensures efficient data transfer. Metrics are appropriately incremented and decremented, and error handling covers both success and failure cases.

transport/session/src/types.rs (2)

119-124: Well-documented type alias for service identification!

The ServiceId type alias with clear documentation improves code clarity and type safety. The documentation effectively explains that these are specialized targets local to the Exit node.


135-136: Good use of the new ServiceId type!

The update to use ServiceId in the ExitNode variant improves type safety and maintains consistency with the new type system.

transport/api/src/lib.rs (1)

97-97: Appropriate public API exposure!

The addition of ServiceId to the public exports is consistent with the type system changes and necessary for the loopback service functionality.

transport/session/src/manager.rs (3)

16-16: LGTM: Import refactoring

Moving the import to a dedicated line improves code organization and maintainability.


388-388: LGTM: Target field simplification

The target field is now directly used from the config, which aligns with the PR's objective of simplifying the service usage.


860-860: LGTM: Test cases updated

Test cases have been appropriately updated to use SessionTarget::TcpStream for consistency with the new target handling.

Also applies to: 984-984, 1079-1079, 1130-1130

hopr/hopr-lib/src/lib.rs (1)

88-88: LGTM: ServiceId export

Adding ServiceId to the public exports is necessary for the loopback service functionality and aligns with the PR's objective of simplifying CT usage.

tests/test_session.py (2)

384-392: LGTM!

The test setup and data preparation are consistent with other UDP tests, ensuring comparable test conditions.


375-427: Implementation looks good!

The test function effectively validates the loopback service functionality:

  • Properly tests the new Service ID 0 for loopback
  • Maintains consistency with other UDP tests
  • Includes appropriate assertions and error handling
🧰 Tools
🪛 Ruff (0.8.0)

397-397: f-string without any placeholders

Remove extraneous f prefix

(F541)


425-425: Line too long (122 > 120)

(E501)

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)
tests/test_session.py (2)

374-424: LGTM! Well-structured test for the loopback service.

The test function effectively verifies the UDP loopback service functionality by sending and receiving data through service ID 0.

Consider implementing a stress test variant of this function to verify the loopback service under high load conditions, as suggested in the previous review.

🧰 Tools
🪛 Ruff (0.8.0)

396-396: f-string without any placeholders

Remove extraneous f prefix

(F541)


396-396: Remove unnecessary f-string prefix.

The string "0" doesn't contain any placeholders, so the f prefix can be removed.

-    src_sock_port = await src_peer.api.session_client(dest_peer.peer_id, path={"Hops": 0}, protocol='udp',
-                                                      target=f"0", service=True)
+    src_sock_port = await src_peer.api.session_client(dest_peer.peer_id, path={"Hops": 0}, protocol='udp',
+                                                      target="0", service=True)
🧰 Tools
🪛 Ruff (0.8.0)

396-396: f-string without any placeholders

Remove extraneous f prefix

(F541)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5573726 and 6378f89.

📒 Files selected for processing (1)
  • tests/test_session.py (6 hunks)
🧰 Additional context used
🪛 Ruff (0.8.0)
tests/test_session.py

396-396: f-string without any placeholders

Remove extraneous f prefix

(F541)


565-565: Line too long (122 > 120)

(E501)

🔇 Additional comments (1)
tests/test_session.py (1)

255-256: LGTM! Simplified assertions improve readability.

The changes to session closure assertions across all test functions follow pytest best practices by using direct assertions instead of explicit boolean comparisons.

Also applies to: 318-319, 371-372, 423-424, 493-494, 518-519, 565-566

Copy link
Contributor

@tolbrino tolbrino left a comment

Choose a reason for hiding this comment

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

It feels like we are missing documentation on the possible targets.
Also crate version bumps missing.

@github-actions github-actions bot added the dependencies Pull requests that update a dependency file label Dec 13, 2024
@NumberFour8
Copy link
Contributor Author

It feels like we are missing documentation on the possible targets. Also crate version bumps missing.

The code documentation is in-place. But I agree that high-level documentation is missing and perhaps should be created somewhere outside the Rust docs.

@NumberFour8 NumberFour8 merged commit 506eefc into master Dec 13, 2024
29 checks passed
@NumberFour8 NumberFour8 deleted the lukas/add-loopback-service branch December 13, 2024 11:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants