aio-libs / aiohttp-sse

Server-sent events support for aiohttp
Other
192 stars 35 forks source link

Don't swallow asyncio.CancelledError #458

Closed Olegt0rr closed 5 months ago

Olegt0rr commented 5 months ago

No library should be swallowing CancelledError exceptions unconditionally like that, it will just break other people's applications.

https://github.com/aio-libs/aiohttp-sse/blob/7fdb4321a8e7951c6b27b80746f29332af34ffa4/aiohttp_sse/__init__.py#L138-L146

The problem is that your program won't stop when you explicitly told it to stop.

async def my_task():
    while True:
        ...
        await sse_response.wait()

async def main():
    t = asyncio.create_task(my_task())
    await asyncio.sleep(0.5)
    t.cancel()
    with suppress(asyncio.CancelledError):
        await my_task()

This program will never exit.

Originally posted by @Dreamsorcerer in https://github.com/aio-libs/aiohttp-sse/issues/456#issuecomment-1925751196

Olegt0rr commented 5 months ago

Then we discussed that we need to add something like that:

if asyncio.current_task().cancelling():
            raise asyncio.CancelledError
Olegt0rr commented 4 months ago

Workaround for python < 3.11

Use delayed sse.stop_streaming() instead of timeout

loop = asyncio.get_event_loop()
loop.call_later(delay, sse.stop_streaming)
await sse.wait()