| 1 |
""" |
| 2 |
Test that async streaming endpoints can be cancelled without hanging. |
| 3 |
|
| 4 |
Ref: https://github.com/fastapi/fastapi/issues/14680 |
| 5 |
""" |
| 6 |
|
| 7 |
from collections.abc import AsyncIterable |
| 8 |
|
| 9 |
import anyio |
| 10 |
import pytest |
| 11 |
from fastapi import FastAPI |
| 12 |
from fastapi.responses import StreamingResponse |
| 13 |
from starlette.types import Message, Scope |
| 14 |
|
| 15 |
pytestmark = [ |
| 16 |
pytest.mark.anyio, |
| 17 |
pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning"), |
| 18 |
] |
| 19 |
|
| 20 |
|
| 21 |
app = FastAPI() |
| 22 |
|
| 23 |
|
| 24 |
@app.get("/stream-raw", response_class=StreamingResponse) |
| 25 |
async def stream_raw() -> AsyncIterable[str]: |
| 26 |
"""Async generator with no internal await - would hang without checkpoint.""" |
| 27 |
i = 0 |
| 28 |
while True: |
| 29 |
yield f"item {i}\n" |
| 30 |
i += 1 |
| 31 |
|
| 32 |
|
| 33 |
@app.get("/stream-jsonl") |
| 34 |
async def stream_jsonl() -> AsyncIterable[int]: |
| 35 |
"""JSONL async generator with no internal await.""" |
| 36 |
i = 0 |
| 37 |
while True: |
| 38 |
yield i |
| 39 |
i += 1 |
| 40 |
|
| 41 |
|
| 42 |
async def _run_asgi_and_cancel(app: FastAPI, path: str, timeout: float) -> bool: |
| 43 |
"""Call the ASGI app for *path* and cancel after *timeout* seconds. |
| 44 |
|
| 45 |
Returns `True` if the cancellation was delivered (i.e. it did not hang). |
| 46 |
""" |
| 47 |
chunks: list[bytes] = [] |
| 48 |
|
| 49 |
async def receive() -> Message: |
| 50 |
# Simulate a client that never disconnects, rely on cancellation |
| 51 |
await anyio.sleep(float("inf")) |
| 52 |
return {"type": "http.disconnect"} # pragma: no cover |
| 53 |
|
| 54 |
async def send(message: Message) -> None: |
| 55 |
if message["type"] == "http.response.body": |
| 56 |
chunks.append(message.get("body", b"")) |
| 57 |
|
| 58 |
scope: Scope = { |
| 59 |
"type": "http", |
| 60 |
"asgi": {"version": "3.0", "spec_version": "2.0"}, |
| 61 |
"http_version": "1.1", |
| 62 |
"method": "GET", |
| 63 |
"path": path, |
| 64 |
"query_string": b"", |
| 65 |
"root_path": "", |
| 66 |
"headers": [], |
| 67 |
"server": ("test", 80), |
| 68 |
} |
| 69 |
|
| 70 |
with anyio.move_on_after(timeout) as cancel_scope: |
| 71 |
await app(scope, receive, send) |
| 72 |
|
| 73 |
# If we got here within the timeout the generator was cancellable. |
| 74 |
# cancel_scope.cancelled_caught is True when move_on_after fired. |
| 75 |
return cancel_scope.cancelled_caught or len(chunks) > 0 |
| 76 |
|
| 77 |
|
| 78 |
async def test_raw_stream_cancellation() -> None: |
| 79 |
"""Raw streaming endpoint should be cancellable within a reasonable time.""" |
| 80 |
cancelled = await _run_asgi_and_cancel(app, "/stream-raw", timeout=3.0) |
| 81 |
# The key assertion: we reached this line at all (didn't hang). |
| 82 |
# cancelled will be True because the infinite generator was interrupted. |
| 83 |
assert cancelled |
| 84 |
|
| 85 |
|
| 86 |
async def test_jsonl_stream_cancellation() -> None: |
| 87 |
"""JSONL streaming endpoint should be cancellable within a reasonable time.""" |
| 88 |
cancelled = await _run_asgi_and_cancel(app, "/stream-jsonl", timeout=3.0) |
| 89 |
assert cancelled |