"""Document HTTP transport, byte validation, and the response ownership handoff.""" import asyncio import hashlib import inspect import re from collections import OrderedDict from collections.abc import Awaitable, Callable, Coroutine, Hashable, Mapping from dataclasses import dataclass from typing import Protocol, cast from urllib.parse import unquote, urlparse from weakref import WeakSet import aiohttp from fastapi import Request from fastapi.responses import JSONResponse, Response from backend.shared.transport.streams import OwnedStreamingResponse, SharedRangeFlight, UpstreamLease from backend.shared.transport.upstream import RedirectWalk from backend.reader.document.application.ranges import RangeFlightState from backend.reader.document.domain.range_cache import (RangeCacheScope, RangeObservationState, begin_range_observation, range_cache_seconds, range_representation_matches, requires_fresh_range, resident_age_headers, strong_etag) from backend.reader.document.domain.policy import RangeKey, RangeCacheEntry, RangeFlightKey, ReaderStreamOptions class DocumentState(RangeObservationState, RangeFlightState, Protocol): upstream_semaphore: asyncio.Semaphore http_session: object reader_range_blocked_flights: WeakSet[SharedRangeFlight] def _block_old_range_joins(state: DocumentState, scope: RangeCacheScope, policy: Hashable, cache_control: str | None, etag: str | None, *, fresh: bool, moved: bool) -> None: if not hasattr(state, "reader_range_blocked_flights"): state.reader_range_blocked_flights = WeakSet() flights: Mapping[RangeFlightKey, SharedRangeFlight] = getattr(state, "reader_range_flights", {}) current_task = asyncio.current_task() for (key, flight_policy, flight_cache_control), flight in flights.items(): if (key[0], key[2], key[3]) != scope or flight_policy != policy or flight_cache_control != cache_control: continue if flight.task is current_task: continue if moved or not flight.shared or not range_representation_matches(flight.headers.get("etag", ""), etag, fresh=fresh): # Keep the owner and admission slot. A new request for this range # bypasses the old producer instead of joining it. state.reader_range_blocked_flights.add(flight) def _can_join_range(state: DocumentState, key: RangeFlightKey) -> bool: if not hasattr(state, "reader_range_blocked_flights") or not hasattr(state, "reader_range_flights"): return True flight = state.reader_range_flights.get(key) return flight is None or flight not in state.reader_range_blocked_flights class OpenResponse(Protocol): def __call__(self, session: object, url: str, timeout: aiohttp.ClientTimeout, *, method: str, request_headers: dict[str, str], url_validator: Callable[[str], str], auto_decompress: bool, cache_redirects: bool = True, redirect_walk: RedirectWalk | None = None) -> Awaitable[aiohttp.ClientResponse]: ... class ProxyTiming(Protocol): def __call__(self, headers: Mapping[str, str], *, cache: str, queued: float = 0, upstream: float = 0) -> dict[str, str]: ... @dataclass(frozen=True) class DocumentDependencies: """Live transport hooks; request-local policy remains captured by the caller.""" state: Callable[[], DocumentState] open_response: Callable[[], OpenResponse] redirect_validator: Callable[[], Callable[[str], str]] bucket_validator: Callable[[], Callable[[str, str], str]] shared_response: Callable[[], Callable[[Request, str, RangeKey, ReaderStreamOptions], Awaitable[Response]]] cached_subrange: Callable[[RangeKey], tuple[bytes, dict[str, str]] | None] range_bounds: Callable[[str | None, int], tuple[int, int] | None] browser_headers: Callable[[str, dict[str, str], int], dict[str, str]] timing: Callable[[], ProxyTiming] allows_compression: Callable[[str, Request, int], bool] upstream_headers: Callable[[], tuple[str, ...]] isolation_headers: Callable[[], Mapping[str, str]] document_max_bytes: Callable[[], int] cache_ttl: Callable[[], int] cache_max_item_bytes: Callable[[], int] cache_max_bytes: Callable[[], int] cache_max_entries: Callable[[], int] limit_error: Callable[[], type[Exception]] clock: Callable[[], float] async def stream_with_disconnect(request: Request, open_stream: Callable[[], Coroutine[object, object, Response]]) -> Response: if not callable(getattr(request, "is_disconnected", None)): return await open_stream() stop_watching = asyncio.Event() async def disconnected(): while not stop_watching.is_set(): if await request.is_disconnected(): return if not stop_watching.is_set(): await asyncio.sleep(0.1) # StreamingResponse handles disconnects after headers; own the wait for # the upstream slot and headers too, so abandoned books cannot occupy it. transport = asyncio.create_task(open_stream()) watcher = asyncio.create_task(disconnected()) try: try: await asyncio.wait((transport, watcher), return_when=asyncio.FIRST_COMPLETED) client_left = watcher.done() if client_left: watcher.result() finally: stop_watching.set() watcher.cancel() if not transport.done(): transport.cancel() await asyncio.gather(transport, watcher, return_exceptions=True) if not client_left: return transport.result() except BaseException: await discard_unclaimed_response(transport) raise await discard_unclaimed_response(transport) return Response(status_code=204, headers={"Cache-Control": "no-store"}) async def discard_unclaimed_response(transport: asyncio.Task[Response]) -> None: # Headers may have arrived just before the disconnect; no ASGI sender # owns this response yet, so close it here. if transport.done() and not transport.cancelled() and transport.exception() is None: response = transport.result() if isinstance(response, OwnedStreamingResponse): try: cleanup_result = response.cleanup() if inspect.isawaitable(cleanup_result): await cleanup_result finally: close = getattr(response.body_iterator, "aclose", None) if close is not None: await close() async def stream_document( request: Request, target_url: str, deps: DocumentDependencies, *, url_validator: Callable[[str], str], cache_control: str | None = None, max_bytes: int | None = None, media_type: str | None = None, validation_scope: Hashable | None = None, _share_range: bool = True, expected_sha256: str | None = None, expected_bytes: int | None = None, ) -> Response: # Native media is streamed, not parsed or buffered as a complete document. # Bound transport memory and idle time instead of rejecting large recordings. is_media_stream = bool(media_type and media_type.startswith(("audio/", "video/"))) is_pdf = media_type == "application/pdf" or unquote(urlparse(target_url).path).lower().endswith(".pdf") if max_bytes is None and not is_media_stream: max_bytes = deps.document_max_bytes() forwarded_headers = { name: request.headers[name] for name in ("Range", "If-Range", "If-None-Match", "If-Modified-Since", "Cache-Control", "Pragma") if name in request.headers } fresh_range = requires_fresh_range(forwarded_headers) range_header = forwarded_headers.get("Range") total_limit = max_bytes # Conditional requests must reach the origin: a cached partial body cannot # represent a 200/304 decision made against a different validator. has_conditionals = any( name in forwarded_headers for name in ("If-Range", "If-None-Match", "If-Modified-Since") ) # The bounded cache does not record the redirect chain. Reuse is safe # only for the standard Reader policy and the explicitly scoped bucket # policy; arbitrary custom policies must revalidate each network response. scope_parts = cast(tuple[object, ...], validation_scope) if isinstance(validation_scope, tuple) else () bucket_cache_policy = (len(scope_parts) == 2 and scope_parts[0] is deps.bucket_validator() and scope_parts[1] == target_url) cache_policy_safe = ((url_validator is deps.redirect_validator() and validation_scope is None and cache_control is None) or bucket_cache_policy) public_get = cache_policy_safe and request.method == "GET" and expected_sha256 is None fresh = fresh_range or has_conditionals observes_ranges = public_get and (is_pdf or range_header is not None or fresh) flight_policy: Hashable = cast(Hashable, validation_scope) if validation_scope is not None else url_validator range_key: RangeKey | None = ( (target_url, range_header, max_bytes, media_type) if request.method == "GET" and range_header and not has_conditionals and expected_sha256 is None else None ) def browser_cache_headers(headers: dict[str, str]) -> dict[str, str]: # A scoped bucket route can supply a distinct downstream cache policy. return {**headers, "Cache-Control": cache_control} if cache_control is not None else headers if range_key or observes_ranges: # Cache lookups and origin observations use the same validated URL. try: target_url = url_validator(target_url) except Exception as exc: print(f"阅读代理异常: {exc}") return JSONResponse({"error": str(exc) or "上游阅读文件加载失败"}, status_code=502) if cache_policy_safe and (range_key or observes_ranges) and not hasattr(deps.state(), "reader_range_cache"): deps.state().reader_range_cache = cast("OrderedDict[RangeKey, RangeCacheEntry]", OrderedDict()) deps.state().reader_range_cache_bytes = 0 if range_key: range_key = (target_url, range_key[1], max_bytes, media_type) if cache_policy_safe: cached = deps.state().reader_range_cache.get(range_key) if not fresh_range else None if cached: cached_at, payload, cached_headers = cached current_time = deps.clock() if current_time - cached_at < range_cache_seconds(cached_headers, deps.cache_ttl()): cached_headers = resident_age_headers(cached_headers, cached_at, current_time) deps.state().reader_range_cache.move_to_end(range_key) return Response(content=payload, status_code=206, headers=deps.timing()( deps.browser_headers(target_url, browser_cache_headers(cached_headers), 206), cache="hit")) deps.state().reader_range_cache.pop(range_key, None) deps.state().reader_range_cache_bytes -= len(payload) if not fresh_range: covered = deps.cached_subrange(range_key) if covered is not None: payload, cached_headers = covered return Response(content=payload, status_code=206, headers=deps.timing()( deps.browser_headers(target_url, browser_cache_headers(cached_headers), 206), cache="slice")) requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_header or "") if (_share_range and not fresh_range and requested and int(requested[1]) <= int(requested[2]) and int(requested[2]) - int(requested[1]) + 1 <= deps.cache_max_item_bytes() and (urlparse(target_url).path.lower().endswith(".pdf") or media_type == "application/pdf") and _can_join_range(deps.state(), (range_key, flight_policy, cache_control))): return await deps.shared_response()(request, target_url, range_key, ReaderStreamOptions( url_validator=url_validator, cache_control=cache_control, max_bytes=max_bytes, media_type=media_type, validation_scope=cast(Hashable | None, validation_scope))) semaphore = deps.state().upstream_semaphore queued_at = deps.clock() await semaphore.acquire() acquired_at = deps.clock() lease = UpstreamLease(semaphore) try: cache_scope = (target_url, max_bytes, media_type) observation, ticket = begin_range_observation(deps.state(), cache_scope) if observes_ranges else (None, 0) redirect_walk = RedirectWalk(refresh=fresh) if observes_ranges else None upstream = lease.response = await deps.open_response()( deps.state().http_session, target_url, # A fixed 180-second total can truncate a valid multi-gigabyte PDF # on a slow connection; retain connect and idle-read timeouts. aiohttp.ClientTimeout(total=None if is_media_stream or is_pdf else 180, connect=15, sock_read=60), method=request.method, request_headers=forwarded_headers, url_validator=url_validator, auto_decompress=False, # Validate freshness against the source, not an older signed target. cache_redirects=not fresh, redirect_walk=redirect_walk, ) headers_at = deps.clock() if upstream.status == 429: # We generate our own error body, so do not copy its upstream # representation headers. Keep the origin's retry deadline even # when its (unused) error body is compressed or too large. retry_headers = {"Cache-Control": "no-store"} retry_after = upstream.headers.get("Retry-After", "").strip() if re.fullmatch(r"[ -~]{1,128}", retry_after): retry_headers["Retry-After"] = retry_after if request.method == "HEAD": return Response(status_code=429, headers=retry_headers) return JSONResponse({"error": "上游阅读文件加载失败: HTTP 429"}, status_code=429, headers=retry_headers) # Range offsets and document limits describe identity bytes, not compressed wire bytes. if upstream.headers.get("Content-Encoding", "identity").strip().lower() != "identity": return JSONResponse({"error": "上游阅读文件编码无效"}, status_code=502) headers = {name: upstream.headers[name] for name in deps.upstream_headers() if name in upstream.headers} headers.update(deps.isolation_headers()) headers["Cache-Control"] = cache_control or headers.get("Cache-Control", "public, max-age=300") # Gecko treats any Content-Encoding header as compressed media and # disables length/range seeking. GZipMiddleware already excludes media. if is_media_stream: headers.pop("Content-Encoding", None) elif deps.allows_compression(target_url, request, upstream.status): # GZip negotiates the representation; do not advertise an identity # strong validator as byte-equivalent to the encoded response. if headers.get("ETag", "").startswith('"'): headers["ETag"] = "W/" + headers["ETag"] else: headers["Content-Encoding"] = "identity" if media_type: headers["Content-Type"] = media_type status = upstream.status # The server cache uses origin freshness, not the browser-only PDF # no-store policy. Keep the origin's age with the cached representation. origin_cache_headers = {name: upstream.headers[name] for name in ("Cache-Control", "Age") if name in upstream.headers} cached_response_headers = {**headers, **origin_cache_headers} headers = deps.browser_headers(target_url, headers, status) headers = deps.timing()(headers, cache="miss", queued=acquired_at - queued_at, upstream=headers_at - acquired_at) declared_length = upstream.headers.get("Content-Length") length = None if declared_length is not None: try: length = int(declared_length) except (TypeError, ValueError): return JSONResponse({"error": "上游阅读文件长度无效"}, status_code=502) if length < 0 or (max_bytes is not None and length > max_bytes): return JSONResponse({"error": "阅读文件过大"}, status_code=413) content_range = upstream.headers.get("Content-Range") full_requested_range = False if expected_sha256 is not None: if status != 200 or length != expected_bytes: return JSONResponse({'error': '阅读页图长度不匹配'}, status_code=502, headers={'Cache-Control': 'no-store'}) if status == 206: match = re.fullmatch(r"bytes\s+([0-9]{1,20})-([0-9]{1,20})/([0-9]{1,20})", str(content_range or "")) if not match: return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502) range_start, range_end, total_length = (int(value) for value in match.groups()) if (range_start > range_end or range_end >= total_length or (length is not None and length != range_end - range_start + 1)): return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502) if total_limit is not None and total_length > total_limit: return JSONResponse({"error": "阅读文件过大"}, status_code=413) if not range_header: return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502) bounds = deps.range_bounds(range_header, total_length) # A 206 may stop early. Forward that prefix but never cache it # as the complete request; a wrong start would corrupt offsets. if bounds is not None: if range_start != bounds[0] or range_end > bounds[1]: return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502) full_requested_range = (range_start, range_end) == bounds elif re.fullmatch(r"bytes=[0-9]{0,20}-[0-9]{0,20}", range_header): return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502) unsatisfied_length = None if status == 416: match = re.fullmatch(r"bytes\s+\*/([0-9]{1,20})", str(content_range or "")) if match: unsatisfied_length = int(match.group(1)) if total_limit is not None and unsatisfied_length > total_limit: return JSONResponse({"error": "阅读文件过大"}, status_code=413) etag = None moved = False accepted = redirect_walk is None or redirect_walk.is_current() has_bytes = status in (200, 206) validated_unsatisfied = fresh and unsatisfied_length is not None and range_header is not None if redirect_walk is not None and fresh and (has_bytes or validated_unsatisfied or (status == 304 and has_conditionals)): # Commit in the same turn as the Range observation, after header # validation. Do not publish an alias learned on a bypass request. retired = redirect_walk.forget(status == 304) accepted = retired is not None moved = retired is True if accepted and observation is not None: # A later-started alias hit may have finished during the # rewalk. It was still on the retired redirect generation. observation, ticket = begin_range_observation(deps.state(), cache_scope) if observation is not None and accepted and (has_bytes or validated_unsatisfied or (status == 304 and has_conditionals)): etag = strong_etag(upstream.headers.get("ETag", "")) length_changed = validated_unsatisfied and any( (key[0], key[2], key[3]) == cache_scope and entry[2].get("Content-Range", "").rpartition("/")[2] != str(unsatisfied_length) for key, entry in deps.state().reader_range_cache.items() ) moved = moved or length_changed # Without representation evidence a same-target 304 need not # invalidate existing bytes, but a moved target always does. if has_bytes or moved or etag is not None: if observation.observe(deps.state(), ticket, etag, fresh=fresh, moved=moved) or fresh: _block_old_range_joins(deps.state(), cache_scope, flight_policy, cache_control, etag, fresh=fresh, moved=moved) if request.method == "HEAD" or status == 304: return Response(status_code=status, headers=headers) if not has_bytes and status != 416: return JSONResponse({"error": f"上游阅读文件加载失败: HTTP {status}"}, status_code=status) async def stream_reader_content(): total = 0 chunks: list[bytes] = [] checksum = hashlib.sha256() if expected_sha256 else None tail = b'' cacheable = bool( cache_policy_safe and range_key and status == 206 and full_requested_range and length is not None and not fresh_range and length <= deps.cache_max_item_bytes() and range_cache_seconds(cached_response_headers, deps.cache_ttl()) > 0 ) try: async for chunk in upstream.content.iter_chunked(65536): total += len(chunk) if max_bytes is not None and total > max_bytes: raise deps.limit_error()("阅读文件过大") if cacheable: chunks.append(chunk) if checksum is not None: checksum.update(chunk) if expected_bytes is None or total > expected_bytes: raise ValueError('reading image exceeds its pinned size') # Stream previews while retaining the completion marker. # Once the pinned size is reached, send the final chunk # after verification as one piece. A one-byte final # refinement can trigger another native image decode. pending = tail + chunk if total == expected_bytes: tail = pending elif len(pending) > 1: yield pending[:-1] tail = pending[-1:] else: tail = pending else: yield chunk if checksum is not None: if total != expected_bytes or checksum.hexdigest() != expected_sha256: raise ValueError('reading image checksum mismatch') yield tail if (cacheable and total == length and (redirect_walk is None or redirect_walk.is_current()) and (observation is None or observation.can_store(ticket, etag))): payload = b"".join(chunks) cache = deps.state().reader_range_cache # cacheable implies a concrete key; retain the original admission decision. cache_key = cast(RangeKey, range_key) previous = cache.pop(cache_key, None) if previous: deps.state().reader_range_cache_bytes -= len(previous[1]) cache[cache_key] = (headers_at, payload, cached_response_headers) deps.state().reader_range_cache_bytes += len(payload) while (deps.state().reader_range_cache_bytes > deps.cache_max_bytes() or len(cache) > deps.cache_max_entries()): _, (_, evicted, _) = cache.popitem(last=False) deps.state().reader_range_cache_bytes -= len(evicted) finally: lease.close() return lease.streaming_response(stream_reader_content(), status_code=status, headers=headers) except Exception as exc: print(f"阅读代理异常: {exc}") return JSONResponse({"error": str(exc) or "上游阅读文件加载失败"}, status_code=502) finally: if not lease.transferred: lease.close()