-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0d964e4
commit d5c321f
Showing
2 changed files
with
45 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import logging | ||
from contextlib import asynccontextmanager | ||
|
||
from anyio import create_task_group | ||
from fastapi import Request | ||
|
||
from dedoc.config import get_config | ||
|
||
|
||
@asynccontextmanager | ||
async def cancel_on_disconnect(request: Request) -> None: | ||
""" | ||
Async context manager for async code that needs to be cancelled if client disconnects prematurely. | ||
The client disconnect is monitored through the Request object. | ||
Source: https://github.com/dorinclisu/runner-with-api | ||
See discussion: https://github.com/fastapi/fastapi/discussions/8805 | ||
""" | ||
logger = get_config().get("logger", logging.getLogger()) | ||
async with create_task_group() as task_group: | ||
async def watch_disconnect() -> None: | ||
while True: | ||
message = await request.receive() | ||
|
||
if message["type"] == "http.disconnect": | ||
client = f"{request.client.host}:{request.client.port}" if request.client else "-:-" | ||
logger.info(f"{client} - `{request.method} {request.url.path}` 499 DISCONNECTED") | ||
|
||
task_group.cancel_scope.cancel() | ||
break | ||
|
||
task_group.start_soon(watch_disconnect) | ||
|
||
try: | ||
yield | ||
finally: | ||
task_group.cancel_scope.cancel() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters