|
| 1 | +import asyncio |
| 2 | +import inspect |
| 3 | +import logging |
| 4 | +from asyncio import CancelledError |
| 5 | +from contextlib import suppress |
| 6 | +from functools import wraps |
| 7 | +from typing import Any, Callable, Coroutine, Optional |
| 8 | + |
| 9 | +from fastapi import Request, Response |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +_DEFAULT_CHECK_INTERVAL_S: float = 0.5 |
| 15 | + |
| 16 | +HTTP_499_CLIENT_CLOSED_REQUEST = 499 |
| 17 | +# A non-standard status code introduced by nginx for the case when a client |
| 18 | +# closes the connection while nginx is processing the request. |
| 19 | +# SEE https://www.webfx.com/web-development/glossary/http-status-codes/what-is-a-499-status-code/ |
| 20 | + |
| 21 | +TASK_NAME_PREFIX = "cancellable_request" |
| 22 | + |
| 23 | +_FastAPIHandlerCallable = Callable[..., Coroutine[Any, Any, Optional[Any]]] |
| 24 | + |
| 25 | + |
| 26 | +async def _cancel_task_if_client_disconnected( |
| 27 | + request: Request, task: asyncio.Task, interval: float = _DEFAULT_CHECK_INTERVAL_S |
| 28 | +) -> None: |
| 29 | + try: |
| 30 | + while True: |
| 31 | + if task.done(): |
| 32 | + logger.debug("task %s is done", task) |
| 33 | + break |
| 34 | + if await request.is_disconnected(): |
| 35 | + logger.warning( |
| 36 | + "client %s disconnected! Cancelling handler for %s", |
| 37 | + request.client, |
| 38 | + f"{request.url=}", |
| 39 | + ) |
| 40 | + task.cancel() |
| 41 | + break |
| 42 | + await asyncio.sleep(interval) |
| 43 | + except CancelledError: |
| 44 | + logger.debug("task monitoring %s handler was cancelled", f"{request.url=}") |
| 45 | + raise |
| 46 | + finally: |
| 47 | + logger.debug("task monitoring %s handler completed", f"{request.url}") |
| 48 | + |
| 49 | + |
| 50 | +def cancellable_request(handler_fun: _FastAPIHandlerCallable): |
| 51 | + """This decorator periodically checks if the client disconnected and |
| 52 | + then will cancel the request and return a HTTP_499_CLIENT_CLOSED_REQUEST code (a la nginx). |
| 53 | +
|
| 54 | + Usage: decorate the cancellable route and add request: Request as an argument |
| 55 | +
|
| 56 | + @cancellable_request |
| 57 | + async def route( |
| 58 | + _request: Request, |
| 59 | + ... |
| 60 | + ) |
| 61 | + """ |
| 62 | + # CHECK: Early check that will raise upon import |
| 63 | + # IMPROVEMENT: inject this parameter to handler_fun here before it returned in the wrapper and consumed by fastapi.router? |
| 64 | + found_required_arg = any( |
| 65 | + parameter.name == "_request" and parameter.annotation == Request |
| 66 | + for parameter in inspect.signature(handler_fun).parameters.values() |
| 67 | + ) |
| 68 | + if not found_required_arg: |
| 69 | + raise ValueError( |
| 70 | + f"Invalid handler {handler_fun.__name__} signature: missing required parameter _request: Request" |
| 71 | + ) |
| 72 | + |
| 73 | + # WRAPPER ---- |
| 74 | + @wraps(handler_fun) |
| 75 | + async def wrapper(*args, **kwargs) -> Optional[Any]: |
| 76 | + request: Request = kwargs["_request"] |
| 77 | + |
| 78 | + # Intercepts handler call and creates a task out of it |
| 79 | + handler_task = asyncio.create_task( |
| 80 | + handler_fun(*args, **kwargs), |
| 81 | + name=f"{TASK_NAME_PREFIX}/handler/{handler_fun.__name__}", |
| 82 | + ) |
| 83 | + # An extra task to monitor when the client disconnects so it can |
| 84 | + # cancel 'handler_task' |
| 85 | + auto_cancel_task = asyncio.create_task( |
| 86 | + _cancel_task_if_client_disconnected(request, handler_task), |
| 87 | + name=f"{TASK_NAME_PREFIX}/auto_cancel/{handler_fun.__name__}", |
| 88 | + ) |
| 89 | + |
| 90 | + try: |
| 91 | + return await handler_task |
| 92 | + except CancelledError: |
| 93 | + logger.warning( |
| 94 | + "Request %s was cancelled since client %s disconnected !", |
| 95 | + f"{request.url}", |
| 96 | + request.client, |
| 97 | + ) |
| 98 | + return Response( |
| 99 | + "Request cancelled because client disconnected", |
| 100 | + status_code=HTTP_499_CLIENT_CLOSED_REQUEST, |
| 101 | + ) |
| 102 | + finally: |
| 103 | + # NOTE: This is ALSO called 'await handler_task' returns |
| 104 | + auto_cancel_task.cancel() |
| 105 | + with suppress(CancelledError): |
| 106 | + await auto_cancel_task |
| 107 | + |
| 108 | + return wrapper |
0 commit comments