vomebook
Fix Reader version coherence and reviewed search races
8c62083
Raw History Blame Contribute Delete
6.03 kB
"""Shared range admission, subscriber ownership, and worker shutdown."""
import asyncio
from collections.abc import Awaitable, Callable, Hashable
from dataclasses import dataclass
from typing import Protocol, cast
from fastapi import Request
from fastapi.responses import Response
from backend.shared.transport.streams import OwnedStreamingResponse, SharedRangeFlight
from backend.reader.document.domain.policy import RangeFlightKey, RangeKey, ReaderStreamOptions
class RangeFlightState(Protocol):
reader_range_flights: dict[RangeFlightKey, SharedRangeFlight]
reader_range_flight_owners: set[SharedRangeFlight]
class RangeStream(Protocol):
def __call__(self, request: Request, target_url: str, *,
url_validator: Callable[[str], str], cache_control: str | None,
max_bytes: int | None, media_type: str | None, validation_scope: Hashable | None,
_share_range: bool) -> Awaitable[Response]: ...
@dataclass(frozen=True)
class RangeDependencies:
state: Callable[[], RangeFlightState]
stream: Callable[[], RangeStream]
max_flights: Callable[[], int]
max_item_bytes: Callable[[], int]
clock: Callable[[], float]
async def shutdown_range_flights(state: Callable[[], RangeFlightState]) -> None:
owners: set[SharedRangeFlight] = getattr(state(), "reader_range_flight_owners", set())
closing = list(owners)
results = await asyncio.gather(*(flight.close() for flight in closing), return_exceptions=True)
errors: list[BaseException] = []
flights: dict[RangeFlightKey, SharedRangeFlight] = getattr(state(), "reader_range_flights", {})
for flight, result in zip(closing, results):
if isinstance(result, BaseException):
owners.add(flight) # Retain failed cleanup ownership for diagnosis/retry.
errors.append(result)
else:
owners.discard(flight)
for key in list(flights):
if flights[key] is flight:
flights.pop(key)
if errors:
raise BaseExceptionGroup("Reader range flight close failures", errors)
async def shared_range_response(request: Request, target_url: str, range_key: RangeKey,
options: ReaderStreamOptions, deps: RangeDependencies) -> Response:
if not hasattr(deps.state(), "reader_range_flights"):
new_flights: dict[RangeFlightKey, SharedRangeFlight] = {}
new_owners: set[SharedRangeFlight] = set()
deps.state().reader_range_flights = new_flights
deps.state().reader_range_flight_owners = new_owners
flights: dict[RangeFlightKey, SharedRangeFlight] = deps.state().reader_range_flights
owners: set[SharedRangeFlight] = deps.state().reader_range_flight_owners
policy = options["validation_scope"] if options["validation_scope"] is not None else options["url_validator"]
key: RangeFlightKey = (range_key, policy, options["cache_control"])
flight = flights.get(key)
if flight is not None and flight.error is not None:
# Existing subscribers still own the failed stream. A retry should
# open a fresh response, not replay that stream's partial bytes.
return await deps.stream()(request, target_url, _share_range=False, **options)
joined = flight is not None
if flight is None:
if len(flights) >= deps.max_flights():
return await deps.stream()(request, target_url, _share_range=False, **options)
def finished(owner: SharedRangeFlight) -> None:
if flights.get(key) is owner:
flights.pop(key, None)
if owner.done and owner.close_error is None:
owners.discard(owner)
flight = SharedRangeFlight(
lambda: deps.stream()(request, target_url, _share_range=False, **options),
deps.max_item_bytes(), finished)
flights[key] = flight
owners.add(flight)
subscription = flight.subscribe()
shared_at = deps.clock()
transferred = False
selected: Response | None = None
try:
try:
if not await asyncio.shield(flight.ready):
selected = flight.take_response()
if selected is None:
selected = await deps.stream()(request, target_url, _share_range=False, **options)
else:
headers = dict(flight.headers)
if joined:
headers["server-timing"] += f', reader_shared;dur={(deps.clock() - shared_at) * 1000:.2f};desc="joined"'
selected = OwnedStreamingResponse(subscription.stream(), cleanup=subscription.release,
status_code=206, headers=headers)
transferred = True
finally:
if not transferred:
await subscription.release()
return selected
except BaseException:
# A selected declined/fallback response is still ours while release
# awaits. Cancellation there must not lose its upstream lease.
if selected is not None:
cleanup_owner = SharedRangeFlight(lambda: asyncio.sleep(0, result=cast(Response, selected)),
deps.max_item_bytes(), owners.discard)
cleanup_owner.response = selected
owners.add(cleanup_owner)
cleanup = asyncio.create_task(cleanup_owner.close())
while not cleanup.done():
try:
await asyncio.shield(cleanup)
except asyncio.CancelledError:
continue
except BaseException:
break
try:
cleanup.result()
except BaseException as error:
asyncio.get_running_loop().call_exception_handler({
"message": "Reader response cleanup failed during interrupted handoff",
"exception": error,
"task": cleanup,
})
raise