Skip to content

Fix potential goroutine leak in httpreqresp.Do function#16691

Closed
Copilot wants to merge 1 commit intomainfrom
copilot/fix-16665
Closed

Fix potential goroutine leak in httpreqresp.Do function#16691
Copilot wants to merge 1 commit intomainfrom
copilot/fix-16665

Conversation

Copy link
Contributor

Copilot AI commented Aug 16, 2025

The Do function in cl/sentinel/httpreqresp/server.go had a potential goroutine leak due to an unbuffered channel. When the request context was cancelled before the HTTP handler completed, the goroutine would block indefinitely on ans <- resp because no receiver was available.

Root Cause:

func Do(handler http.Handler, r *http.Request) (*http.Response, error) {
    ans := make(chan *http.Response)  // Unbuffered channel
    go func() {
        // ... handler processing ...
        ans <- resp  // Blocks forever if context cancelled first
    }()
    select {
    case res := <-ans:
        return res, nil
    case <-r.Context().Done():
        return nil, r.Context().Err()  // No one left to receive from ans
    }
}

Solution:
Changed the channel to be buffered with capacity 1:

ans := make(chan *http.Response, 1)

This allows the goroutine to send its response without blocking, even when the context cancellation case wins the race condition. The goroutine can complete normally and be garbage collected.

Testing:
Added comprehensive tests in server_test.go that verify:

  • Context cancellation doesn't cause goroutine leaks
  • Normal operation continues to work correctly
  • No regression in existing functionality

The fix is minimal (adding , 1 to the channel declaration) and maintains backward compatibility while preventing resource leaks.

Fixes #16665.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copy link
Contributor Author

Copilot AI commented Aug 16, 2025

@Giulio2002 👋 This repository doesn't have Copilot instructions. With Copilot instructions, I can understand the repository better, work faster and produce higher quality PRs.

I can generate a .github/copilot-instructions.md file for you automatically. Click here to open a pre-filled issue and assign it to me. I'll write the instructions, and then tag you for review.

@Giulio2002 Giulio2002 closed this Aug 16, 2025
Copilot AI changed the title [WIP] Potential Goroutine Leak Due to Unbuffered Channel Fix potential goroutine leak in httpreqresp.Do function Aug 16, 2025
Copilot AI requested a review from Giulio2002 August 16, 2025 14:35
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.

Potential Goroutine Leak Due to Unbuffered Channel

2 participants