Skip to content
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

Print the response's body on demand for debugging purposes #276

Merged
merged 12 commits into from
Jan 24, 2025

Conversation

shackra
Copy link
Contributor

@shackra shackra commented Dec 28, 2024

This PR adds debugging functionality that displays the response's body as it arrives to us, not immediately, but when reading it.

Example:

# assume baton-random-connector is a connector that expects a JSON response
BATON_DEBUG_PRINT_RESPONSE_BODY=yes baton-random-connector
# * prints out the response body when read *

The uhttp.WithJSONResponse(&target) option on .Do would trigger a read, and we would see what was read on the console.

Summary by CodeRabbit

  • New Features
    • Introduced a debugging option to log HTTP response bodies.
  • Improvements
    • Enhanced HTTP client with configurable response body logging via environment variable.
    • Provides a flexible way to enable/disable response body debugging.
  • Debugging
    • New capability to inspect HTTP response contents during development.
  • Documentation
    • Updated linter settings to improve error handling practices.
    • Added requirements for explanations on nolint directives.
  • Code Organization
    • Simplified visibility of the ErrSyncNotComplete variable.
    • Updated comments for clarity in the SyncGrantExpansion method.

@shackra shackra requested a review from jirwin as a code owner December 28, 2024 08:01
Copy link

coderabbitai bot commented Dec 28, 2024

Warning

Rate limit exceeded

@shackra has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 20 minutes and 38 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 0017a64 and e9a3deb.

📒 Files selected for processing (1)
  • pkg/uhttp/wrapper.go (6 hunks)

Walkthrough

The changes introduce a debugging facility for HTTP request responses in the uhttp package. A new type, printReader, is implemented to log the body of HTTP responses as they are read. The BaseHttpClient is modified to conditionally wrap the response body with printReader based on an environment variable. Additionally, updates to the linter configuration enhance error handling practices by adding exemptions and requiring justifications for suppressed warnings. The syncer.go file sees minor adjustments to variable declarations and comments.

Changes

File Change Summary
pkg/uhttp/body_print.go - Added printReader struct to wrap and log reader contents
- Implemented wrapPrintBody function to create logged reader
pkg/uhttp/wrapper.go - Added environment variable check for BATON_DEBUG_PRINT_RESPONSE_BODY to conditionally wrap response body
.golangci.yml - Updated unhandled-error rule in revive linter to include fmt.Fprint
- Adjusted nolintlint settings to require explanations for nolint directives
pkg/sync/syncer.go - Updated ErrSyncNotComplete variable declaration to standalone
- Minor comment update for SyncGrantExpansion method

Poem

🐰 Debugging Bunny's HTTP Delight
Hop through responses, byte by byte,
Logging secrets with rabbit might,
Print the body, reveal the trace,
With WithPrintBody, we embrace
The power of seeing what's in flight! 🌈


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. (Beta)
  • @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.

@shackra shackra requested review from ggreer and removed request for jirwin December 28, 2024 08:02
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

🧹 Nitpick comments (7)
pkg/uhttp/body_print.go (5)

3-7: Consider using more neutral documentation.

The playful and suggestive wording may be fun in a testing or internal environment, but for production use, consider more neutral phrasing to maintain a professional tone.


20-21: Performance overhead from chunk-by-chunk logging.

You're logging the response in each Read call, which might degrade performance for large or heavily chunked responses. Consider buffering the read data and printing it only once.


27-29: Nil-check the input reader.

While it's uncommon, a nil reader might cause unexpected panics. Consider adding a guard clause to ensure body is non-nil.

 func wrapBodyToUndress(body io.Reader) io.Reader {
+   if body == nil {
+       return nil
+   }
    return &printReader{reader: body}
 }

31-33: Naming clarity for undressOption.

While the term "undress" appears playful, a name like debugBodyOption or printBodyOption might be clearer for new or external contributors.


39-41: Add documentation for WithUndressBody.

Briefly explain that enabling this option can log the response body for debugging purposes. This helps consumers fully understand the parameter's effect.

pkg/uhttp/wrapper.go (2)

97-97: Flag naming aligns with the code but lacks doc comments.

Add a doc comment above debugPrintBody to clarify its purpose (to wrap and log the HTTP response body).


345-349: Consider partial logging to prevent large memory usage and PII risk.

Even though io.ReadAll is used to read the body into memory, be aware of potential large responses. Consider:

  1. Using a limited reader before wrapping the body.
  2. Or logging only the first N bytes to prevent excessive memory usage.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0c9a018 and c4af553.

📒 Files selected for processing (2)
  • pkg/uhttp/body_print.go (1 hunks)
  • pkg/uhttp/wrapper.go (2 hunks)
🔇 Additional comments (1)
pkg/uhttp/body_print.go (1)

35-37: Simplify or validate the flag assignment.

The assignment is straightforward. Optionally, check if the client has a non-nil reference before setting fields.

pkg/uhttp/body_print.go Outdated Show resolved Hide resolved
pkg/uhttp/body_print.go Outdated Show resolved Hide resolved
pkg/uhttp/body_print.go Outdated Show resolved Hide resolved
pkg/uhttp/body_print.go Outdated Show resolved Hide resolved
@shackra
Copy link
Contributor Author

shackra commented Dec 30, 2024 via email

@shackra shackra changed the title 💋 Undress the response's body 🙈 Print the response's body on demand for debugging purposes Jan 2, 2025
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

🧹 Nitpick comments (3)
pkg/uhttp/body_print.go (3)

13-27: Add documentation and consider buffering output.

The implementation looks good but could be improved:

  1. Add documentation for the type and Read method
  2. Consider using a buffered writer to prevent interleaved output in concurrent scenarios
+// printReader wraps an io.Reader and prints its contents to stdout while reading.
+// This type is intended for development debugging only.
 type printReader struct {
 	reader io.Reader
 }
 
+// Read implements io.Reader interface, printing the read contents to stdout.
+// If printing fails, the error is combined with any read error using errors.Join.
 func (pr *printReader) Read(p []byte) (int, error) {

29-31: Add documentation for the helper function.

The implementation is correct, but needs documentation to explain its purpose and usage.

+// wrapPrintBody wraps the given io.Reader with a printReader that outputs
+// the read contents to stdout. For development debugging only.
 func wrapPrintBody(body io.Reader) io.Reader {

33-43: Consider using environment variable for debug control.

As suggested in previous reviews, using an environment variable instead of a WrapperOption might be safer to prevent accidentally committing debug code to production.

Example implementation:

-type printBodyOption struct {
-	debugPrintBody bool
-}
-
-func (o printBodyOption) Apply(c *BaseHttpClient) {
-	c.debugPrintBody = o.debugPrintBody
-}
-
-func WithPrintBody(shouldPrint bool) WrapperOption {
-	return printBodyOption{debugPrintBody: shouldPrint}
-}
+// Environment variable to control response body printing
+const envDebugPrintBody = "BATON_DEBUG_PRINT_BODY"
+
+// isDebugPrintBodyEnabled returns true if response body printing is enabled via
+// environment variable BATON_DEBUG_PRINT_BODY=1
+func isDebugPrintBodyEnabled() bool {
+	return os.Getenv(envDebugPrintBody) == "1"
+}

This approach:

  1. Prevents debug code from being accidentally committed
  2. Follows standard practice for debug flags
  3. Makes it clearer this is a development-only feature
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 07ff8f6 and 8b19aab.

📒 Files selected for processing (1)
  • pkg/uhttp/body_print.go (1 hunks)
🧰 Additional context used
📓 Learnings (1)
pkg/uhttp/body_print.go (1)
Learnt from: shackra
PR: ConductorOne/baton-sdk#276
File: pkg/uhttp/body_print.go:18-25
Timestamp: 2024-12-28T08:09:03.129Z
Learning: The response body printing functionality introduced in `body_print.go` is for development usage only and not intended for production, as explained by shackra in PR #276.

pkg/uhttp/body_print.go Outdated Show resolved Hide resolved
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

🧹 Nitpick comments (1)
pkg/sync/syncer.go (1)

Line range hint 972-1526: Consider splitting the grant expansion logic into a separate package.

The grant expansion logic is complex and self-contained. Moving it to a dedicated package would:

  • Improve code organization and maintainability
  • Make the logic more testable
  • Reduce the size of the syncer.go file
  • Allow for better documentation of the grant expansion concepts

This refactoring could be done in a follow-up PR to keep the current changes focused on their original purpose.

🧰 Tools
🪛 GitHub Check: go-lint

[failure] 972-972:
Comment should end in a period (godot)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b19aab and 0338465.

⛔ Files ignored due to path filters (1)
  • flake.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • .golangci.yml (1 hunks)
  • pkg/sync/syncer.go (2 hunks)
  • pkg/uhttp/body_print.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/uhttp/body_print.go
🧰 Additional context used
🪛 GitHub Check: go-lint
pkg/sync/syncer.go

[failure] 972-972:
Comment should end in a period (godot)

🔇 Additional comments (2)
pkg/sync/syncer.go (1)

36-36: LGTM! Clear and well-structured error declaration.

The standalone error declaration improves code readability and follows Go's error naming conventions.

.golangci.yml (1)

39-39: LGTM! Addition of fmt.Fprint is consistent with existing error handling exemptions.

The addition of fmt.Fprint to the unhandled-error exemption list aligns with the existing pattern of exempting fmt package's printing functions, which rarely return meaningful errors in practice.

Let's verify the usage of fmt.Fprint in the codebase to ensure it's being used appropriately:

✅ Verification successful

Verified: fmt.Fprint usage is appropriate and error handling is properly implemented

The codebase analysis shows that fmt.Fprint is used appropriately in two main contexts:

  • Debug/logging purposes (e.g., in pkg/uhttp/body_print.go for printing response bodies)
  • Standard output/error writing (e.g., in pkg/cli/commands.go)

In both cases where error handling is critical (writing to os.Stdout), proper error checking is implemented:

  • pkg/cli/commands.go: Checks and returns the error
  • pkg/uhttp/body_print.go: Joins with other errors using errors.Join

The remaining usages are in vendor dependencies where the function is used for non-critical operations like debug output or string building with bytes.Buffer (which never returns errors).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze fmt.Fprint usage patterns
# Expected: fmt.Fprint should primarily be used for debug/logging purposes

# Search for fmt.Fprint usage
echo "Analyzing fmt.Fprint usage patterns:"
rg --type go "fmt\.Fprint\(" -A 2 -B 2

# Look for any error handling of fmt.Fprint to understand current practices
echo -e "\nChecking for any existing error handling of fmt.Fprint:"
ast-grep --pattern 'if err := fmt.Fprint($$$); err != nil { $$$ }'

Length of output: 7764

pkg/sync/syncer.go Outdated Show resolved Hide resolved
@shackra shackra force-pushed the shackra/debug-print-body branch from 2bc8be3 to 267b1f1 Compare January 10, 2025 23:53
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

🧹 Nitpick comments (1)
pkg/uhttp/wrapper.go (1)

345-349: Add documentation for the debug feature.

While the implementation is clean, it would be helpful to add documentation explaining:

  1. The purpose of debugPrintBody
  2. How it affects the response handling
  3. The relationship with wrapPrintBody

Consider adding a comment block above this section:

+  // If debugPrintBody is enabled, wrap the response body with a reader that prints
+  // the contents as they are read. This is useful for debugging purposes.
   if c.debugPrintBody {
     resp.Body = io.NopCloser(wrapPrintBody(bytes.NewBuffer(body)))
   } else {
     resp.Body = io.NopCloser(bytes.NewBuffer(body))
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6b06b3b and 267b1f1.

⛔ Files ignored due to path filters (1)
  • flake.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • .golangci.yml (1 hunks)
  • pkg/sync/syncer.go (2 hunks)
  • pkg/uhttp/body_print.go (1 hunks)
  • pkg/uhttp/wrapper.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/sync/syncer.go
  • pkg/uhttp/body_print.go
🔇 Additional comments (2)
.golangci.yml (1)

39-39: LGTM! Addition of fmt.Fprint to unhandled-error exceptions is appropriate.

The addition aligns with the PR's debugging feature and follows the existing pattern for fmt package functions.

pkg/uhttp/wrapper.go (1)

94-97: LGTM! Clean addition of the debug flag.

The debugPrintBody field is appropriately placed in the BaseHttpClient struct and follows the existing field organization pattern.

pkg/uhttp/wrapper.go Outdated Show resolved Hide resolved
- Adds `BATON_DEBUG_PRINT_RESPONSE_BODY`
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

🧹 Nitpick comments (1)
pkg/uhttp/body_print.go (1)

3-13: Enhance documentation to include environment variable usage.

The documentation should be updated to reflect both methods of enabling the debug printing:

  1. Environment variable BATON_DEBUG_PRINT_RESPONSE_BODY
  2. WithPrintBody option
 // Implements a debugging facility for request responses. This changes
 // the behavior of `BaseHttpClient` with an unexported flag.
 //
 // IMPORTANT: This feature is intended for development and debugging purposes only.
 // Do not enable in production as it may expose sensitive information in logs.
 //
-// Usage:
+// Usage (Option 1 - Environment Variable):
+//   export BATON_DEBUG_PRINT_RESPONSE_BODY=true
+//   # Run your application
+//
+// Usage (Option 2 - Client Option):
 //   client := uhttp.NewBaseHttpClient(
 //     httpClient,
 //     uhttp.WithPrintBody(true), // Enable response body printing
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 267b1f1 and 0017a64.

📒 Files selected for processing (2)
  • pkg/uhttp/body_print.go (1 hunks)
  • pkg/uhttp/wrapper.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/uhttp/wrapper.go
🧰 Additional context used
📓 Learnings (1)
pkg/uhttp/body_print.go (1)
Learnt from: shackra
PR: ConductorOne/baton-sdk#276
File: pkg/uhttp/body_print.go:18-25
Timestamp: 2024-12-28T08:09:03.129Z
Learning: The response body printing functionality introduced in `body_print.go` is for development usage only and not intended for production, as explained by shackra in PR #276.
🔇 Additional comments (2)
pkg/uhttp/body_print.go (2)

22-24: LGTM! Clean and focused type definition.

The printReader type follows Go conventions and properly encapsulates the underlying reader.


38-40: LGTM! Clean factory function implementation.

The wrapPrintBody function follows Go conventions and provides a clean way to create printReader instances.

pkg/uhttp/body_print.go Show resolved Hide resolved
@shackra shackra requested a review from jirwin January 11, 2025 00:06
.golangci.yml Show resolved Hide resolved
@ggreer ggreer merged commit 03891ab into main Jan 24, 2025
4 checks passed
@ggreer ggreer deleted the shackra/debug-print-body branch January 24, 2025 18:50
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.

4 participants