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

fix: Avoid CancelledError from being propagated to lifespan's receive() #2367

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions tests/test_lifespan.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
from unittest import mock

import pytest

Expand Down Expand Up @@ -126,6 +127,44 @@ async def test():
loop.close()


@pytest.mark.parametrize("mode", ("auto", "on"))
def test_lifespan_on_when_app_is_cancelled(mode):
def get_app(started_event: asyncio.Event):
async def app(scope, receive, send):
started_event.set()
await receive()
pytest.fail("Should be cancelled before it gets here.")

return app

async def test():
# Python 3.8/3.9 doesn't allow us to instantiate an asyncio.Event object
# while outside of a running event loop context
started_event = asyncio.Event()

config = Config(app=get_app(started_event), lifespan=mode)
lifespan = LifespanOn(config)

main_lifespan_task = asyncio.create_task(lifespan.main())

started_response = await started_event.wait()
assert started_response
assert not lifespan.shutdown_event.is_set()

with mock.patch.object(lifespan, "logger") as logger:
main_lifespan_task.cancel()
await main_lifespan_task

assert not lifespan.error_occured
logger.info.assert_called_with("Lifespan task cancelled.")
assert lifespan.startup_event.is_set()
assert lifespan.shutdown_event.is_set()

loop = asyncio.new_event_loop()
loop.run_until_complete(test())
loop.close()


@pytest.mark.parametrize("mode", ("auto", "on"))
@pytest.mark.parametrize("raise_exception", (True, False))
def test_lifespan_with_failed_startup(mode, raise_exception, caplog):
Expand Down
5 changes: 5 additions & 0 deletions uvicorn/lifespan/on.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ async def main(self) -> None:
"state": self.state,
}
await app(scope, self.receive, self.send)
except asyncio.CancelledError:
# Lifespan task was cancelled, likely due to the server shutting down.
# This is not an error that should be handled by BaseException above,
# so we just log it and exit.
self.logger.info("Lifespan task cancelled.")
Copy link
Contributor

Choose a reason for hiding this comment

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

CancelledError should generally be re-raised, in order to propagate cancellation up the call chain or to the to-be-cancelled task.

Suggested change
self.logger.info("Lifespan task cancelled.")
self.logger.info("Lifespan task cancelled.")
raise

Copy link
Author

Choose a reason for hiding this comment

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

You are correct. Initially I went with the reraise, but the issue persisted, so I naively assumed it was already the top of the chain and that not propagating it would be fine.

I think the main reason is because the issue is not actually here but on starllete (I commented about in #2367 (comment))

except BaseException as exc:
self.asgi = None
self.error_occured = True
Expand Down
Loading