|
| 1 | +""" |
| 2 | +SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | +http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +
|
| 16 | +SPDX-License-Identifier: Apache-2.0 |
| 17 | +""" |
| 18 | +import asyncio |
| 19 | +import unittest |
| 20 | + |
| 21 | +from starlette.applications import Starlette |
| 22 | +from starlette.background import BackgroundTask |
| 23 | +from starlette.middleware.base import BaseHTTPMiddleware |
| 24 | +from starlette.routing import Route |
| 25 | + |
| 26 | +from src.service.core import responses |
| 27 | + |
| 28 | + |
| 29 | +def _scope(spec_version: str = '2.4') -> dict: |
| 30 | + """Minimal ASGI HTTP scope for calling a response directly.""" |
| 31 | + return {'type': 'http', 'asgi': {'version': '3.0', 'spec_version': spec_version}} |
| 32 | + |
| 33 | + |
| 34 | +async def _idle_receive(): |
| 35 | + """ASGI receive for a client that stays connected and sends nothing further.""" |
| 36 | + await asyncio.Future() |
| 37 | + |
| 38 | + |
| 39 | +async def _discard_send(message) -> None: # pylint: disable=unused-argument |
| 40 | + """ASGI send that drops every message.""" |
| 41 | + |
| 42 | + |
| 43 | +def _disconnect_once(after: asyncio.Event): |
| 44 | + """ASGI receive that reports a disconnect once `after` is set.""" |
| 45 | + |
| 46 | + async def receive(): |
| 47 | + await after.wait() |
| 48 | + return {'type': 'http.disconnect'} |
| 49 | + |
| 50 | + return receive |
| 51 | + |
| 52 | + |
| 53 | +def _quiet_body(started: asyncio.Event, closed: asyncio.Event): |
| 54 | + """Body that blocks before its first chunk, recording start and closure.""" |
| 55 | + |
| 56 | + async def body(): |
| 57 | + try: |
| 58 | + started.set() |
| 59 | + await asyncio.Future() |
| 60 | + yield 'unreachable\n' |
| 61 | + finally: |
| 62 | + closed.set() |
| 63 | + |
| 64 | + return body() |
| 65 | + |
| 66 | + |
| 67 | +class TestClosingStreamingResponse(unittest.IsolatedAsyncioTestCase): |
| 68 | + """Covers release of an idle body when the client disconnects.""" |
| 69 | + |
| 70 | + async def test_quiet_body_is_closed_when_client_disconnects(self): |
| 71 | + for spec_version in ('2.3', '2.4'): |
| 72 | + with self.subTest(spec_version=spec_version): |
| 73 | + started, closed = asyncio.Event(), asyncio.Event() |
| 74 | + response = responses.ClosingStreamingResponse(_quiet_body(started, closed)) |
| 75 | + await asyncio.wait_for( |
| 76 | + response(_scope(spec_version), _disconnect_once(started), _discard_send), |
| 77 | + timeout=1, |
| 78 | + ) |
| 79 | + self.assertTrue(closed.is_set(), 'A quiet body outlived its client.') |
| 80 | + |
| 81 | + async def test_body_is_closed_after_it_is_fully_sent(self): |
| 82 | + closed = asyncio.Event() |
| 83 | + sent = [] |
| 84 | + |
| 85 | + async def body(): |
| 86 | + try: |
| 87 | + yield 'one\n' |
| 88 | + yield 'two\n' |
| 89 | + finally: |
| 90 | + closed.set() |
| 91 | + |
| 92 | + async def collecting_send(message): |
| 93 | + if message['type'] == 'http.response.body': |
| 94 | + sent.append(message['body']) |
| 95 | + |
| 96 | + response = responses.ClosingStreamingResponse(body()) |
| 97 | + await asyncio.wait_for( |
| 98 | + response(_scope(), _idle_receive, collecting_send), timeout=1) |
| 99 | + |
| 100 | + self.assertEqual(b''.join(sent), b'one\ntwo\n') |
| 101 | + self.assertTrue(closed.is_set(), 'The body was not closed after a full send.') |
| 102 | + |
| 103 | + async def test_body_failure_propagates(self): |
| 104 | + |
| 105 | + async def failing_body(): |
| 106 | + # The unreachable yield is what makes this an async generator; the |
| 107 | + # raise fires on the first __anext__. |
| 108 | + if False: # pylint: disable=using-constant-test |
| 109 | + yield 'unreachable\n' |
| 110 | + raise OSError('backend read failed') |
| 111 | + |
| 112 | + response = responses.ClosingStreamingResponse(failing_body()) |
| 113 | + with self.assertRaisesRegex(OSError, 'backend read failed'): |
| 114 | + await asyncio.wait_for( |
| 115 | + response(_scope(), _idle_receive, _discard_send), timeout=1) |
| 116 | + |
| 117 | + async def test_background_task_runs_after_the_body_is_closed(self): |
| 118 | + order = [] |
| 119 | + |
| 120 | + async def body(): |
| 121 | + try: |
| 122 | + yield 'one\n' |
| 123 | + finally: |
| 124 | + order.append('body closed') |
| 125 | + |
| 126 | + async def background(): |
| 127 | + order.append('background') |
| 128 | + |
| 129 | + response = responses.ClosingStreamingResponse( |
| 130 | + body(), background=BackgroundTask(background)) |
| 131 | + await asyncio.wait_for( |
| 132 | + response(_scope(), _idle_receive, _discard_send), timeout=1) |
| 133 | + |
| 134 | + self.assertEqual(order, ['body closed', 'background']) |
| 135 | + |
| 136 | + async def test_quiet_body_is_closed_behind_http_middleware(self): |
| 137 | + """The core service wraps requests in BaseHTTPMiddleware; it must not |
| 138 | + prevent the disconnect from reaching the response.""" |
| 139 | + started, closed = asyncio.Event(), asyncio.Event() |
| 140 | + request_sent = False |
| 141 | + |
| 142 | + async def endpoint(request): # pylint: disable=unused-argument |
| 143 | + return responses.ClosingStreamingResponse(_quiet_body(started, closed)) |
| 144 | + |
| 145 | + async def pass_through(request, call_next): |
| 146 | + return await call_next(request) |
| 147 | + |
| 148 | + async def receive(): |
| 149 | + nonlocal request_sent |
| 150 | + if not request_sent: |
| 151 | + request_sent = True |
| 152 | + return {'type': 'http.request', 'body': b'', 'more_body': False} |
| 153 | + await started.wait() |
| 154 | + return {'type': 'http.disconnect'} |
| 155 | + |
| 156 | + app = Starlette(routes=[Route('/logs', endpoint)]) |
| 157 | + app.add_middleware(BaseHTTPMiddleware, dispatch=pass_through) |
| 158 | + await asyncio.wait_for( |
| 159 | + app({**_scope(), 'http_version': '1.1', 'method': 'GET', 'scheme': 'http', |
| 160 | + 'path': '/logs', 'raw_path': b'/logs', 'query_string': b'', 'headers': [], |
| 161 | + 'client': ('127.0.0.1', 12345), 'server': ('testserver', 80)}, |
| 162 | + receive, _discard_send), |
| 163 | + timeout=1, |
| 164 | + ) |
| 165 | + |
| 166 | + self.assertTrue(closed.is_set(), 'A quiet body was not closed through HTTP middleware.') |
| 167 | + |
| 168 | + |
| 169 | +if __name__ == '__main__': |
| 170 | + unittest.main() |
0 commit comments