"""Request-owned cancellation around the compatibility search executor.""" import asyncio from collections.abc import Awaitable, Callable, Mapping from contextlib import AbstractAsyncContextManager from typing import Protocol, TypeVar _T = TypeVar("_T") SearchResult = tuple[object, float, float] class SearchRunner(Protocol): async def run(self, function: Callable[[], _T]) -> tuple[_T, float, float]: ... class RunSearch(Protocol): async def __call__(self, executor: SearchRunner, compute: Callable[[], object], request: "RequestReceiver | None") -> SearchResult | None: ... # Starlette exposes receive as a callable property; small test connections may # implement it as a method. Both satisfy this transport-independent interface. class RequestReceiver(Protocol): @property def receive(self) -> Callable[[], Awaitable[Mapping[str, object]]]: ... async def run_search_with_disconnect(executor: SearchRunner, compute: Callable[[], object], request: RequestReceiver | None) -> SearchResult | None: if request is None: return await executor.run(compute) async def disconnected() -> None: # FastAPI has consumed the complete body. This watcher owns receive # only until the endpoint returns, before response middleware takes over. while (await request.receive())["type"] != "http.disconnect": await asyncio.sleep(0) work = asyncio.create_task(executor.run(compute)) watcher = asyncio.create_task(disconnected()) try: await asyncio.wait((work, watcher), return_when=asyncio.FIRST_COMPLETED) if work.done(): result = work.result() # Preserve even a simultaneous worker failure. if not watcher.done(): return result watcher.result() # FIRST_COMPLETED guarantees this if work did not return. return None finally: for task in (work, watcher): if not task.done(): task.cancel() await asyncio.gather(work, watcher, return_exceptions=True) async def execute_search(compute: Callable[[], object], request: RequestReceiver | None, *, executor: SearchRunner | None, executor_factory: Callable[[], AbstractAsyncContextManager[SearchRunner]], run: RunSearch) -> SearchResult | None: if executor is None: # Direct endpoint tests without ASGI lifespan own a temporary pool. async with executor_factory() as owned_executor: return await run(owned_executor, compute, request) return await run(executor, compute, request)