Skip to content

RHINENG-30154: close HTTP response bodies after retries - #2313

Merged
swadeley merged 2 commits into
RedHatInsights:masterfrom
swadeley:RHINENG-30154-close-http-bodies
Aug 21, 2026
Merged

RHINENG-30154: close HTTP response bodies after retries#2313
swadeley merged 2 commits into
RedHatInsights:masterfrom
swadeley:RHINENG-30154-close-http-bodies

Conversation

@swadeley

@swadeley swadeley commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

HTTPCallRetry discarded response bodies on success and retry, so Candlepin calls from patchman-listener leaked TCP sockets until the pod restarted (RHINENG-30154). Close and drain the body on every retry path, and close S3 yum-update responses on error as well.

Test plan

  • go test ./base/utils/ -run TestHTTPCallRetry
  • Confirm listener still assigns templates via Candlepin in a local/dev upload
  • After deploy, node_sockstat_TCP_mem on listener nodes stays flat instead of climbing ~7k pages/hour

Secure Coding Practices Checklist GitHub Link

Secure Coding Checklist

  • Input Validation
  • Output Encoding
  • Authentication and Password Management
  • Session Management
  • Access Control
  • Cryptographic Practices
  • Error Handling and Logging
  • Data Protection
  • Communication Security
  • System Configuration
  • Database Security
  • File Management
  • Memory Management
  • General Coding Practices

Made with Cursor

Summary by Sourcery

Close HTTP response bodies consistently to prevent socket leaks in retrying API calls and S3 yum-update requests.

Bug Fixes:

  • Prevent HTTP response bodies from leaking connections by draining and closing them across successful, retryable, and failed request paths.
  • Ensure S3 yum-update response bodies are closed even when the request returns an error.

Enhancements:

  • Centralize bounded response-body draining and closing to support connection reuse without reading arbitrarily large payloads.

Tests:

  • Add coverage for response-body closure on success, retries, non-retryable errors, and bounded draining.

HTTPCallRetry discarded responses without closing the body on success
and retry, leaking TCP sockets from listener Candlepin calls.

Co-authored-by: Cursor <cursoragent@cursor.com>
@swadeley
swadeley requested a review from a team as a code owner August 21, 2026 08:20
@sourcery-ai

sourcery-ai Bot commented Aug 21, 2026

Copy link
Copy Markdown

Reviewer's Guide

Ensure all HTTP responses used in HTTPCallRetry and yum-update S3 requests are drained and closed to prevent leaking TCP connections, and add targeted tests to verify body draining and closure behavior in all retry paths.

File-Level Changes

Change Details Files
Refine HTTPCallRetry to always drain and close HTTP response bodies across success, retry, and error paths to avoid leaking connections.
  • Add maxHTTPResponseDrain constant and closeHTTPResponse helper that drains up to a fixed limit before closing the body
  • Invoke closeHTTPResponse on retryable status codes before looping to the next attempt
  • Invoke closeHTTPResponse on successful HTTP calls before returning data
  • Invoke closeHTTPResponse when no retry codes are specified but the call errors and will be retried
  • Invoke closeHTTPResponse on non-retryable errors before returning a wrapped error
base/utils/http.go
Introduce test utilities and unit tests to validate draining/closing semantics of HTTPCallRetry and closeHTTPResponse, including drain-size limits.
  • Implement closeTrackingBody helper to track bytes read and closed state of response bodies
  • Add trackingResponse and assertBodyDrainedAndClosed helpers for concise HTTP response tests
  • Add tests covering success, retryable status, non-retryable error paths, and closeHTTPResponse drain/limit behavior
base/utils/http_test.go
Ensure yum-update S3 HTTP responses are always closed, including error paths, without failing the call if close itself errors.
  • Wrap yum-updates S3 request body close in a nil-safe deferred function
  • Log but do not propagate errors from closing the yum-updates response body
  • Remove previous immediate close that wrapped close errors as response errors
listener/upload.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • In closeHTTPResponse, io.Copy(io.Discard, resp.Body) will read the entire body even for very large responses; consider either limiting the number of bytes drained (e.g., via io.LimitReader) or only draining when you know the body is small to avoid unnecessary memory and bandwidth use.
  • The new defer resp.Body.Close() in getYumUpdates drops the previous error wrapping around resp.Body.Close; if close errors are meaningful in this context, consider at least logging them so they’re not silently ignored.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `closeHTTPResponse`, `io.Copy(io.Discard, resp.Body)` will read the entire body even for very large responses; consider either limiting the number of bytes drained (e.g., via `io.LimitReader`) or only draining when you know the body is small to avoid unnecessary memory and bandwidth use.
- The new `defer resp.Body.Close()` in `getYumUpdates` drops the previous error wrapping around `resp.Body.Close`; if close errors are meaningful in this context, consider at least logging them so they’re not silently ignored.

## Individual Comments

### Comment 1
<location path="base/utils/http_test.go" line_range="14-16" />
<code_context>
 	"github.com/stretchr/testify/assert"
 )

+type closeTrackingBody struct {
+	io.Reader
+	closed atomic.Bool
+}
+
</code_context>
<issue_to_address>
**suggestion (testing):** Track that the response body is actually drained, not just closed

Since `closeHTTPResponse` now drains the body with `io.Copy(io.Discard, resp.Body)`, this helper should also verify that behavior, not just that `Close` was called. Please extend it (or add another helper) to track `Read` calls or bytes read, and add a test assertion that the body is fully consumed before it is closed, to prevent regressions that skip draining.

Suggested implementation:

```golang
type closeTrackingBody struct {
	rc        io.ReadCloser
	readBytes int64
	closed    atomic.Bool
}

func newCloseTrackingBody(rc io.ReadCloser) *closeTrackingBody {
	return &closeTrackingBody{rc: rc}
}

func (b *closeTrackingBody) Read(p []byte) (int, error) {
	n, err := b.rc.Read(p)
	if n > 0 {
		atomic.AddInt64(&b.readBytes, int64(n))
	}
	return n, err
}

func (b *closeTrackingBody) Close() error {
	b.closed.Store(true)
	return b.rc.Close()
}

func (b *closeTrackingBody) BytesRead() int64 {
	return atomic.LoadInt64(&b.readBytes)
}

func (b *closeTrackingBody) Closed() bool {
	return b.closed.Load()
}

```

To fully enforce and test drain-before-close behavior, you should also:

1. Update the test that currently uses `closeTrackingBody` (presumably the test for `closeHTTPResponse`) to:
   - Wrap the body:  
     `bodyContent := "some body data"`  
     `body := newCloseTrackingBody(io.NopCloser(strings.NewReader(bodyContent)))`
   - Construct the response with `Body: body`.
   - Call `closeHTTPResponse(resp)`.
   - Assert:
     - `assert.True(t, body.Closed())`
     - `assert.Equal(t, int64(len(bodyContent)), body.BytesRead())`
2. If there are multiple tests for `closeHTTPResponse`, ensure each one uses `newCloseTrackingBody` and asserts that the full body length was read before or by the time it is closed, to prevent regressions where draining is skipped.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread base/utils/http_test.go Outdated
@codecov-commenter

codecov-commenter commented Aug 21, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.61538% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.03%. Comparing base (25a7324) to head (a9dabb2).

Files with missing lines Patch % Lines
listener/upload.go 50.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2313      +/-   ##
==========================================
+ Coverage   58.83%   59.03%   +0.20%     
==========================================
  Files         150      150              
  Lines        9605     9614       +9     
==========================================
+ Hits         5651     5676      +25     
+ Misses       3360     3344      -16     
  Partials      594      594              
Flag Coverage Δ
unittests 59.03% <84.61%> (+0.20%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

MichaelMraka
MichaelMraka previously approved these changes Aug 21, 2026
Unbounded io.Copy could read huge leftover bodies; cap the drain at
net/http's reuse limit and log yum-update Body.Close failures.

Co-authored-by: Cursor <cursoragent@cursor.com>
@swadeley

Copy link
Copy Markdown
Contributor Author

Hi @MichaelMraka , sorry, just pushed changes to address sourcery-ai feedback

Can you re-ACK when sourcery-ai completes its next review ?

Thank you

@swadeley

Copy link
Copy Markdown
Contributor Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@swadeley
swadeley requested a review from MichaelMraka August 21, 2026 08:42
@swadeley
swadeley merged commit c74c957 into RedHatInsights:master Aug 21, 2026
8 checks passed
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.

3 participants