File size: 6,033 Bytes
8f2e8ae eeb144a 8f2e8ae 8c62083 8f2e8ae | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | """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
|