Skip to content

fix(router): netPoll handle wss *tls.Conn type #1843

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

agufagit
Copy link

@agufagit agufagit commented May 8, 2025

fix #1838

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of secure (TLS) websocket connections to ensure reliable connection management and event polling.

@github-actions github-actions bot added the router label May 8, 2025
@StarpTech
Copy link
Contributor

HI @agufagit, thanks for your contribution. We'll review it soon.

@jensneuse jensneuse requested a review from Copilot May 22, 2025 07:16
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes #1838 by ensuring that TLS connections are correctly unwrapped before being passed to the net poller. Key changes include handling *tls.Conn types in addConnection, removeConnection, and socketFd, which unifies the connection handling logic for both plain and TLS connections.

Comment on lines +480 to +483
if con, ok := conn.(*tls.Conn); ok {
netConn := con.NetConn()
return h.netPoll.Add(netConn)
}
Copy link
Preview

Copilot AI May 22, 2025

Choose a reason for hiding this comment

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

[nitpick] The logic to unwrap TLS connections is repeated in addConnection, removeConnection, and socketFd. Consider extracting this logic into a helper function to reduce duplication and improve maintainability.

Suggested change
if con, ok := conn.(*tls.Conn); ok {
netConn := con.NetConn()
return h.netPoll.Add(netConn)
}
conn = unwrapTLSConn(conn)

Copilot uses AI. Check for mistakes.

Copy link

github-actions bot commented Jun 6, 2025

This PR was marked stale due to lack of activity. It will be closed in 14 days.

@github-actions github-actions bot added the Stale label Jun 6, 2025
@StarpTech StarpTech removed the Stale label Jun 6, 2025
@endigma
Copy link
Member

endigma commented Jun 6, 2025

Hi @agufagit, can you rebase/merge in main and add a test to show what this fixes?

Also, for once in my life, the Copilot review suggestion is actually pretty good, I would suggest extracting the reused unwrap function and just calling Add/Remove once

@endigma endigma self-requested a review June 6, 2025 13:25
@endigma endigma removed their request for review June 18, 2025 10:46
@endigma
Copy link
Member

endigma commented Jun 18, 2025

Hi @agufagit, I'm unfollowing this for now, feel free to comment on this issue if you intend to make it ready for merge.

Copy link

github-actions bot commented Jul 3, 2025

This PR was marked stale due to lack of activity. It will be closed in 14 days.

@github-actions github-actions bot added the Stale label Jul 3, 2025
Copy link

coderabbitai bot commented Jul 3, 2025

Walkthrough

The changes update internal connection management in the WebsocketHandler to correctly handle TLS-wrapped connections. Methods for adding, removing, and retrieving socket file descriptors now unwrap *tls.Conn to operate on the underlying raw connection, ensuring proper integration with the net poller and correct socket identification for wss (TLS) connections.

Changes

Files Change Summary
router/core/websocket.go Updated addConnection, removeConnection, and socketFd to unwrap *tls.Conn for net poller.

Assessment against linked issues

Objective Addressed Explanation
Properly handle *tls.Conn in socketFd, addConnection, and removeConnection (Issue #1838)
Ensure net poller operates on underlying connection, not TLS wrapper (Issue #1838)
Enable successful wss connection establishment by fixing fd retrieval (Issue #1838)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

@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 comments (1)
router/core/websocket.go (1)

475-519: Add unit tests for TLS‐aware connection handling

We need explicit unit tests in router/core to cover how WebsocketHandler and socketFd unwrap and handle *tls.Conn. None of the existing integration tests exercise the internal net-poller logic for TLS connections.

Please add a new test file (for example, router/core/websocket_tls_test.go) with tests that:

  • Verify socketFd(conn) unwraps a *tls.Conn and returns the underlying file descriptor, and returns 0 on errors.
  • Stub or mock a netPoll implementation to record calls, then exercise WebsocketHandler.addConnection with both plain net.Conn and wrapped *tls.Conn, asserting that netPoll.Add() is invoked with the unwrapped net.Conn.
  • Likewise, call WebsocketHandler.removeConnection and assert netPoll.Remove() is passed the correct connection instance for both plain and TLS-wrapped net.Conn.

Target router/core/websocket.go around lines 475–519. This will ensure our TLS unwrapping fix is covered and prevent regressions.

♻️ Duplicate comments (2)
router/core/websocket.go (2)

475-478: Extract TLS unwrapping logic to reduce code duplication.

The TLS connection unwrapping logic is repeated across multiple methods. As suggested in the previous review, consider extracting this into a helper function.

Apply this refactor to reduce duplication:

+// unwrapTLSConn unwraps a TLS connection to get the underlying network connection
+func unwrapTLSConn(conn net.Conn) net.Conn {
+	if tlsConn, ok := conn.(*tls.Conn); ok {
+		return tlsConn.NetConn()
+	}
+	return conn
+}
+
 func (h *WebsocketHandler) addConnection(conn net.Conn, handler *WebSocketConnectionHandler) error {
 	h.stats.ConnectionsInc()
 	h.connectionsMu.Lock()
 	defer h.connectionsMu.Unlock()
 	fd := socketFd(conn)
 	if fd == 0 {
 		return fmt.Errorf("unable to get socket fd for conn: %d", handler.connectionID)
 	}
 	h.connections[fd] = handler
-	if con, ok := conn.(*tls.Conn); ok {
-		netConn := con.NetConn()
-		return h.netPoll.Add(netConn)
-	}
-	return h.netPoll.Add(conn)
+	return h.netPoll.Add(unwrapTLSConn(conn))
 }

488-494: Update removeConnection to use the extracted helper function.

Once the unwrapTLSConn helper function is implemented, this method should also use it for consistency.

 func (h *WebsocketHandler) removeConnection(conn net.Conn, handler *WebSocketConnectionHandler, fd int) {
 	h.stats.ConnectionsDec()
 	h.connectionsMu.Lock()
 	delete(h.connections, fd)
 	h.connectionsMu.Unlock()
-
-	var err error
-	if con, ok := conn.(*tls.Conn); ok {
-		netConn := con.NetConn()
-		err = h.netPoll.Remove(netConn)
-	} else {
-		err = h.netPoll.Remove(conn)
-	}
+	err := h.netPoll.Remove(unwrapTLSConn(conn))
 	if err != nil {
 		h.logger.Warn("Removing connection from net poller", zap.Error(err))
 	}
 	handler.Close(true)
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 81a0880 and 9842358.

📒 Files selected for processing (1)
  • router/core/websocket.go (4 hunks)
🔇 Additional comments (1)
router/core/websocket.go (1)

6-6: LGTM: TLS import added appropriately.

The crypto/tls import is correctly added to support TLS connection handling throughout the file.

Comment on lines +516 to +519
if con, ok := conn.(*tls.Conn); ok {
netConn := con.NetConn()
return socketFd(netConn)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update socketFd to use the extracted helper function.

The recursive TLS unwrapping logic here can also benefit from the helper function, though it needs to handle the recursive case.

 func socketFd(conn net.Conn) int {
 	if con, ok := conn.(syscall.Conn); ok {
 		raw, err := con.SyscallConn()
 		if err != nil {
 			return 0
 		}
 		sfd := 0
 		_ = raw.Control(func(fd uintptr) {
 			sfd = int(fd)
 		})
 		return sfd
 	}
 	if con, ok := conn.(netpoll.ConnImpl); ok {
 		return con.GetFD()
 	}
-	if con, ok := conn.(*tls.Conn); ok {
-		netConn := con.NetConn()
-		return socketFd(netConn)
-	}
+	if _, ok := conn.(*tls.Conn); ok {
+		return socketFd(unwrapTLSConn(conn))
+	}
 	return 0
 }
📝 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
if con, ok := conn.(*tls.Conn); ok {
netConn := con.NetConn()
return socketFd(netConn)
}
func socketFd(conn net.Conn) int {
if con, ok := conn.(syscall.Conn); ok {
raw, err := con.SyscallConn()
if err != nil {
return 0
}
sfd := 0
_ = raw.Control(func(fd uintptr) {
sfd = int(fd)
})
return sfd
}
if con, ok := conn.(netpoll.ConnImpl); ok {
return con.GetFD()
}
if _, ok := conn.(*tls.Conn); ok {
return socketFd(unwrapTLSConn(conn))
}
return 0
}
🤖 Prompt for AI Agents
In router/core/websocket.go around lines 516 to 519, the code unwraps a TLS
connection but does not use the existing helper function designed for recursive
TLS unwrapping. Refactor this block to call the helper function that handles
recursive unwrapping of TLS connections, ensuring that the socket file
descriptor is obtained correctly even if multiple layers of TLS wrapping exist.

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.

wss connection error "unable to get socket fd for conn"
4 participants