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

Raise exception from background task on BaseHTTPMiddleware #2812

Open
wants to merge 7 commits into
base: master
Choose a base branch
from

Conversation

Kludex
Copy link
Member

@Kludex Kludex commented Dec 26, 2024

How to reproduce:

import asyncio
from typing import Any

from starlette.applications import Starlette
from starlette.background import BackgroundTask
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route


class CustomHeaderMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next: Any):
        response = await call_next(request)
        return response


async def bg_task():
    await asyncio.sleep(0.1)
    raise ValueError("TEST")


def homepage(request: Request):
    task = BackgroundTask(bg_task)
    message = {"status": "Ok"}
    return JSONResponse(message, background=task)


routes = [Route("/", homepage)]

middleware = [Middleware(CustomHeaderMiddleware)]

app = Starlette(routes=routes, middleware=middleware)

@Kludex Kludex requested review from jhominal and graingert December 26, 2024 08:56
@Kludex
Copy link
Member Author

Kludex commented Dec 29, 2024

@graingert would you mind reviewing this? 🙏

@graingert
Copy link
Member

ah I broke it

@graingert
Copy link
Member

ok back working again

@graingert graingert self-requested a review December 29, 2024 12:48
@@ -258,14 +259,15 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
except OSError:
raise ClientDisconnect()
else:
async with anyio.create_task_group() as task_group:
with collapse_excgroups():
Copy link
Member Author

Choose a reason for hiding this comment

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

Why was this added?

Copy link
Member

@graingert graingert Dec 29, 2024

Choose a reason for hiding this comment

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

it's subtle but it's needed to get test_custom_middleware to pass

the reason is app_exc shouldn't be subject to collapse_excgroups (it's outside of with recv_stream, send_stream, collapse_excgroups():)- eg it's from the user's code so might have use a TG or Nursery and therefore legitimately wrapped in a EG

however that means if something raises an exception from StreamingResponse they're not really expecting an (optional!) background task to watch for disconnections, so they expect the EG to be unwrapped

Copy link
Member

Choose a reason for hiding this comment

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

I mention that it's an optional background task in StreamingResponse, because it should not be the case that StreamingResponse raises a different kind of exception based on asgi version

Copy link
Member Author

Choose a reason for hiding this comment

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

I don't want to change anything outside the base http middleware because of it

Copy link
Member

@graingert graingert Dec 29, 2024

Choose a reason for hiding this comment

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

we can nest the raise app_exc inside the collapse_excgroups() in base.py - but it's not really correct

Copy link
Member

Choose a reason for hiding this comment

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

I'll have a think

Copy link
Member Author

Choose a reason for hiding this comment

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

Do you have an MRE to share of a code that would be a problem with the raise app_exc inside the collapse_excgroups?

The PR you are working in seems to also change the StreamingResponse, so it's not really avoiding changes in it.

Copy link
Member

@graingert graingert Dec 29, 2024

Choose a reason for hiding this comment

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

so the raise app_exc can't be put inside the async with of the task group because the app_exc might not be set until after the task group has finished, and you should not put anything in between a task group and collapse_excgroups because then you're collapsing exc groups that you've not created. Thus it has to be this way.

If you want to avoid touching StreamingResponse in this PR, I've separated the changes out into another PR that's more like the old anyio 3 behaviour and strict_exception_groups=False

Copy link
Member

@graingert graingert Dec 29, 2024

Choose a reason for hiding this comment

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

There's a discussion ongoing in the trio gitter to make strict_exception_groups not deprecated and expose it in anyio, then I'd make a PR to use that where available

Copy link
Member

Choose a reason for hiding this comment

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

Do you have an MRE to share of a code that would be a problem with the raise app_exc inside the collapse_excgroups?

The PR you are working in seems to also change the StreamingResponse, so it's not really avoiding changes in it.

MRE converted to test cases and in #2830

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.

middleware causes exceptions to not be raised/handled silently (back again)
2 participants