Skip to content

Conversation

NumberFour8
Copy link
Contributor

When UDP-based Session goes idle or is closed by the other side, it should be correctly removed from the Session list.

Also added some cosmetic code improvements.

When UDP-based Session goes idle or is closed by the other side, it should be correctly removed from the Session list.

Also added some cosmetic code improvements.
@NumberFour8 NumberFour8 added this to the 2.2.0-rc.1 milestone Nov 16, 2024
@NumberFour8 NumberFour8 requested a review from a team November 16, 2024 08:28
@NumberFour8 NumberFour8 self-assigned this Nov 16, 2024
@NumberFour8 NumberFour8 marked this pull request as ready for review November 16, 2024 08:28
Copy link
Contributor

coderabbitai bot commented Nov 16, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve modifications across three main files: udp.rs, session.rs, and manager.rs. Enhancements include improved documentation and error handling for UDP and TCP session management, along with refined logging practices. The create_client function in session.rs now establishes sessions more efficiently for both protocols. Additionally, the SessionManager's methods have been updated to clarify session initiation and improve error logging. Overall, these changes focus on enhancing clarity, consistency, and maintainability without altering existing functionality.

Changes

File Path Change Summary
common/network-types/src/udp.rs Updated comments and documentation for ConnectedUdpStream and UdpStreamBuilder. Adjusted logging statements for clarity. Enhanced error handling in poll_read, poll_write, and poll_flush methods.
hoprd/rest-api/src/session.rs Significant changes to create_client function for TCP and UDP session management. Improved error handling and comments. Updated function signatures for create_client and websocket.
transport/session/src/manager.rs Updated documentation and error handling in new_session and dispatch_message methods. Adjusted logging for session ID clarity. Minor documentation improvements throughout.
common/network-types/Cargo.toml Version updated from 0.5.0 to 0.5.1.
hoprd/rest-api/Cargo.toml Version updated from 3.6.0 to 3.6.1.
transport/session/Cargo.toml Version updated from 0.3.0 to 0.3.1.

Possibly related PRs

Suggested labels

bug, dependencies, crate:hopr-db-api, crate:core-network

Suggested reviewers

  • Teebor-Choka

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 49a40f4 and 6973376.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • common/network-types/Cargo.toml (1 hunks)
  • hoprd/rest-api/Cargo.toml (1 hunks)
  • transport/session/Cargo.toml (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • common/network-types/Cargo.toml
  • hoprd/rest-api/Cargo.toml
  • transport/session/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 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
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

🧹 Outside diff range and nitpick comments (5)
common/network-types/src/udp.rs (1)

304-305: Consider implementing socket splitting

The TODO comment suggests an important architectural improvement that could enhance socket management and reusability.

Would you like me to help design and implement the socket splitting functionality? I can create a GitHub issue to track this enhancement.

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

Line range hint 359-419: Consider enhancing error handling and race condition protection in session initiation

The session initiation logic could benefit from the following improvements:

  1. Add more granular error handling for different failure scenarios (network issues, protocol mismatches, etc.)
  2. Consider adding a mutex or similar synchronization primitive around session establishment to prevent potential race conditions when multiple sessions are being established simultaneously
 pub async fn new_session(&self, cfg: SessionClientConfig) -> crate::errors::Result<Session> {
+    // Add a mutex guard here to prevent race conditions
+    let _guard = self.session_establishment_lock.lock().await;
+
     let msg_sender = self.msg_sender.get().ok_or(SessionManagerError::NotStarted)?;
 
     let (tx_initiation_done, rx_initiation_done) = futures::channel::mpsc::unbounded();
@@ -419,6 +422,15 @@
             Either::Left((Err(e)), _) => {
-                error!(challenge = e.challenge, error = ?e, "the other party rejected the session initiation with error");
-                Err(TransportSessionError::Rejected(e.reason))
+                match e.reason {
+                    StartErrorReason::NoSlotsAvailable => {
+                        error!(challenge = e.challenge, "no slots available for session");
+                        Err(TransportSessionError::NoSlots)
+                    }
+                    StartErrorReason::ProtocolMismatch => {
+                        error!(challenge = e.challenge, "protocol version mismatch");
+                        Err(TransportSessionError::ProtocolMismatch)
+                    }
+                    _ => Err(TransportSessionError::Rejected(e.reason))
+                }
             }

519-519: Improve session logging consistency and metadata

The session logging could be enhanced by:

  1. Using structured logging with consistent fields across all log messages
  2. Including additional session metadata (e.g., protocol, capabilities)
  3. Adding timing information for session establishment
-debug!(%peer, "got new session request, searching for a free session slot");
+debug!(
+    %peer,
+    protocol = ?session_req.target.protocol(),
+    capabilities = ?session_req.capabilities,
+    "got new session request, searching for a free session slot"
+);

-info!(%session_id, "new session established");
+info!(
+    %session_id,
+    protocol = ?session_req.target.protocol(),
+    capabilities = ?session_req.capabilities,
+    establishment_time_ms = %start_time.elapsed().as_millis(),
+    "new session established"
+);

Also applies to: 590-619

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

Line range hint 505-549: Ensure consistent listener management between TCP and UDP sessions.

In the UDP session handling, the listener is removed from open_listeners when the session closes:

// Once the Session closes, remove it from the list
open_listeners_clone.write().await.remove(&listener_id);

However, in the TCP case, this cleanup step is missing. This could lead to inconsistent state or resource leaks. Consider adding similar cleanup logic for TCP sessions to ensure consistent management across both protocols.

Apply this diff to add the cleanup logic for TCP sessions:

 state
     .open_listeners
     .write()
     .await
     .insert(ListenerId(protocol, bound_host), (target.clone(), jh));
+ 
+ // Remove the listener from the list when the task completes
+ let open_listeners_clone = state.open_listeners.clone();
+ let listener_id = ListenerId(protocol, bound_host);
+ hopr_async_runtime::prelude::spawn(async move {
+     jh.await.unwrap_or_else(|e| error!(error = %e, "TCP listener task failed"));
+     open_listeners_clone.write().await.remove(&listener_id);
+ });

 bound_host

788-791: Standardize logging format in error handling.

The logging statement has inconsistent formatting. Aligning it with the standard logging practices improves readability and consistency.

Apply this diff to standardize the logging format:

-            Err(error) => error!(
-                session_id = ?session_id,
-                %error,
-                "error during data transfer"
-            ),
+            Err(error) => {
+                error!(
+                    session_id = ?session_id,
+                    error = %error,
+                    "Error during data transfer"
+                );
+            },
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 52d3d87 and 49a40f4.

📒 Files selected for processing (3)
  • common/network-types/src/udp.rs (17 hunks)
  • hoprd/rest-api/src/session.rs (7 hunks)
  • transport/session/src/manager.rs (6 hunks)
🧰 Additional context used
📓 Learnings (1)
hoprd/rest-api/src/session.rs (2)
Learnt from: Teebor-Choka
PR: hoprnet/hoprnet#6393
File: hoprd/rest-api/src/session.rs:91-91
Timestamp: 2024-11-12T10:55:50.205Z
Learning: The current implementation in `hoprd/rest-api/src/session.rs` assumes all sessions are TCP-like due to the missing implementation of UDP behavior. The commented-out code suggests an intention to support different session types based on `capabilities`.
Learnt from: Teebor-Choka
PR: hoprnet/hoprnet#6393
File: hoprd/rest-api/src/session.rs:91-91
Timestamp: 2024-11-12T10:56:01.095Z
Learning: The current implementation in `hoprd/rest-api/src/session.rs` assumes all sessions are TCP-like due to the missing implementation of UDP behavior. The commented-out code suggests an intention to support different session types based on `capabilities`.
🔇 Additional comments (5)
common/network-types/src/udp.rs (2)

Line range hint 267-277: Documentation improvements look good!

The clarifications about platform-specific behavior and wildcard address handling enhance the API documentation.


437-438: Logging improvements enhance observability!

The changes consistently improve log messages across different scenarios:

  • Better error context for discarded data
  • Enhanced EOF and error logging
  • Improved error reporting for data dispatch and transmission
  • Clear completion logging for rx/tx queues

The log levels are appropriately chosen, and the context provided will aid in debugging.

Also applies to: 459-461, 469-472, 484-487, 495-497, 521-525, 534-536, 543-546

hoprd/rest-api/src/session.rs (3)

Line range hint 443-449: TCP socket binding and error handling are correctly implemented.

The code correctly binds the TCP socket and appropriately handles errors, ensuring that specific issues like AddrInUse are distinctly managed.


456-457: Added comments enhance code readability.

The new comments clearly describe the process of handling incoming TCP connections, improving the maintainability of the code.


718-718: Logging unusable listen addresses enhances debugging.

Logging the errors when a listen address is not usable provides valuable information for troubleshooting without interrupting the binding attempts.

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.

crate version bump missing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
crate:hoprd-api dependencies Pull requests that update a dependency file
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants