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

Don't poll for disconnects in BaseHTTPMiddleware via StreamingResponse #2620

Merged
merged 12 commits into from
Sep 1, 2024

Conversation

adriangb
Copy link
Member

Fixes #2516

@mikkelduif
Copy link
Contributor

I can confirm that this PR fixes the example I have reproduced in #2516 (comment)

@adriangb adriangb requested a review from Kludex June 13, 2024 20:57
@mikkelduif
Copy link
Contributor

I do still recommend you avoid BaseHTTPMiddleware

Maybe we should consider to add a section to: https://www.starlette.io/middleware/#basehttpmiddleware emphasising this.
I do not know the exact technicalities for this, however, it might help future users to avoid it.

@adriangb
Copy link
Member Author

adriangb commented Jun 14, 2024

Seems like the issue now is coverage in tests (all of the tests still pass). There are several pieces of test code that are not not being hit but I'm not sure if they were essential or just an implementation detail, some more careful evaluation is needed.

@avihaiyosef
Copy link

@adriangb, what is the status of this PR?

@dlahyani
Copy link

dlahyani commented Aug 4, 2024

Hi @adriangb , thanks for this fix.
Any expectation on when this is going to land in a new release of starlette?

@Kludex
Copy link
Sponsor Member

Kludex commented Aug 4, 2024

This PR needs someone motivated to check why the coverage dropped.

Anyone that uses BaseHTTPMiddleware in their company, and wants to spend some engineers hours working on this, is welcome.

Otherwise, you can try to sponsor @adriangb as an appreciation gesture for his efforts here, and maybe motivate him to continue the work here.

@isidentical
Copy link

@Kludex thanks for the reminder to sponsor, @adriangb has been doing amazing work and we just hit an issue that might be related to this PR so we just started sponsoring (albeit modestly) thru github!!! Would highly recommend anyone else to do the same.

@adriangb
Copy link
Member Author

@Kludex I looked into the coverage.

Basically before we were using StreamingResponse which calls receive() to check for disconnection.
Since I changed this to use a similar implementation but one that does not check for disconnection receive() is no longer called.

For example, if I check out master and apply the changes to test_base.py I get the following traceback:

tests/middleware/test_base.py:776: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
starlette/middleware/base.py:189: in __call__
    with collapse_excgroups():
../../.pyenv/versions/3.12.2/lib/python3.12/contextlib.py:158: in __exit__
    self.gen.throw(value)
starlette/_utils.py:89: in collapse_excgroups
    raise exc
starlette/responses.py:265: in __call__
    await wrap(partial(self.listen_for_disconnect, receive))
starlette/responses.py:261: in wrap
    await func()
starlette/responses.py:238: in listen_for_disconnect
    message = await receive()
starlette/middleware/base.py:54: in wrapped_receive
    msg = await self.receive()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

    async def rcv() -> AsyncGenerator[Message, None]:
        yield {"type": "http.request", "body": b"1", "more_body": True}
        yield {"type": "http.request", "body": b"2", "more_body": True}
        yield {"type": "http.request", "body": b"3"}
>       raise AssertionError(  # pragma: no cover
            "Should not be called, no need to poll for disconnect"
        )
E       AssertionError: Should not be called, no need to poll for disconnect

@adriangb
Copy link
Member Author

@Kludex thanks for the reminder to sponsor, @adriangb has been doing amazing work and we just hit an issue that might be related to this PR so we just started sponsoring (albeit modestly) thru github!!! Would highly recommend anyone else to do the same.

Thank you for your sponsorship!

@hakanutku
Copy link

@Kludex Could you please review this PR when you get a chance? I appreciate your time!

@Kludex
Copy link
Sponsor Member

Kludex commented Aug 22, 2024

I'm a bit tired of people asking me stuff.

I'm very dedicated to the projects I maintain, which means people just need to wait a bit. I don't like people pressuring me to review stuff.

You want to motivate me to check this PR? Feel free to sponsor me. Otherwise, wait for me to voluntarily come here and review it.

Too many issues regarding BaseHTTPMiddleware, and I need to check previous work and make sure this is fine. It takes time.

@Kludex Kludex merged commit d771bb7 into master Sep 1, 2024
12 checks passed
@Kludex Kludex deleted the fix-middleware-stacking branch September 1, 2024 07:04
christophe-papazian added a commit to DataDog/dd-trace-py that referenced this pull request Sep 3, 2024
Fix and enable again starlette tests that were disabled.
Reason of the bug:
- starlette was fixed in 0.38.3 for an issue that was causing trouble in
our appsec instrumentation. Tests were upgraded accordingly

Fix: 
encode/starlette#2620
Issue:
encode/starlette#2516


Also improve the guards in the asgi middleware appsec instrumentation
for request body to ensure that we never break.

## Checklist
- [x] PR author has checked that all the criteria below are met
- The PR description includes an overview of the change
- The PR description articulates the motivation for the change
- The change includes tests OR the PR description describes a testing
strategy
- The PR description notes risks associated with the change, if any
- Newly-added code is easy to change
- The change follows the [library release note
guidelines](https://ddtrace.readthedocs.io/en/stable/releasenotes.html)
- The change includes or references documentation updates if necessary
- Backport labels are set (if
[applicable](https://ddtrace.readthedocs.io/en/latest/contributing.html#backporting))

## Reviewer Checklist
- [x] Reviewer has checked that all the criteria below are met 
- Title is accurate
- All changes are related to the pull request's stated goal
- Avoids breaking
[API](https://ddtrace.readthedocs.io/en/stable/versioning.html#interfaces)
changes
- Testing strategy adequately addresses listed risks
- Newly-added code is easy to change
- Release note makes sense to a user of the library
- If necessary, author has acknowledged and discussed the performance
implications of this PR as reported in the benchmarks PR comment
- Backport labels are set in a manner that is consistent with the
[release branch maintenance
policy](https://ddtrace.readthedocs.io/en/latest/contributing.html#backporting)
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,

Choose a reason for hiding this comment

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

is the removal of background here intentional? We use background for both actual background tasks but also to detect when a streaming request was cancelled by the client (request.is_disconnected had some minor overhead).

Choose a reason for hiding this comment

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

Cutting a PR for this

Choose a reason for hiding this comment

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

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.

RuntimeError("No response returned") in BaseHTTPMiddleware
9 participants