Skip to content

Commit d9ea89f

Browse files
committed
improve
1 parent 31da515 commit d9ea89f

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

packages/service-library/src/servicelib/fastapi/cancellation_middleware.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import logging
33

44
from servicelib.logging_utils import log_context
5+
from starlette.requests import Request
56
from starlette.types import ASGIApp, Receive, Scope, Send
67

78
_logger = logging.getLogger(__name__)
@@ -11,10 +12,11 @@ class _TerminateTaskGroupError(Exception):
1112
pass
1213

1314

14-
async def _message_poller(queue, receive):
15+
async def _message_poller(request: Request, queue: asyncio.Queue, receive: Receive):
1516
while True:
1617
message = await receive()
1718
if message["type"] == "http.disconnect":
19+
_logger.info("client disconnected, terminating request to %s!", request.url)
1820
raise _TerminateTaskGroupError
1921

2022
# Puts the message in the queue
@@ -37,15 +39,21 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
3739
# Let's make a shared queue for the request messages
3840
queue = asyncio.Queue()
3941

40-
with log_context(_logger, logging.DEBUG, f"cancellable request {scope}"):
42+
request = Request(scope)
43+
44+
with log_context(_logger, logging.DEBUG, f"cancellable request {request.url}"):
4145
try:
4246
async with asyncio.TaskGroup() as tg:
4347
handler_task = tg.create_task(
4448
_handler(self.app, scope, queue, send)
4549
)
46-
poller_task = tg.create_task(_message_poller(queue, receive))
50+
poller_task = tg.create_task(
51+
_message_poller(request, queue, receive)
52+
)
4753
response = await handler_task
4854
poller_task.cancel()
4955
return response
5056
except* _TerminateTaskGroupError:
51-
_logger.info("The client disconnected. The task group was cancelled.")
57+
_logger.info(
58+
"The client disconnected. request to %s was cancelled.", request.url
59+
)

0 commit comments

Comments
 (0)