Download tests/proxy/test_proxy_ownership.py from VoiceOfML/Search: direct link, hf CLI and curl.
- Browser
- Download file 40.2 kB
-
https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/tests/proxy/test_proxy_ownership.py
- Command line
-
hf download hf://spaces/VoiceOfML/Search/tests/proxy/test_proxy_ownership.py
-
curl -L -o test_proxy_ownership.py https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/tests/proxy/test_proxy_ownership.py
40.2 kB
| """Exercise response ownership through ASGI, including disconnect before iteration.""" | |
| import asyncio | |
| import unittest | |
| from types import SimpleNamespace | |
| from unittest.mock import AsyncMock, patch | |
| from urllib.parse import urlencode | |
| from starlette.requests import ClientDisconnect | |
| from starlette.responses import Response | |
| from backend import app | |
| from backend.download.http import routes as download_routes | |
| from backend.proxy_streams import OwnedStreamingResponse, SharedRangeFlight, UpstreamLease | |
| from tests.proxy.test_async_proxy import FakeResponse, FakeSession | |
| class DownloadConnection: | |
| """Connection fixture pattern from the search middleware disconnect tests.""" | |
| def __init__(self, path): | |
| self.path = path | |
| self.messages = asyncio.Queue() | |
| self.messages.put_nowait({'type': 'http.request', 'body': b'', 'more_body': False}) | |
| self.sent = [] | |
| self.receiving = 0 | |
| self.concurrent = False | |
| async def receive(self): | |
| self.receiving += 1 | |
| self.concurrent |= self.receiving > 1 | |
| try: | |
| return await self.messages.get() | |
| finally: | |
| self.receiving -= 1 | |
| async def send(self, message): | |
| self.sent.append(message) | |
| def disconnect(self): | |
| self.messages.put_nowait({'type': 'http.disconnect'}) | |
| async def run(self): | |
| query = urlencode({'file': '书.pdf', 'link': DownloadDisconnectTests.url}).encode() | |
| scope = {'type': 'http', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, | |
| 'http_version': '1.1', 'method': 'GET', 'scheme': 'http', | |
| 'path': self.path, 'raw_path': self.path.encode(), 'query_string': query, | |
| 'headers': [], 'server': ('test', 80), 'client': ('test', 123)} | |
| await app.app(scope, self.receive, self.send) | |
| class DownloadDisconnectTests(unittest.IsolatedAsyncioTestCase): | |
| url = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf' | |
| routes = ('/api/download', '/api/download/check') | |
| async def asyncSetUp(self): | |
| self.tasks = [] | |
| self.semaphore = asyncio.Semaphore(8) | |
| self.probe_semaphore = asyncio.Semaphore(2) | |
| self.session = FakeSession([]) | |
| for item in (patch.object(download_routes, '_check_limit', return_value=self.probe_semaphore), | |
| patch.object(app.app.state, 'upstream_semaphore', self.semaphore, create=True), | |
| patch.object(app.app.state, 'http_session', self.session, create=True)): | |
| item.start() | |
| self.addCleanup(item.stop) | |
| async def asyncTearDown(self): | |
| for task in self.tasks: | |
| if not task.done(): | |
| task.cancel() | |
| await asyncio.gather(*self.tasks, return_exceptions=True) | |
| def launch(self, coroutine): | |
| task = asyncio.create_task(coroutine) | |
| self.tasks.append(task) | |
| return task | |
| async def until(self, predicate): | |
| async with asyncio.timeout(3): | |
| while not predicate(): | |
| await asyncio.sleep(.005) | |
| async def completed(self, task): | |
| # Observe completion before any teardown cancellation can hide the bug. | |
| done, _ = await asyncio.wait({task}, timeout=3) | |
| self.assertIn(task, done, 'disconnected request still waits for upstream work') | |
| return task.result() | |
| async def queued_disconnect(self, path): | |
| pool, size = ((self.probe_semaphore, 2) if path.endswith('/check') else (self.semaphore, 8)) | |
| for _ in range(size): | |
| await pool.acquire() | |
| connection = DownloadConnection(path) | |
| task = self.launch(connection.run()) | |
| await self.until(lambda: bool(pool._waiters)) | |
| connection.disconnect() | |
| await self.completed(task) | |
| self.assertEqual(connection.sent[0]['status'], 204) | |
| self.assertFalse(pool._waiters) | |
| self.assertEqual(pool._value, 0) | |
| for _ in range(size): | |
| pool.release() | |
| await asyncio.sleep(0) | |
| self.assertEqual(self.session.urls, []) | |
| self.assertEqual(self.semaphore._value, 8) | |
| self.assertEqual(self.probe_semaphore._value, 2) | |
| self.assertEqual(connection.receiving, 0) | |
| self.assertFalse(connection.concurrent) | |
| async def test_queued_download_disconnect_never_opens_upstream(self): | |
| await self.queued_disconnect('/api/download') | |
| async def test_queued_check_disconnect_never_opens_upstream(self): | |
| await self.queued_disconnect('/api/download/check') | |
| async def test_headers_disconnect_cancels_and_joins_transport(self): | |
| for path in self.routes: | |
| with self.subTest(path=path): | |
| entered, cancelled = asyncio.Event(), asyncio.Event() | |
| async def request(*args, **kwargs): | |
| entered.set() | |
| try: | |
| await asyncio.Future() | |
| finally: | |
| await asyncio.sleep(0) | |
| cancelled.set() | |
| with patch.object(self.session, 'request', side_effect=request): | |
| connection = DownloadConnection(path) | |
| task = self.launch(connection.run()) | |
| await self.until(entered.is_set) | |
| self.assertEqual(self.semaphore._value, 7 if path == '/api/download' else 8) | |
| self.assertEqual(self.probe_semaphore._value, 1 if path.endswith('/check') else 2) | |
| connection.disconnect() | |
| await self.completed(task) | |
| self.assertTrue(cancelled.is_set()) | |
| self.assertEqual(connection.sent[0]['status'], 204) | |
| self.assertEqual(self.semaphore._value, 8) | |
| self.assertEqual(self.probe_semaphore._value, 2) | |
| self.assertEqual(connection.receiving, 0) | |
| self.assertFalse(connection.concurrent) | |
| async def test_normal_streaming_and_errors_through_middleware(self): | |
| for path in self.routes: | |
| for upstream in (FakeResponse(chunks=(b'one', b'two')), FakeResponse(503), | |
| OSError('headers failed')): | |
| with self.subTest(path=path, upstream=upstream): | |
| self.session.responses.append(upstream) | |
| connection = DownloadConnection(path) | |
| await self.completed(self.launch(connection.run())) | |
| ok = isinstance(upstream, FakeResponse) and upstream.status == 200 | |
| self.assertEqual(connection.sent[0]['status'], 200 if ok else 502) | |
| self.assertEqual(self.semaphore._value, 8) | |
| self.assertEqual(connection.receiving, 0) | |
| self.assertFalse(connection.concurrent) | |
| if isinstance(upstream, FakeResponse): | |
| self.assertTrue(upstream.released) | |
| if ok and path == '/api/download': | |
| self.assertEqual(b''.join(m.get('body', b'') for m in connection.sent), b'onetwo') | |
| headers = dict(connection.sent[0]['headers']) | |
| self.assertEqual(headers[b'cache-control'], b'no-cache') | |
| self.assertEqual(headers[b'content-disposition'], | |
| b"attachment; filename*=UTF-8''%E4%B9%A6.pdf") | |
| async def test_external_cancellation_during_headers_propagates(self): | |
| for path in self.routes: | |
| with self.subTest(path=path): | |
| entered, cancelled = asyncio.Event(), asyncio.Event() | |
| async def request(*args, **kwargs): | |
| entered.set() | |
| try: | |
| await asyncio.Future() | |
| finally: | |
| cancelled.set() | |
| with patch.object(self.session, 'request', side_effect=request): | |
| connection = DownloadConnection(path) | |
| task = self.launch(connection.run()) | |
| await self.until(entered.is_set) | |
| task.cancel() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await self.completed(task) | |
| self.assertTrue(cancelled.is_set()) | |
| self.assertEqual(self.semaphore._value, 8) | |
| self.assertEqual(self.probe_semaphore._value, 2) | |
| self.assertEqual(connection.receiving, 0) | |
| async def test_disconnect_discards_headers_returned_during_transport_cancellation(self): | |
| for path in self.routes: | |
| with self.subTest(path=path): | |
| entered = asyncio.Event() | |
| upstream = FakeResponse(chunks=(b'orphan',)) | |
| closed = [] | |
| class Iterator: | |
| def __aiter__(self): | |
| return self | |
| async def __anext__(self): | |
| raise AssertionError('discarded body must not be consumed') | |
| async def aclose(self): | |
| closed.append(True) | |
| async def request(*args, **kwargs): | |
| entered.set() | |
| try: | |
| await asyncio.Future() | |
| except asyncio.CancelledError: | |
| return upstream | |
| with patch.object(self.session, 'request', side_effect=request), \ | |
| patch.object(UpstreamLease, 'chunks', return_value=Iterator()), \ | |
| patch.object(upstream, 'release', wraps=upstream.release) as release: | |
| connection = DownloadConnection(path) | |
| task = self.launch(connection.run()) | |
| await self.until(entered.is_set) | |
| connection.disconnect() | |
| await self.completed(task) | |
| self.assertEqual(connection.sent[0]['status'], 204) | |
| release.assert_called_once() | |
| self.assertEqual(closed, [True] if path == '/api/download' else []) | |
| self.assertEqual(self.semaphore._value, 8) | |
| self.assertEqual(connection.receiving, 0) | |
| async def test_simultaneous_headers_and_disconnect_discard_completed_response(self): | |
| original_wait = asyncio.wait | |
| async def both(tasks, **kwargs): | |
| await original_wait(tasks, return_when=asyncio.ALL_COMPLETED) | |
| return {tasks[0]}, {tasks[1]} # Completion snapshots may already be stale. | |
| for path in self.routes: | |
| with self.subTest(path=path): | |
| upstream = FakeResponse() | |
| self.session.responses.append(upstream) | |
| request = SimpleNamespace(receive=AsyncMock(return_value={'type': 'http.disconnect'})) | |
| closed = AsyncMock() | |
| class Iterator: | |
| def __aiter__(self): | |
| return self | |
| async def __anext__(self): | |
| raise AssertionError('discarded body must not be consumed') | |
| aclose = closed | |
| with patch.object(app.asyncio, 'wait', side_effect=both), \ | |
| patch.object(UpstreamLease, 'chunks', return_value=Iterator()), \ | |
| patch.object(upstream, 'release', wraps=upstream.release) as release: | |
| response = (await app.api_download('书.pdf', self.url, request=request) | |
| if path == '/api/download' else | |
| await app.api_download_check(self.url, request=request)) | |
| self.assertEqual(response.status_code, 204) | |
| release.assert_called_once() | |
| self.assertEqual(closed.await_count, 1 if path == '/api/download' else 0) | |
| self.assertEqual(self.semaphore._value, 8) | |
| async def test_discard_waits_for_async_cleanup_with_and_without_body_close(self): | |
| for closable in (False, True): | |
| with self.subTest(closable=closable): | |
| entered, cleaning, finish = asyncio.Event(), asyncio.Event(), asyncio.Event() | |
| events = [] | |
| class Iterator: | |
| def __aiter__(self): | |
| return self | |
| async def __anext__(self): | |
| raise AssertionError('discarded body must not be consumed') | |
| class ClosableIterator(Iterator): | |
| async def aclose(self): | |
| events.append('closed') | |
| async def cleanup(): | |
| events.append('cleanup started') | |
| cleaning.set() | |
| await finish.wait() | |
| events.append('cleanup finished') | |
| response = OwnedStreamingResponse( | |
| ClosableIterator() if closable else Iterator(), cleanup=cleanup) | |
| async def create(): | |
| entered.set() | |
| try: | |
| await asyncio.Future() | |
| except asyncio.CancelledError: | |
| return response | |
| connection = DownloadConnection('/api/download') | |
| task = self.launch(app._download_with_disconnect(connection, create)) | |
| try: | |
| await self.until(entered.is_set) | |
| connection.disconnect() | |
| await self.until(cleaning.is_set) | |
| self.assertFalse(task.done(), 'discard must await asynchronous cleanup') | |
| self.assertEqual(events, ['cleanup started']) | |
| self.assertEqual(connection.receiving, 0) | |
| finish.set() | |
| discarded = await self.completed(task) | |
| self.assertEqual(discarded.status_code, 204) | |
| self.assertIsNot(discarded, response) | |
| self.assertEqual(events, ['cleanup started', 'cleanup finished'] + | |
| (['closed'] if closable else [])) | |
| self.assertFalse(connection.concurrent) | |
| finally: | |
| finish.set() | |
| async def test_repeated_external_cancellation_waits_for_suspended_discard(self): | |
| for trigger in ('disconnect', 'external cancellation'): | |
| with self.subTest(trigger=trigger): | |
| entered, cleaning, closing = asyncio.Event(), asyncio.Event(), asyncio.Event() | |
| finish_cleanup, finish_close = asyncio.Event(), asyncio.Event() | |
| events, discard_tasks = [], [] | |
| async def cleanup(): | |
| discard_tasks.append(asyncio.current_task()) | |
| events.append('cleanup started') | |
| cleaning.set() | |
| await finish_cleanup.wait() | |
| events.append('cleanup finished') | |
| class Iterator: | |
| def __aiter__(self): | |
| return self | |
| async def __anext__(self): | |
| raise AssertionError('discarded body must not be consumed') | |
| async def aclose(self): | |
| events.append('close started') | |
| closing.set() | |
| await finish_close.wait() | |
| events.append('close finished') | |
| response = OwnedStreamingResponse(Iterator(), cleanup=cleanup) | |
| async def create(): | |
| entered.set() | |
| try: | |
| await asyncio.Future() | |
| except asyncio.CancelledError: | |
| return response | |
| connection = DownloadConnection('/api/download') | |
| task = self.launch(app._download_with_disconnect(connection, create)) | |
| try: | |
| await self.until(entered.is_set) | |
| if trigger == 'disconnect': | |
| connection.disconnect() | |
| else: | |
| task.cancel() | |
| await self.until(cleaning.is_set) | |
| self.assertEqual(connection.receiving, 0) | |
| for stage in ('cleanup', 'close'): | |
| for _ in range(2): | |
| self.assertTrue(task.cancel()) | |
| # Let each cancellation reach the helper while discard is blocked. | |
| await asyncio.sleep(0) | |
| self.assertFalse(task.done()) | |
| self.assertEqual(len(discard_tasks), 1) | |
| self.assertFalse(discard_tasks[0].done()) | |
| self.assertEqual(discard_tasks[0].cancelling(), 0) | |
| if stage == 'cleanup': | |
| self.assertEqual(events, ['cleanup started']) | |
| finish_cleanup.set() | |
| await self.until(closing.is_set) | |
| else: | |
| self.assertEqual(events, ['cleanup started', 'cleanup finished', | |
| 'close started']) | |
| finish_close.set() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await self.completed(task) | |
| self.assertEqual(events, ['cleanup started', 'cleanup finished', | |
| 'close started', 'close finished']) | |
| self.assertTrue(discard_tasks[0].done()) | |
| self.assertFalse(discard_tasks[0].cancelled()) | |
| self.assertIsNone(discard_tasks[0].result()) | |
| self.assertFalse(connection.concurrent) | |
| finally: | |
| finish_cleanup.set() | |
| finish_close.set() | |
| async def test_receive_failure_propagates_and_cancels_queued_work(self): | |
| for _ in range(8): | |
| await self.semaphore.acquire() | |
| request = SimpleNamespace(receive=AsyncMock(side_effect=OSError('receive failed'))) | |
| with self.assertRaisesRegex(OSError, 'receive failed'): | |
| await app.api_download('书.pdf', self.url, request=request) | |
| self.assertFalse(self.semaphore._waiters) | |
| self.assertEqual(self.semaphore._value, 0) | |
| self.assertEqual(self.session.urls, []) | |
| async def test_external_cancellation_during_watcher_handoff_closes_body(self): | |
| for path in self.routes: | |
| with self.subTest(path=path): | |
| receiving, cleaning, finish = asyncio.Event(), asyncio.Event(), asyncio.Event() | |
| upstream = FakeResponse() | |
| closed = [] | |
| class Request: | |
| async def receive(self): | |
| receiving.set() | |
| try: | |
| await asyncio.Future() | |
| finally: | |
| cleaning.set() | |
| await finish.wait() | |
| class Iterator: | |
| def __aiter__(self): | |
| return self | |
| async def __anext__(self): | |
| raise AssertionError('unclaimed body must not be consumed') | |
| async def aclose(self): | |
| await asyncio.sleep(0) | |
| closed.append(True) | |
| async def request(*args, **kwargs): | |
| await receiving.wait() | |
| return upstream | |
| with patch.object(self.session, 'request', side_effect=request), \ | |
| patch.object(UpstreamLease, 'chunks', return_value=Iterator()), \ | |
| patch.object(upstream, 'release', wraps=upstream.release) as release: | |
| coroutine = (app.api_download('书.pdf', self.url, request=Request()) | |
| if path == '/api/download' else | |
| app.api_download_check(self.url, request=Request())) | |
| task = self.launch(coroutine) | |
| try: | |
| await self.until(cleaning.is_set) | |
| task.cancel() | |
| finish.set() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await self.completed(task) | |
| release.assert_called_once() | |
| self.assertEqual(closed, [True] if path == '/api/download' else []) | |
| self.assertEqual(self.semaphore._value, 8) | |
| finally: | |
| finish.set() | |
| class ProxyOwnershipTests(unittest.IsolatedAsyncioTestCase): | |
| async def test_shared_plain_range_is_replayed_to_each_subscriber_once(self): | |
| created = [] | |
| finished = [] | |
| async def create(): | |
| created.append(True) | |
| return Response(b"payload", status_code=206, headers={"etag": '"v1"'}) | |
| flight = SharedRangeFlight(create, 100, finished.append) | |
| first, second = flight.subscribe(), flight.subscribe() | |
| self.assertTrue(await asyncio.wait_for(flight.ready, 1)) | |
| self.assertEqual(flight.headers["etag"], '"v1"') | |
| self.assertEqual(created, [True]) | |
| self.assertEqual([bytes(chunk) async for chunk in first.stream()], [b"payload"]) | |
| self.assertEqual([bytes(chunk) async for chunk in second.stream()], [b"payload"]) | |
| self.assertEqual(flight.size, 7) | |
| self.assertTrue(flight.done) | |
| self.assertEqual(flight.subscribers, 0) | |
| self.assertIn(flight, finished) | |
| async def test_unclaimed_declined_range_closes_its_owned_response(self): | |
| released, finished = [], [] | |
| async def chunks(): | |
| yield b"upstream" | |
| response = OwnedStreamingResponse(chunks(), cleanup=lambda: released.append("closed"), | |
| status_code=200) | |
| async def create(): | |
| return response | |
| flight = SharedRangeFlight(create, 100, finished.append) | |
| subscriber = flight.subscribe() | |
| self.assertFalse(await asyncio.wait_for(flight.ready, 1)) | |
| await asyncio.wait_for(flight.task, 1) | |
| self.assertIs(flight.response, response) | |
| self.assertEqual(released, []) | |
| await subscriber.release() | |
| self.assertEqual(released, ["closed"]) | |
| self.assertIsNone(flight.response) | |
| self.assertIsNone(subscriber.flight) | |
| self.assertIn(flight, finished) | |
| async def test_invalid_length_declines_without_consuming_stream(self): | |
| for length in ("invalid", "-1", "101"): | |
| with self.subTest(length=length): | |
| released, yielded = [], [] | |
| async def chunks(): | |
| yielded.append(True) | |
| yield b"payload" | |
| response = OwnedStreamingResponse(chunks(), cleanup=lambda: released.append(True), | |
| status_code=206, headers={"content-length": length}) | |
| async def create(): | |
| return response | |
| flight = SharedRangeFlight(create, 100, lambda _flight: None) | |
| subscriber = flight.subscribe() | |
| self.assertFalse(await asyncio.wait_for(flight.ready, 1)) | |
| await asyncio.wait_for(flight.task, 1) | |
| await subscriber.release() | |
| self.assertEqual(yielded, []) | |
| self.assertEqual(released, [True]) | |
| async def test_creator_error_reaches_subscriber_and_finishes(self): | |
| finished = [] | |
| async def create(): | |
| raise ValueError("upstream headers failed") | |
| flight = SharedRangeFlight(create, 100, finished.append) | |
| subscriber = flight.subscribe() | |
| with self.assertRaisesRegex(ValueError, "upstream headers failed"): | |
| await asyncio.wait_for(flight.ready, 1) | |
| await subscriber.release() | |
| self.assertTrue(flight.done) | |
| self.assertIsInstance(flight.error, ValueError) | |
| self.assertEqual(flight.subscribers, 0) | |
| self.assertIn(flight, finished) | |
| async def test_close_before_subscribe_does_not_start_work(self): | |
| finished = [] | |
| async def create(): | |
| self.fail("close on an unused flight must not start upstream work") | |
| flight = SharedRangeFlight(create, 100, finished.append) | |
| await flight.close() | |
| self.assertEqual(finished, [flight]) | |
| self.assertIsNone(flight.task) | |
| async def test_repeated_release_and_close_do_not_drop_another_subscriber(self): | |
| async def create(): | |
| return Response(b"payload", status_code=206) | |
| flight = SharedRangeFlight(create, 100, lambda _flight: None) | |
| first, second = flight.subscribe(), flight.subscribe() | |
| self.assertTrue(await asyncio.wait_for(flight.ready, 1)) | |
| first.close() | |
| first.close() | |
| self.assertEqual(flight.subscribers, 1) | |
| self.assertEqual([bytes(chunk) async for chunk in second.stream()], [b"payload"]) | |
| await first.release() | |
| await first.release() | |
| self.assertEqual([chunk async for chunk in first.stream()], []) | |
| self.assertEqual(flight.subscribers, 0) | |
| async def test_async_cleanup_is_awaited_even_when_client_disconnects(self): | |
| cleaned = [] | |
| async def chunks(): | |
| yield b"first" | |
| yield b"second" | |
| async def cleanup(): | |
| await asyncio.sleep(0) | |
| cleaned.append("released") | |
| response = OwnedStreamingResponse(chunks(), cleanup=cleanup, status_code=206) | |
| async def send(message): | |
| if message["type"] == "http.response.body": | |
| raise OSError("disconnected") | |
| with self.assertRaises(ClientDisconnect): | |
| await response({"type": "http", "asgi": {"spec_version": "2.4"}}, AsyncMock(), send) | |
| self.assertEqual(cleaned, ["released"]) | |
| async def test_empty_lease_still_releases_the_owned_slot(self): | |
| semaphore = asyncio.Semaphore(1) | |
| await semaphore.acquire() | |
| lease = UpstreamLease(semaphore) | |
| with self.assertRaisesRegex(RuntimeError, "response unavailable"): | |
| async for _chunk in lease.chunks("test"): | |
| pass | |
| lease.close() | |
| self.assertEqual(semaphore._value, 1) | |
| async def test_lease_without_slot_releases_response_once(self): | |
| upstream = FakeResponse(chunks=(b"one", b"two")) | |
| lease = UpstreamLease() | |
| lease.response = upstream | |
| with patch.object(upstream, "release", wraps=upstream.release) as release: | |
| self.assertEqual([chunk async for chunk in lease.chunks("test")], [b"one", b"two"]) | |
| lease.close() | |
| release.assert_called_once() | |
| async def test_shared_range_rejects_body_larger_than_declared(self): | |
| async def chunks(): | |
| yield b"abcd" | |
| released = [] | |
| response = OwnedStreamingResponse(chunks(), cleanup=lambda: released.append("closed"), | |
| status_code=206, headers={"content-length": "3"}) | |
| async def create(): | |
| return response | |
| finished = [] | |
| flight = SharedRangeFlight(create, 100, finished.append) | |
| subscriber = flight.subscribe() | |
| self.assertTrue(await flight.ready) | |
| with self.assertRaisesRegex(ValueError, "exceeds declared length"): | |
| _ = [chunk async for chunk in subscriber.stream()] | |
| self.assertEqual(released, ["closed"]) | |
| self.assertTrue(flight.done) | |
| self.assertEqual(flight.size, 0) | |
| self.assertIn(flight, finished) | |
| async def response(self, kind, upstream): | |
| state = SimpleNamespace(http_session=FakeSession([upstream]), upstream_semaphore=asyncio.Semaphore(1)) | |
| with patch.object(app, "app", SimpleNamespace(state=state)): | |
| if kind == "download": | |
| response = await app.api_download("书.pdf", "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf") | |
| else: | |
| response = await app.api_reader_content( | |
| SimpleNamespace(method="GET", headers={}), | |
| "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf") | |
| return response, state | |
| async def test_cancel_after_headers_before_handoff_releases_unclaimed_response(self): | |
| state = SimpleNamespace(http_session=FakeSession([FakeResponse(200, {"Content-Length":"2"}, (b"ok",))]), | |
| upstream_semaphore=asyncio.Semaphore(1)) | |
| original = state.http_session.responses[0] | |
| watcher_entered = asyncio.Event() | |
| watcher_cleanup_started = asyncio.Event() | |
| allow_watcher_cleanup = asyncio.Event() | |
| class Request: | |
| method = "GET" | |
| headers = {} | |
| async def is_disconnected(self): | |
| try: | |
| watcher_entered.set() | |
| await asyncio.Future() | |
| finally: | |
| watcher_cleanup_started.set() | |
| await allow_watcher_cleanup.wait() | |
| with patch.object(app, "app", SimpleNamespace(state=state)): | |
| request = asyncio.create_task(app.stream_reader_document(Request(), | |
| "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.txt")) | |
| try: | |
| await asyncio.wait_for(watcher_entered.wait(), 1) | |
| await asyncio.wait_for(watcher_cleanup_started.wait(), 1) | |
| self.assertEqual(state.upstream_semaphore._value, 0) | |
| request.cancel() | |
| allow_watcher_cleanup.set() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await asyncio.wait_for(request, 1) | |
| self.assertTrue(original.released) | |
| self.assertEqual(state.upstream_semaphore._value, 1) | |
| finally: | |
| allow_watcher_cleanup.set() | |
| if not request.done(): | |
| request.cancel() | |
| await asyncio.gather(request, return_exceptions=True) | |
| async def test_cancel_after_shared_headers_before_handoff_releases_subscription(self): | |
| from collections import OrderedDict | |
| url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf" | |
| upstream = FakeResponse(206, {"Content-Length":"2", "Content-Range":"bytes 0-1/10"}, (b"ab",)) | |
| state = SimpleNamespace(http_session=FakeSession([upstream]), upstream_semaphore=asyncio.Semaphore(1), | |
| reader_range_cache=OrderedDict(), reader_range_cache_bytes=0, | |
| reader_range_flights={}, reader_range_flight_owners=set()) | |
| watcher_cleanup = asyncio.Event() | |
| continue_cleanup = asyncio.Event() | |
| class Request: | |
| method = "GET" | |
| headers = {"Range":"bytes=0-1"} | |
| async def is_disconnected(self): | |
| try: | |
| await asyncio.Future() | |
| finally: | |
| watcher_cleanup.set() | |
| await continue_cleanup.wait() | |
| with patch.object(app, "app", SimpleNamespace(state=state)): | |
| request = asyncio.create_task(app.stream_reader_document(Request(), url)) | |
| try: | |
| await asyncio.wait_for(watcher_cleanup.wait(), 1) | |
| self.assertEqual(state.upstream_semaphore._value, 0) | |
| self.assertTrue(state.reader_range_flight_owners) | |
| request.cancel() | |
| continue_cleanup.set() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await asyncio.wait_for(request, 1) | |
| self.assertTrue(upstream.released) | |
| self.assertEqual(state.upstream_semaphore._value, 1) | |
| self.assertFalse(state.reader_range_flights) | |
| self.assertFalse(state.reader_range_flight_owners) | |
| finally: | |
| continue_cleanup.set() | |
| if not request.done(): | |
| request.cancel() | |
| await asyncio.gather(request, return_exceptions=True) | |
| await app.shutdown_reader_range_flights() | |
| async def test_cancel_during_handoff_handles_plain_and_non_closable_bodies(self): | |
| watcher_cleanup, continue_cleanup = asyncio.Event(), asyncio.Event() | |
| class Request: | |
| method = "GET" | |
| headers = {} | |
| async def is_disconnected(self): | |
| try: | |
| await asyncio.Future() | |
| finally: | |
| watcher_cleanup.set() | |
| await continue_cleanup.wait() | |
| class Iterator: | |
| def __aiter__(self): | |
| return self | |
| async def __anext__(self): | |
| raise StopAsyncIteration | |
| for streaming in (False, True): | |
| watcher_cleanup.clear() | |
| continue_cleanup.clear() | |
| released = [] | |
| response = (OwnedStreamingResponse(Iterator(), cleanup=lambda: released.append(True)) | |
| if streaming else Response(b"error", status_code=502)) | |
| with self.subTest(streaming=streaming), patch.object(app, "_stream_reader_document", AsyncMock(return_value=response)): | |
| task = asyncio.create_task(app.stream_reader_document(Request(), "https://huggingface.co/fixture")) | |
| try: | |
| await asyncio.wait_for(watcher_cleanup.wait(), 1) | |
| task.cancel() | |
| continue_cleanup.set() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await asyncio.wait_for(task, 1) | |
| self.assertEqual(released, [True] if streaming else []) | |
| finally: | |
| continue_cleanup.set() | |
| if not task.done(): | |
| task.cancel() | |
| await asyncio.gather(task, return_exceptions=True) | |
| async def test_header_transport_and_disconnect_race_always_closes_unclaimed_responses(self): | |
| url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.txt" | |
| for order in ("transport", "watcher", "cancel"): | |
| with self.subTest(order=order): | |
| entered = asyncio.Event() | |
| ready = asyncio.Event() | |
| release_fetch = asyncio.Event() | |
| disconnect = asyncio.Event() | |
| upstream = FakeResponse(200, {"Content-Length":"2"}, (b"ok",)) | |
| class Session: | |
| async def request(self, *_args, **_kwargs): | |
| entered.set() | |
| await release_fetch.wait() | |
| ready.set() | |
| return upstream | |
| class Request: | |
| method = "GET" | |
| headers = {} | |
| async def is_disconnected(self): | |
| await disconnect.wait() | |
| return True | |
| state = SimpleNamespace(http_session=Session(), upstream_semaphore=asyncio.Semaphore(1)) | |
| with patch.object(app, "app", SimpleNamespace(state=state)): | |
| task = asyncio.create_task(app.stream_reader_document(Request(), url)) | |
| await asyncio.wait_for(entered.wait(), 1) | |
| if order == "transport": | |
| release_fetch.set() | |
| response = await asyncio.wait_for(task, 1) | |
| self.assertFalse(upstream.released) | |
| response.cleanup() | |
| elif order == "watcher": | |
| disconnect.set() | |
| response = await asyncio.wait_for(task, 1) | |
| self.assertEqual(response.status_code, 204) | |
| else: | |
| release_fetch.set() | |
| await ready.wait() | |
| task.cancel() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await asyncio.wait_for(task, 1) | |
| self.assertEqual(state.upstream_semaphore._value, 1) | |
| if order != "watcher": | |
| self.assertTrue(upstream.released) | |
| async def test_disconnect_before_headers_and_after_first_chunk_releases_once(self): | |
| for kind in ("download", "reader"): | |
| for fail_at in ("http.response.start", "http.response.body"): | |
| with self.subTest(kind=kind, fail_at=fail_at): | |
| upstream = FakeResponse(chunks=(b"one", b"two")) | |
| with patch.object(upstream, "release", wraps=upstream.release) as release: | |
| response, state = await self.response(kind, upstream) | |
| async def send(message): | |
| if message["type"] == fail_at: | |
| raise OSError("client disconnected") | |
| with self.assertRaises(Exception): | |
| await response({"type": "http", "asgi": {"spec_version": "2.4"}}, AsyncMock(), send) | |
| release.assert_called_once() | |
| self.assertEqual(state.upstream_semaphore._value, 1) | |
| async def test_legacy_disconnect_before_iteration_releases(self): | |
| for kind in ("download", "reader"): | |
| with self.subTest(kind=kind): | |
| upstream = FakeResponse() | |
| response, state = await self.response(kind, upstream) | |
| started = asyncio.Event() | |
| async def send(message): | |
| started.set() | |
| await asyncio.Future() | |
| async def receive(): | |
| await started.wait() | |
| return {"type": "http.disconnect"} | |
| await asyncio.wait_for(response({"type": "http", "asgi": {"spec_version": "2.0"}}, receive, send), 1) | |
| self.assertTrue(upstream.released) | |
| self.assertEqual(state.upstream_semaphore._value, 1) | |
| async def test_normal_completion_preserves_bytes_headers_and_releases_once(self): | |
| for kind in ("download", "reader"): | |
| with self.subTest(kind=kind): | |
| upstream = FakeResponse(chunks=(b"one", b"two")) | |
| with patch.object(upstream, "release", wraps=upstream.release) as release: | |
| response, state = await self.response(kind, upstream) | |
| messages = [] | |
| async def send(message): | |
| messages.append(message) | |
| await response({"type": "http", "asgi": {"spec_version": "2.4"}}, AsyncMock(), send) | |
| release.assert_called_once() | |
| self.assertEqual(b"".join(message.get("body", b"") for message in messages), b"onetwo") | |
| self.assertEqual(state.upstream_semaphore._value, 1) | |
| if kind == "download": | |
| self.assertEqual(response.headers["content-disposition"], "attachment; filename*=UTF-8''%E4%B9%A6.pdf") | |
| self.assertEqual(response.headers["cache-control"], "no-cache") | |
| async def test_upstream_body_failure_releases_once(self): | |
| class BrokenResponse(FakeResponse): | |
| def iter_chunked(self, size): | |
| async def chunks(): | |
| yield b"one" | |
| raise OSError("upstream closed") | |
| return chunks() | |
| for kind in ("download", "reader"): | |
| with self.subTest(kind=kind): | |
| upstream = BrokenResponse() | |
| with patch.object(upstream, "release", wraps=upstream.release) as release: | |
| response, state = await self.response(kind, upstream) | |
| with self.assertRaises(OSError): | |
| async for chunk in response.body_iterator: | |
| pass | |
| release.assert_called_once() | |
| self.assertEqual(state.upstream_semaphore._value, 1) | |