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

[otelfiber] fix: when body is stream middleware read everything into memory first, no streaming to client #932

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

Conversation

Alantoo
Copy link

@Alantoo Alantoo commented Jan 29, 2024

Bug Description
When application stream some file middleware reads all the streamed data into the memory to calculate response size which can consume all the available memory.

How to Reproduce
Steps to reproduce the behavior:

  • Stream some binary data from handler

Expected Behavior
The middleware should skip response/request body size calculation when body is stream

Summary by CodeRabbit

  • New Features
    • Enhanced request and response body size handling, including stream management for improved performance and resource utilization.
  • Tests
    • Implemented new tests for streaming response body functionalities to ensure reliability and efficiency.

@github-actions github-actions bot added the ☢️ Bug Something isn't working label Jan 29, 2024
@ReneWerner87 ReneWerner87 changed the title fix: when body is stream middleware read everything into memory first, no streaming to client [otelfiber] fix: when body is stream middleware read everything into memory first, no streaming to client Jan 29, 2024
@ReneWerner87
Copy link
Member

@Alantoo could you pls provide a unittest for this case?

@ReneWerner87
Copy link
Member

@Alantoo friendly ping

Copy link
Contributor

coderabbitai bot commented Mar 5, 2024

Walkthrough

The recent modifications introduce enhancements in handling request and response body sizes, particularly focusing on stream handling. This includes the introduction of a new struct for reading body stream sizes and improvements in testing capabilities for streamed response bodies by implementing a fake file interface and its concrete counterpart.

Changes

File(s) Summary
otelfiber/fiber.go - Added import for github.com/valyala/fasthttp and io
- Added bodyStreamSizeReader struct and Read method
- Modified handling of request and response body sizes, including stream handling
otelfiber/otelfiber_test/fiber_test.go - Added a new fakeFile interface and its implementation fakeFileImpl with a Read method for streaming response body testing in the TestStreamedResponseBody function

🐇✨
In the realm of code, where streams do flow,
A rabbit hopped, with changes in tow.
"Let's measure," it said, "the size of the stream,
And test with a fake, a coder's dream."
With a hop and a skip, improvements were sown,
In the land of the fibers, where speed is grown.
🚀📈

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>.
    • Generate unit-tests 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 tests 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 8f79f35 and 391cb9c.
Files selected for processing (2)
  • otelfiber/fiber.go (6 hunks)
  • otelfiber/otelfiber_test/fiber_test.go (2 hunks)
Additional comments: 7
otelfiber/fiber.go (5)
  • 5-6: The addition of imports for github.com/valyala/fasthttp and io is appropriate given the context of the changes. These imports are necessary for the new functionality introduced to handle streamed data more efficiently.
  • 36-55: The introduction of the bodyStreamSizeReader struct and its Read method is a key part of the solution to handle streamed data without excessive memory consumption. This implementation correctly adheres to the io.Reader interface, ensuring compatibility and proper functionality within the Go ecosystem. The method's logic to record the histogram upon reaching EOF is a clever way to measure the streamed data size without reading it entirely into memory. However, it's important to ensure that the histogram.Record method is thread-safe if Read can be called concurrently.
  • 164-181: The logic to handle request bodies that are streams is correctly implemented by checking request.IsBodyStream(). Creating a copy of the request and setting the body stream to an instance of bodyStreamSizeReader is a smart approach to integrate the new streaming handling mechanism. However, it's crucial to ensure that the CopyTo method and the SetBodyStream method do not introduce any side effects or memory leaks, especially in long-running applications. Additionally, setting the body length to -1 in SetBodyStream correctly indicates an unknown length, aligning with the streaming context.
  • 183-199: Similar to the request handling, the logic for response bodies follows the same pattern and correctly checks if the body is a stream. The use of bodyStreamSizeReader for the response stream and the careful handling of copying the response to avoid issues with closed streams are well thought out. Again, it's important to verify the absence of side effects or memory leaks with the CopyTo and SetBodyStream methods in this context as well.
  • 209-215: The conditional recording of request and response sizes based on whether they are streams or not is a good practice. It ensures that the middleware does not attempt to calculate the size of streamed data, aligning with the PR's objectives. This approach effectively addresses the issue of excessive memory consumption when handling large streamed data. It's essential to ensure that the metrics recorded here accurately reflect the actual sizes for non-streamed data and that the absence of size recording for streamed data is documented and understood by users of the middleware.
otelfiber/otelfiber_test/fiber_test.go (2)
  • 450-483: The introduction of the fakeFile interface and its implementation fakeFileImpl is a strategic addition for testing the middleware's handling of streamed response bodies. The Read method's logic, simulating a finite stream of data, is well-designed for testing purposes. It's important to ensure that the test adequately covers various scenarios, including partial reads and reaching EOF, to fully validate the middleware's behavior with streamed data. Additionally, resetting f.done and f.pos upon reaching EOF might not be necessary unless the intention is to reuse the fakeFileImpl instance in multiple reads, which is not typical for most streaming use cases.
  • 485-525: The TestStreamedResponseBody function is a crucial addition to the test suite, ensuring that the middleware's new behavior with streamed response bodies is correctly implemented. The use of fakeFileImpl to simulate a streamed response and the validation of the recorded metrics for the response size are well-executed. It's important to ensure comprehensive coverage by including tests for various stream sizes and potential edge cases, such as empty streams or streams that trigger multiple reads. Additionally, verifying that no unexpected metrics are recorded and that the middleware's behavior remains consistent across different streaming scenarios would strengthen the test suite.

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 391cb9c and 19642fb.
Files selected for processing (2)
  • otelfiber/fiber.go (6 hunks)
  • otelfiber/otelfiber_test/fiber_test.go (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • otelfiber/fiber.go
  • otelfiber/otelfiber_test/fiber_test.go

@Alantoo
Copy link
Author

Alantoo commented Mar 5, 2024

@Alantoo friendly ping

Hey. Sorry for long delay. Unfortunately had no time to work on it. I've pushed test to make sure response size computed in lazy way correctly. Please let me know if its fine or I should fix anything else.
Thank you

@ReneWerner87
Copy link
Member

@Alantoo pls fix this
image

@ReneWerner87
Copy link
Member

@Alantoo
image

but we still support go 1.19.x

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.

2 participants