litestar icon indicating copy to clipboard operation
litestar copied to clipboard

Bug: cant easily catch http disconnect in a stream

Open euri10 opened this issue 7 months ago • 0 comments

Description

following this discussion

https://discord.com/channels/919193495116337154/1256638718236823593

we could make the below mvce simpler and catch a HTTPDisconnect instead of forcing the user to use anyio CancelledError (see @provinzkraut answer here: https://discord.com/channels/919193495116337154/1256638718236823593/1256895758255521804)

URL to code causing the issue

No response

MCVE

@get("/foo")
async def foo(db_pool: Pool, db_connection: Connection) -> Stream:
    stream_id = await db_connection.fetchval(
        """insert into toto(stream) values ('') returning id"""
    )
    print(stream_id)

    async def chunks(num, stream_id):
        async with db_pool.acquire() as conn:
            try:
                for i in range(num):
                    chunk = f"chunk #{i}\n"
                    yield chunk
                    await asyncio.sleep(0.5)
                    update = await conn.execute(
                        f"update toto set stream = '{i}' where id={stream_id}"
                    )
                    print(update)

            except CancelledError as e:
                print(str(e))
                with CancelScope(shield=True):
                    delete = await conn.execute(f"delete from toto where id={id}")
                    print(delete)
		raise
            finally:
                print("end")
    return Stream(chunks(10, stream_id))

Steps to reproduce

1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

Screenshots

"![SCREENSHOT_DESCRIPTION](SCREENSHOT_LINK.png)"

Logs

No response

Litestar Version

2.9.0

Platform

  • [X] Linux
  • [ ] Mac
  • [ ] Windows
  • [ ] Other (Please specify in the description above)

[!NOTE]
While we are open for sponsoring on GitHub Sponsors and OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.

Check out all issues funded or available for funding on our Polar.sh dashboard

  • If you would like to see an issue prioritized, make a pledge towards it!
  • We receive the pledge once the issue is completed & verified
  • This, along with engagement in the community, helps us know which features are a priority to our users.
Fund with Polar

euri10 avatar Jul 03 '24 11:07 euri10