Skip to content

Commit

Permalink
Ignore BrokenResourceError in BaseHTTPMiddleware
Browse files Browse the repository at this point in the history
ASGI specifies that send is a no-op when the connection is closed.

HTTPMiddleware uses anyio streams which will raise
an exception when the connection is closed.

So we need to ignore the exception in our send function.

Fixes encode#1284
  • Loading branch information
brakhane committed Oct 20, 2021
1 parent 26b5be4 commit d131428
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion starlette/middleware/base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import typing
from contextlib import suppress

import anyio

Expand All @@ -25,9 +26,13 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
async def call_next(request: Request) -> Response:
send_stream, recv_stream = anyio.create_memory_object_stream()

async def docile_stream_send(data):
with suppress(anyio.BrokenResourceError):
await send_stream.send(data)

async def coro() -> None:
async with send_stream:
await self.app(scope, request.receive, send_stream.send)
await self.app(scope, request.receive, docile_stream_send)

task_group.start_soon(coro)

Expand Down

0 comments on commit d131428

Please sign in to comment.