vomebook commited on
Commit ·
8f2e8ae
1
Parent(s): f4d7828
Layer Reader document transport and host navigation
Browse filesFiles changed (27)
- backend/app.py+49-378
- backend/reader/document/__init__.pyAdded+1
- backend/reader/document/application/__init__.pyAdded+1
- backend/reader/document/application/ranges.pyAdded+127
- backend/reader/document/domain/__init__.pyAdded+1
- backend/reader/document/domain/policy.pyAdded+36
- backend/reader/document/http/__init__.pyAdded+1
- backend/reader/document/http/transport.pyAdded+331
- config/types/jsconfig.check.json+3
- config/types/jsconfig.search-exact.json+3
- config/types/jsconfig.strict.json+3
- eslint.config.mjs+1-1
- pyrightconfig.strict.json+7
- scripts/build/check_reader_release.mjs+1
- scripts/build/compose_app.mjs+1
- static/app.js+79-274
- static/index.html+2
- static/reader-resources.js+1
- static/search/reader-host/application/host.jsAdded+191
- static/search/reader-host/presentation/return-position.jsAdded+120
- static/sw.js+2
- tests/gates/test_static_contract.py+9-4
- tests/reader/backend/test_reader_range_flights.py+150
- tests/search/reader-navigation/host_contracts.mjsAdded+119
- tests/search/reader-navigation/test_search_history_races.mjs+7
- tests/support/classic_search_modules.js+1
- typings/search-reader-host.d.tsAdded+53
2 unmodified lines345678952 unmodified lines62636465666768697064 unmodified lines1351361371381391401411421431441393 unmodified lines153815391540154115421543154415451546154715481549155015511552310 unmodified lines1863186418651866186718681869187018711872187318741875187618778 unmodified lines18861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619373 unmodified lines194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159267 unmodified lines24272428242924302431243224332434243524362437243824392 unmodified lines244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362 unmodified linesimport asyncioimport gzipimport hashlibimport inspectimport jsonimport randomimport re52 unmodified linesfrom backend.search_matching import (compile_exact_matcher as compile_exact_matcher,split_exact_terms as split_exact_terms, edit_distance as edit_distance,could_be_fuzzy as could_be_fuzzy, is_fuzzy_match as is_fuzzy_match)from backend.proxy_streams import OwnedStreamingResponse, SharedRangeFlight, UpstreamLeasefrom backend.reader_range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,requested_range_bounds as _requested_range_bounds)from backend.search_execution import SearchBusy, SearchExecutor, check_search_cancelledfrom backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnectfrom backend.search.application.cached import (64 unmodified lines# Index postings are built as lists and published as packed arrays.IndexPostings = MutableSequence[int]CacheKey = tuple[int, str, str]# (target URL, Range header, byte limit, media type) and its cached 206 body.RangeKey = tuple[str, str, int | None, str | None]RangeCacheEntry = tuple[float, bytes, dict[str, str]]RangeFlightKey = tuple[RangeKey, Hashable, str | None]_T = TypeVar("_T")1393 unmodified linesREADER_BUSY_HEADERS = {"Cache-Control": "no-store", "Retry-After": "1"}class ReaderStreamOptions(TypedDict):"""Transport policy shared by every subscriber of one range flight."""url_validator: Callable[[str], str]cache_control: str | Nonemax_bytes: int | Nonemedia_type: str | Nonevalidation_scope: Hashable | Nonedef validate_reader_bucket_redirect_url(url: str, source_url: str) -> str:return _validate_reader_bucket_redirect_url(url, source_url,lambda target, source: validate_fixed_source_redirect_url(target, source))310 unmodified linesdef reader_document_browser_headers(target_url: str, headers: dict[str, str], status: int) -> dict[str, str]:is_pdf = (headers.get("Content-Type", "").split(";", 1)[0].strip().lower() == "application/pdf"or urlparse(target_url).path.lower().endswith(".pdf"))if status == 206 and is_pdf:# Keep browser partial bodies separate from the bounded server cache.# The request-side PDF policy bypasses Chromium's same-URL cache lock.return {**headers, "Cache-Control": "no-store"}return headersasync def stream_reader_document(8 unmodified linesmax_bytes=max_bytes, media_type=media_type, validation_scope=validation_scope,expected_sha256=expected_sha256, expected_bytes=expected_bytes,)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():returnif 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())selected: Response | None = Nonetry:try:await asyncio.wait((transport, watcher), return_when=asyncio.FIRST_COMPLETED)if transport.done():selected = transport.result()else:raise asyncio.CancelledError()finally:stop_watching.set()watcher.cancel()if not transport.done():transport.cancel()await asyncio.gather(transport, watcher, return_exceptions=True)return selectedexcept BaseException:# Headers may have arrived before cancellation, but the ASGI response# is not owned by the caller until this coroutine actually returns.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_resultfinally:close = getattr(response.body_iterator, "aclose", None)if close is not None:await close()raiseasync def _stream_reader_document(3 unmodified lines_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 = READER_DOCUMENT_MAX_BYTESforwarded_headers = {name: request.headers[name]for name in ("Range", "If-Range", "If-None-Match", "If-Modified-Since")if name in request.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 validate_reader_bucket_redirect_urland scope_parts[1] == target_url)cache_policy_safe = ((url_validator is validate_reader_redirect_url and validation_scope is Noneand cache_control is None) or bucket_cache_policy)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 Noneelse None)if range_key:# A cache hit must not bypass the caller's current source policy.# A validator may normalize the target; the cache key and redirects# are derived from the normalized URL for this request.try:target_url = url_validator(target_url)except Exception as exc:print(f"阅读代理异常: {exc}")return JSONResponse({"error": str(exc) or "上游阅读文件加载失败"}, status_code=502)range_key = (target_url, range_key[1], max_bytes, media_type)if cache_policy_safe:if not hasattr(app.state, "reader_range_cache"):app.state.reader_range_cache = cast("OrderedDict[RangeKey, RangeCacheEntry]", OrderedDict())app.state.reader_range_cache_bytes = 0cached = app.state.reader_range_cache.get(range_key)if cached:cached_at, payload, cached_headers = cachedif time.monotonic() - cached_at < READER_RANGE_CACHE_TTL_SECONDS:app.state.reader_range_cache.move_to_end(range_key)return Response(content=payload, status_code=206,headers=reader_proxy_timing(reader_document_browser_headers(target_url, cached_headers, 206), cache="hit"))app.state.reader_range_cache.pop(range_key, None)app.state.reader_range_cache_bytes -= len(payload)covered = reader_cached_subrange(range_key)if covered is not None:payload, cached_headers = coveredreturn Response(content=payload, status_code=206, headers=reader_proxy_timing(reader_document_browser_headers(target_url, 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 requested and int(requested[1]) <= int(requested[2])and int(requested[2]) - int(requested[1]) + 1 <= READER_RANGE_CACHE_MAX_ITEM_BYTESand (urlparse(target_url).path.lower().endswith(".pdf") or media_type == "application/pdf")):return await shared_reader_range_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 = app.state.upstream_semaphorequeued_at = time.monotonic()await semaphore.acquire()acquired_at = time.monotonic()lease = UpstreamLease(semaphore)try:upstream = lease.response = await open_download_response(app.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,)headers_at = time.monotonic()# 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 READER_UPSTREAM_RESPONSE_HEADERS if name in upstream.headers}headers.update(READER_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 reader_body_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_typestatus = upstream.statusheaders = reader_document_browser_headers(target_url, headers, status)headers = reader_proxy_timing(headers, cache="miss", queued=acquired_at - queued_at,upstream=headers_at - acquired_at)declared_length = upstream.headers.get("Content-Length")length = Noneif 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 = Falseif 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_lengthor (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 = _requested_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) == boundselif re.fullmatch(r"bytes=[0-9]{0,20}-[0-9]{0,20}", range_header):return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)elif status == 416:match = re.fullmatch(r"bytes\s+\*/([0-9]{1,20})", str(content_range or ""))if match and total_limit is not None and int(match.group(1)) > total_limit:return JSONResponse({"error": "阅读文件过大"}, status_code=413)if request.method == "HEAD" or status == 304:return Response(status_code=status, headers=headers)if status not in (200, 206, 416):return JSONResponse({"error": f"上游阅读文件加载失败: HTTP {status}"}, status_code=status)async def stream_reader_content():total = 0chunks: list[bytes] = []checksum = hashlib.sha256() if expected_sha256 else Nonetail = b''cacheable = bool(cache_policy_safe and range_key and status == 206 and full_requested_range and length is not Noneand length <= READER_RANGE_CACHE_MAX_ITEM_BYTES)try:async for chunk in upstream.content.iter_chunked(65536):total += len(chunk)if max_bytes is not None and total > max_bytes:raise ReaderDocumentLimitError("阅读文件过大")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 + chunkif total == expected_bytes:tail = pendingelif len(pending) > 1:yield pending[:-1]tail = pending[-1:]else:tail = pendingelse:yield chunkif checksum is not None:if total != expected_bytes or checksum.hexdigest() != expected_sha256:raise ValueError('reading image checksum mismatch')yield tailif cacheable and total == length:payload = b"".join(chunks)cache = app.state.reader_range_cacheprevious = cache.pop(range_key, None)if previous:app.state.reader_range_cache_bytes -= len(previous[1])cache[range_key] = (time.monotonic(), payload, headers)app.state.reader_range_cache_bytes += len(payload)while (app.state.reader_range_cache_bytes > READER_RANGE_CACHE_MAX_BYTESor len(cache) > READER_RANGE_CACHE_MAX_ENTRIES):_, (_, evicted, _) = cache.popitem(last=False)app.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()@app.api_route("/api/reader-cdn", methods=["GET", "HEAD"])267 unmodified linesreturn HTMLResponse(inject_initial_payload(index_path.read_text(encoding="utf-8"), repo_short))return PlainTextResponse("Frontend shell unavailable", status_code=503)def reader_proxy_timing(headers: Mapping[str, str], *, cache: str, queued: float = 0, upstream: float = 0) -> dict[str, str]:return {**headers, "Server-Timing": (f'reader_cache;desc="{cache}", reader_queue;dur={queued * 1000:.2f}, 'f'reader_headers;dur={upstream * 1000:.2f}')}def reader_cached_subrange(range_key: RangeKey) -> tuple[bytes, dict[str, str]] | None:return _cached_reader_subrange(range_key, lambda: cast(_RangeCacheState, app.state),2 unmodified lines)async def shutdown_reader_range_flights() -> None:owners: set[SharedRangeFlight] = getattr(app.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(app.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_reader_range_response(request: Request, target_url: str, range_key: RangeKey,options: ReaderStreamOptions) -> Response:if not hasattr(app.state, "reader_range_flights"):new_flights: dict[RangeFlightKey, SharedRangeFlight] = {}new_owners: set[SharedRangeFlight] = set()app.state.reader_range_flights = new_flightsapp.state.reader_range_flight_owners = new_ownersflights: dict[RangeFlightKey, SharedRangeFlight] = app.state.reader_range_flightsowners: set[SharedRangeFlight] = app.state.reader_range_flight_ownerspolicy = 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)joined = flight is not Noneif flight is None:if len(flights) >= READER_RANGE_MAX_FLIGHTS:return await _stream_reader_document(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: _stream_reader_document(request, target_url, _share_range=False, **options),READER_RANGE_CACHE_MAX_ITEM_BYTES, finished)flights[key] = flightowners.add(flight)subscription = flight.subscribe()shared_at = time.monotonic()transferred = Falseselected: Response | None = Nonetry:try:if not await asyncio.shield(flight.ready):selected = flight.take_response()if selected is None:selected = await _stream_reader_document(request, target_url, _share_range=False, **options)else:headers = dict(flight.headers)if joined:headers["server-timing"] += f', reader_shared;dur={(time.monotonic() - shared_at) * 1000:.2f};desc="joined"'selected = OwnedStreamingResponse(subscription.stream(), cleanup=subscription.release,status_code=206, headers=headers)transferred = Truefinally:if not transferred:await subscription.release()return selectedexcept 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)),READER_RANGE_CACHE_MAX_ITEM_BYTES, owners.discard)cleanup_owner.response = selectedowners.add(cleanup_owner)cleanup = asyncio.create_task(cleanup_owner.close())while not cleanup.done():try:await asyncio.shield(cleanup)except asyncio.CancelledError:continueexcept BaseException:breaktry: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,})raise2 unmodified lines34567852 unmodified lines61626364656667686970717273747576777879808182838464 unmodified lines1491501511521531541393 unmodified lines154815491550155115521553310 unmodified lines18641865186618671868186918708 unmodified lines18791880188118821883188418853 unmodified lines18891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917267 unmodified lines2185218621872188218921902 unmodified lines2193219421952196219721982199220022012202220322042205220622072 unmodified linesimport asyncioimport gzipimport hashlibimport jsonimport randomimport re52 unmodified linesfrom backend.search_matching import (compile_exact_matcher as compile_exact_matcher,split_exact_terms as split_exact_terms, edit_distance as edit_distance,could_be_fuzzy as could_be_fuzzy, is_fuzzy_match as is_fuzzy_match)from backend.proxy_streams import (OwnedStreamingResponse as OwnedStreamingResponse, SharedRangeFlight as SharedRangeFlight, UpstreamLease,)from backend.reader_range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,requested_range_bounds as _requested_range_bounds)from backend.reader.document.domain.policy import (RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry, RangeFlightKey as RangeFlightKey,ReaderStreamOptions as ReaderStreamOptions,reader_document_browser_headers as _reader_document_browser_headers, reader_proxy_timing as reader_proxy_timing,)from backend.reader.document.http.transport import (DocumentState, DocumentDependencies, stream_with_disconnect as _stream_with_disconnect,stream_document as _document_transport,)from backend.reader.document.application.ranges import (RangeFlightState, RangeDependencies, shutdown_range_flights as _shutdown_range_flights,shared_range_response as _shared_range_response,)from backend.search_execution import SearchBusy, SearchExecutor, check_search_cancelledfrom backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnectfrom backend.search.application.cached import (64 unmodified lines# Index postings are built as lists and published as packed arrays.IndexPostings = MutableSequence[int]CacheKey = tuple[int, str, str]_T = TypeVar("_T")1393 unmodified linesREADER_BUSY_HEADERS = {"Cache-Control": "no-store", "Retry-After": "1"}def validate_reader_bucket_redirect_url(url: str, source_url: str) -> str:return _validate_reader_bucket_redirect_url(url, source_url,lambda target, source: validate_fixed_source_redirect_url(target, source))310 unmodified linesdef reader_document_browser_headers(target_url: str, headers: dict[str, str], status: int) -> dict[str, str]:return _reader_document_browser_headers(target_url, headers, status, lambda url: urlparse(url).path)async def stream_reader_document(8 unmodified linesmax_bytes=max_bytes, media_type=media_type, validation_scope=validation_scope,expected_sha256=expected_sha256, expected_bytes=expected_bytes,)return await _stream_with_disconnect(request, open_stream)async def _stream_reader_document(3 unmodified lines_share_range: bool = True,expected_sha256: str | None = None, expected_bytes: int | None = None,) -> Response:return await _document_transport(request, target_url, DocumentDependencies(state=lambda: cast(DocumentState, app.state),open_response=lambda: open_download_response,redirect_validator=lambda: validate_reader_redirect_url,bucket_validator=lambda: validate_reader_bucket_redirect_url,shared_response=lambda: shared_reader_range_response,cached_subrange=lambda key: reader_cached_subrange(key),range_bounds=lambda header, total: _requested_range_bounds(header, total),browser_headers=lambda url, headers, status: reader_document_browser_headers(url, headers, status),timing=lambda: reader_proxy_timing,allows_compression=lambda url, req, status: reader_body_allows_compression(url, req, status),upstream_headers=lambda: READER_UPSTREAM_RESPONSE_HEADERS,isolation_headers=lambda: READER_ISOLATION_HEADERS,document_max_bytes=lambda: READER_DOCUMENT_MAX_BYTES,cache_ttl=lambda: READER_RANGE_CACHE_TTL_SECONDS,cache_max_item_bytes=lambda: READER_RANGE_CACHE_MAX_ITEM_BYTES,cache_max_bytes=lambda: READER_RANGE_CACHE_MAX_BYTES,cache_max_entries=lambda: READER_RANGE_CACHE_MAX_ENTRIES,limit_error=lambda: ReaderDocumentLimitError,clock=lambda: time.monotonic(),), url_validator=url_validator, cache_control=cache_control,max_bytes=max_bytes, media_type=media_type, validation_scope=validation_scope,_share_range=_share_range, expected_sha256=expected_sha256, expected_bytes=expected_bytes)@app.api_route("/api/reader-cdn", methods=["GET", "HEAD"])267 unmodified linesreturn HTMLResponse(inject_initial_payload(index_path.read_text(encoding="utf-8"), repo_short))return PlainTextResponse("Frontend shell unavailable", status_code=503)def reader_cached_subrange(range_key: RangeKey) -> tuple[bytes, dict[str, str]] | None:return _cached_reader_subrange(range_key, lambda: cast(_RangeCacheState, app.state),2 unmodified lines)async def shutdown_reader_range_flights() -> None:await _shutdown_range_flights(lambda: cast(RangeFlightState, app.state))async def shared_reader_range_response(request: Request, target_url: str, range_key: RangeKey,options: ReaderStreamOptions) -> Response:return await _shared_range_response(request, target_url, range_key, options, RangeDependencies(state=lambda: cast(RangeFlightState, app.state),stream=lambda: _stream_reader_document,max_flights=lambda: READER_RANGE_MAX_FLIGHTS,max_item_bytes=lambda: READER_RANGE_CACHE_MAX_ITEM_BYTES,clock=lambda: time.monotonic(),))
1"""Reader document transport package."""1"""Reader document transport package."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Shared range admission, subscriber ownership, and worker shutdown."""import asynciofrom collections.abc import Awaitable, Callable, Hashablefrom dataclasses import dataclassfrom typing import Protocol, cast
from fastapi import Requestfrom fastapi.responses import Response
from backend.proxy_streams import OwnedStreamingResponse, SharedRangeFlightfrom 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) 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, }) raise1"""Reader document transport package."""123456789101112131415161718192021222324252627282930313233343536"""Document transport policy and the identity shared by range subscribers."""from collections.abc import Callable, Hashable, Mappingfrom typing import TypedDict
from backend.reader_range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry
RangeFlightKey = tuple[RangeKey, Hashable, str | None]
class ReaderStreamOptions(TypedDict): """Transport policy shared by every subscriber of one range flight.""" url_validator: Callable[[str], str] cache_control: str | None max_bytes: int | None media_type: str | None validation_scope: Hashable | None
def reader_document_browser_headers(target_url: str, headers: dict[str, str], status: int, url_path: Callable[[str], str]) -> dict[str, str]: is_pdf = ( headers.get("Content-Type", "").split(";", 1)[0].strip().lower() == "application/pdf" or url_path(target_url).lower().endswith(".pdf") ) if status == 206 and is_pdf: # Keep browser partial bodies separate from the bounded server cache. # The request-side PDF policy bypasses Chromium's same-URL cache lock. return {**headers, "Cache-Control": "no-store"} return headers
def reader_proxy_timing(headers: Mapping[str, str], *, cache: str, queued: float = 0, upstream: float = 0) -> dict[str, str]: return {**headers, "Server-Timing": ( f'reader_cache;desc="{cache}", reader_queue;dur={queued * 1000:.2f}, ' f'reader_headers;dur={upstream * 1000:.2f}' )}1"""Reader document transport package."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331"""Document HTTP transport, byte validation, and the response ownership handoff."""import asyncioimport hashlibimport inspectimport refrom collections import OrderedDictfrom collections.abc import Awaitable, Callable, Coroutine, Hashable, Mappingfrom dataclasses import dataclassfrom typing import Protocol, castfrom urllib.parse import unquote, urlparse
import aiohttpfrom fastapi import Requestfrom fastapi.responses import JSONResponse, Response
from backend.proxy_streams import OwnedStreamingResponse, UpstreamLeasefrom backend.reader_range_cache import RangeCacheStatefrom backend.reader.document.domain.policy import RangeKey, RangeCacheEntry, ReaderStreamOptions
class DocumentState(RangeCacheState, Protocol): upstream_semaphore: asyncio.Semaphore http_session: object
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) -> 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()) selected: Response | None = None try: try: await asyncio.wait((transport, watcher), return_when=asyncio.FIRST_COMPLETED) if transport.done(): selected = transport.result() else: raise asyncio.CancelledError() finally: stop_watching.set() watcher.cancel() if not transport.done(): transport.cancel() await asyncio.gather(transport, watcher, return_exceptions=True) return selected except BaseException: # Headers may have arrived before cancellation, but the ASGI response # is not owned by the caller until this coroutine actually returns. 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() raise
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") if name in request.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) 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 ) if range_key: # A cache hit must not bypass the caller's current source policy. # A validator may normalize the target; the cache key and redirects # are derived from the normalized URL for this request. try: target_url = url_validator(target_url) except Exception as exc: print(f"阅读代理异常: {exc}") return JSONResponse({"error": str(exc) or "上游阅读文件加载失败"}, status_code=502) range_key = (target_url, range_key[1], max_bytes, media_type) if cache_policy_safe: if not hasattr(deps.state(), "reader_range_cache"): deps.state().reader_range_cache = cast("OrderedDict[RangeKey, RangeCacheEntry]", OrderedDict()) deps.state().reader_range_cache_bytes = 0 cached = deps.state().reader_range_cache.get(range_key) if cached: cached_at, payload, cached_headers = cached if deps.clock() - cached_at < deps.cache_ttl(): 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, cached_headers, 206), cache="hit")) deps.state().reader_range_cache.pop(range_key, None) deps.state().reader_range_cache_bytes -= len(payload) 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, 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 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")): 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: 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, ) headers_at = deps.clock() # 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 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) elif status == 416: match = re.fullmatch(r"bytes\s+\*/([0-9]{1,20})", str(content_range or "")) if match and total_limit is not None and int(match.group(1)) > total_limit: return JSONResponse({"error": "阅读文件过大"}, status_code=413) if request.method == "HEAD" or status == 304: return Response(status_code=status, headers=headers) if status not in (200, 206, 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 length <= deps.cache_max_item_bytes() ) 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: 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] = (deps.clock(), payload, 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()85 unmodified lines86878889909185 unmodified lines"../../static/reader/ui/reader-scroll-anchor.js","../../static/search/download-controller.js","../../static/search/reader-navigation.js","../../static/search/search-session.js","../../static/search/size-format.js","../../static/search/record-path.js",85 unmodified lines86878889909192939485 unmodified lines"../../static/reader/ui/reader-scroll-anchor.js","../../static/search/download-controller.js","../../static/search/reader-navigation.js","../../typings/search-reader-host.d.ts","../../static/search/reader-host/presentation/return-position.js","../../static/search/reader-host/application/host.js","../../static/search/search-session.js","../../static/search/size-format.js","../../static/search/record-path.js",
14 unmodified lines15161718192014 unmodified lines"../../typings/search-sidebar.d.ts","../../static/search/search-session.js","../../static/search/reader-navigation.js","../../static/search/download-controller.js","../../static/search/result-identity.js","../../static/search/folder-selection.js",14 unmodified lines15161718192021222314 unmodified lines"../../typings/search-sidebar.d.ts","../../static/search/search-session.js","../../static/search/reader-navigation.js","../../typings/search-reader-host.d.ts","../../static/search/reader-host/presentation/return-position.js","../../static/search/reader-host/application/host.js","../../static/search/download-controller.js","../../static/search/result-identity.js","../../static/search/folder-selection.js",
67 unmodified lines68697071727367 unmodified lines"../../static/reader/pdf/reader-pdf-text-store.mjs","../../static/search/search-session.js","../../static/search/reader-navigation.js","../../static/search/download-controller.js","../../static/search/size-format.js","../../static/search/record-path.js",67 unmodified lines68697071727374757667 unmodified lines"../../static/reader/pdf/reader-pdf-text-store.mjs","../../static/search/search-session.js","../../static/search/reader-navigation.js","../../typings/search-reader-host.d.ts","../../static/search/reader-host/presentation/return-position.js","../../static/search/reader-host/application/host.js","../../static/search/download-controller.js","../../static/search/size-format.js","../../static/search/record-path.js",
19 unmodified lines2021222324252619 unmodified linesglobals: { ...globals.browser, ...globals.serviceworker, ...globals.worker,module: "readonly", require: "readonly",...Object.fromEntries(["VoiceOfMLReaderSecurity", "VoiceOfMLReader", "VoiceOfMLReaderResources","VoiceOfMLReaderStore", "VoiceOfMLReaderChapters", "VoiceOfMLReaderVirtual", "VoiceOfMLReaderNavigation","VoiceOfMLDownloadController", "VoiceOfMLSearchSession", "VoiceOfMLReaderRequests", "VoiceOfMLReaderRuntime","VoiceOfMLReaderAdapters", "VoiceOfMLReaderScroll", "DOMPurify", "marked"].map(name => [name, "readonly"])) }19 unmodified lines2021222324252619 unmodified linesglobals: { ...globals.browser, ...globals.serviceworker, ...globals.worker,module: "readonly", require: "readonly",...Object.fromEntries(["VoiceOfMLReaderSecurity", "VoiceOfMLReader", "VoiceOfMLReaderResources","VoiceOfMLReaderStore", "VoiceOfMLReaderChapters", "VoiceOfMLReaderVirtual", "VoiceOfMLReaderNavigation", "VoiceOfMLReaderHost", "VoiceOfMLReaderReturn","VoiceOfMLDownloadController", "VoiceOfMLSearchSession", "VoiceOfMLReaderRequests", "VoiceOfMLReaderRuntime","VoiceOfMLReaderAdapters", "VoiceOfMLReaderScroll", "DOMPurify", "marked"].map(name => [name, "readonly"])) }
60 unmodified lines61626364656660 unmodified lines"backend/reader/bucket/application/resources.py","backend/reader/bucket/http/__init__.py","backend/reader/bucket/http/routes.py","backend/app.py"],"pythonVersion": "3.11",60 unmodified lines6162636465666768697071727360 unmodified lines"backend/reader/bucket/application/resources.py","backend/reader/bucket/http/__init__.py","backend/reader/bucket/http/routes.py","backend/reader/document/__init__.py","backend/reader/document/application/__init__.py","backend/reader/document/application/ranges.py","backend/reader/document/domain/__init__.py","backend/reader/document/domain/policy.py","backend/reader/document/http/__init__.py","backend/reader/document/http/transport.py","backend/app.py"],"pythonVersion": "3.11",
270 unmodified lines271272273274275276270 unmodified lines"search/domain/search-window-page.js","search/presentation/sidebar-render.js","search/reader-navigation.js","reader.css","reader/core/reader-request-manager.js","reader/formats/reader-chapter-repository.js",270 unmodified lines271272273274275276277270 unmodified lines"search/domain/search-window-page.js","search/presentation/sidebar-render.js","search/reader-navigation.js","search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js","reader.css","reader/core/reader-request-manager.js","reader/formats/reader-chapter-repository.js",
5 unmodified lines678910115 unmodified lines// Keep classic-script globals for the host; each dependency owns its own scope.export const APP_DEPENDENCIES = Object.freeze(["reader-resources.js", "reader/core/reader-contract.js", "search/reader-navigation.js","search/search-session.js", "search/download-controller.js", "search/size-format.js", "search/record-path.js","search/highlight.js", "search/response-cache.js", "search/file-types.js", "search/response-validation.js", "search/result-identity.js","search/input/domain/ownership.js", "search/input/application/controller.js",5 unmodified lines67891011125 unmodified lines// Keep classic-script globals for the host; each dependency owns its own scope.export const APP_DEPENDENCIES = Object.freeze(["reader-resources.js", "reader/core/reader-contract.js", "search/reader-navigation.js","search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js","search/search-session.js", "search/download-controller.js", "search/size-format.js", "search/record-path.js","search/highlight.js", "search/response-cache.js", "search/file-types.js", "search/response-validation.js", "search/result-identity.js","search/input/domain/ownership.js", "search/input/application/controller.js",
762 unmodified lines763764765766767768769123 unmodified lines893894895896897898899111 unmodified lines1011101210131014101510161017406 unmodified lines142414251426142714281429143014311432856 unmodified lines22892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575396 unmodified lines297229732974297529762977297853 unmodified lines3032303330343035303630373038428 unmodified lines346734683469347034713472347334741111 unmodified lines458645874588458945904591459299 unmodified lines4692469346944695469646974698157 unmodified lines485648574858485948604861486297 unmodified lines4960496149624963496449654966762 unmodified linesconst view = displayedSearchView;const target = view && getReturnPositionTarget(view.key);if (target) return target;if (!view || positionRestore || readerOverlay || !view.results.length || !VSCROLL.heights.length) return null;if (STATE.results !== view.results || (STATE.isLoading && view.key !== getSearchViewKey())) return searchPositions.get(view.key) || null;const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);if (!view.results[index]) return searchPositions.get(view.key) || null;123 unmodified linesfor (const [page, data] of task.cachedPages || []) {if (!task.ready.has(page) && data.generation === lookup.generation && data.total === total) task.ready.set(page, data);}if (task.preview && !readerOverlay) {const latest = captureReaderReturnScroll(), record = STATE.results[latest.index];const anchorId = getResultStableId(record);if (anchorId && anchorId !== position.anchorId) {111 unmodified lines}function resumeResultRecovery() {if (document.hidden || !navigator.onLine || readerOverlay) return;if (positionRestore?.failed && isRecoverableSearchError(positionRestore.error)) {tryRestoreSearchPosition(positionRestore.key);return;406 unmodified linesVSCROLL.heightCache = new Map(snapshot.heightCache || []);for (const [id, value] of snapshot.heightRecords || []) VSCROLL.heightCache.set(id, value);const restoredScroll = restoreScroll && snapshot.scroll ? { ...snapshot.scroll, route: location.href, viewKey: key } : null;readerReturnScrollState = null;resetVirtualScrollState();readerReturnScrollState = restoredScroll;renderResults(false);updateStatusBar();updateLoadInfo();856 unmodified linesreturn readerUrl;}function syncReaderFolderFilter(rawUrl) {try {const readerUrl = new URL(rawUrl, location.origin);const folderRaw = readerUrl.searchParams.get("folder_url");if (!folderRaw) return readerUrl.href;const folderUrl = new URL(folderRaw, location.origin);const mergedFolderUrl = readerNavigation.mergeSearchParams(folderUrl, buildSearchURLParams(), {keys: READER_RETURN_SEARCH_KEYS});readerUrl.searchParams.set("folder_url", mergedFolderUrl.href);return readerUrl.href;} catch (_) { return rawUrl; }}const READER_RETURN_SEARCH_KEYS = Object.freeze(["q", "min_size", "max_size", "ext", "history", "mirror", "sort","search_folders", "exact", "sidebar", "filters", "wide"]);let readerOverlay = null;let readerOverlayRevision = 0;let readerUiState = "base";let readerClosing = false;const readerNavigation = VoiceOfMLReaderNavigation.createNavigation("/static/reader.html", {// "返回阅读" on the background-reading bar reopens the kept Reader.resume: (url) => navigateToReader(url),close: () => { if (readerOverlay) handleReaderMessage({ origin: location.origin,source: readerOverlay.contentWindow, data: { type: "voice-reader-close" } }); }});let readerReturnScrollState = null;let readerReturnSnapshot = null;let readerReturnRestoreGeneration = 0;let readerReturnRestoreActive = false;function captureReaderReturnScroll() {if (!DOM.resultsContainer) return null;const top = getResultScrollTop();let index = 0;let offset = top;if (STATE.results.length) {ensureHeightTree();index = findVirtualIndex(top);offset = top - getVirtualOffset(index);}const active = document.activeElement;const focus = active instanceof HTMLElement && active.id ? { id: active.id,start: active instanceof HTMLInputElement ? active.selectionStart : null,end: active instanceof HTMLInputElement ? active.selectionEnd : null,direction: active instanceof HTMLInputElement ? active.selectionDirection : null } : null;return { route: location.href, viewKey: getSearchViewKey(), top, index, offset, focus };}function readerSearchHandoffReady(saved) {// A preview has already restored usable rows and geometry while validation// may still be fetching adjacent pages. Keep that validation running.if (STATE.isLoading || !STATE._loadedPage || !STATE.results.length) return false;if (positionRestore && (!positionRestore.preview || positionRestore.key !== saved.viewKey)) return false;const index = Math.min(saved.index, Math.max(0, STATE.total - 1));return !!STATE.results[index];}function restoreReaderSearchHandoff() {let saved;try {const handoff = JSON.parse(sessionStorage.getItem("reader-navigation-restore") || "null");sessionStorage.removeItem("reader-navigation-restore");if (!handoff || handoff.returnUrl !== location.href) return;const current = /** @type {{readerUrl?: string; returnScroll?: ReturnType<typeof captureReaderReturnScroll>} | null} */ (readerNavigation.saved());if (!current || current.readerUrl !== handoff.readerUrl) return;const url = readerNavigation.parse(handoff.readerUrl);const token = url.searchParams.get("nav");if (!token || sessionStorage.getItem("reader-return:" + token) !== location.href) return;saved = current.returnScroll;if (!saved || saved.route !== location.href || saved.viewKey !== getSearchViewKey() ||!Number.isInteger(saved.index) || saved.index < 0 || !Number.isFinite(saved.offset) || !Number.isFinite(saved.top)) return;} catch (_) { return; }const route = location.href;let cancelled = false;const cancel = () => { cancelled = true; cleanup(); };const cleanup = () => {for (const type of ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"])document.removeEventListener(type, cancel, true);};for (const type of ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"])document.addEventListener(type, cancel, true);const routeRevision = routeRenderId;const deadline = Date.now() + 30000;const restore = () => {if (cancelled || routeRevision !== routeRenderId || location.href !== route || saved.viewKey !== getSearchViewKey() || Date.now() > deadline) {cleanup(); return;}if (!readerSearchHandoffReady(saved)) { requestAnimationFrame(restore); return; }cleanup();readerReturnScrollState = saved;restoreReaderReturnScroll(false, true);const focus = saved.focus;const element = focus && document.getElementById(focus.id);if (!element || (document.activeElement !== document.body && document.activeElement !== element)) return;element.focus({ preventScroll: true });if (element instanceof HTMLInputElement && Number.isInteger(focus.start) && Number.isInteger(focus.end) &&["forward", "backward", "none"].includes(focus.direction)) {try { element.setSelectionRange(focus.start, focus.end, focus.direction); } catch (_) {}}};requestAnimationFrame(restore);}function restoreReaderReturnScroll(windowRendered = false, restoreTop = false) {const saved = readerReturnScrollState;if (!saved) return;if (saved.route && saved.route !== location.href) { readerReturnScrollState = null; return; }if (saved.viewKey && saved.viewKey !== getSearchViewKey()) { readerReturnScrollState = null; return; }const generation = ++readerReturnRestoreGeneration;let attempts = 0;const restore = () => {if (generation !== readerReturnRestoreGeneration || saved.viewKey !== getSearchViewKey() || saved.route !== location.href) return;if (!DOM.resultsContainer || !STATE.results.length) {if (++attempts < 20) requestAnimationFrame(restore);return;}ensureHeightTree();const index = Math.min(saved.index, STATE.results.length - 1);const target = Math.max(0, restoreTop ? saved.top : getVirtualOffset(index) + saved.offset);const max = Math.max(0, getVirtualTotalHeight() - DOM.resultsContainer.clientHeight);readerReturnRestoreActive = true;setResultScrollTop(Math.min(target, max));if (!windowRendered) {VSCROLL.renderStart = -1;VSCROLL.renderEnd = -1;}renderVisible();windowRendered = false;updateScrollTrack();readerReturnRestoreActive = false;if (++attempts < 4 && Math.abs(getResultScrollTop() - target) > 1) requestAnimationFrame(restore);else readerReturnScrollState = null;};restore();if (readerReturnScrollState === saved) requestAnimationFrame(() => requestAnimationFrame(restore));}function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {if (!readerOverlay) return false;readerOverlayRevision++;readerClosing = false;readerUiState = "base";readerOverlay = null;const returnFocus = readerNavigation.unmount();if (readerOverlay) return true;if (restoreScroll) {const saved = readerReturnScrollState;const snapshot = readerReturnSnapshot;const source = snapshot && searchSnapshotSources.get(snapshot);const currentView = displayedSearchView;const sameView = snapshot && source && saved?.viewKey === getSearchViewKey() &¤tView?.key === saved.viewKey && currentView.revision === source.revision &&searchViewSnapshots.get(saved.viewKey) === snapshot;const changed = sameView && (STATE.results.length !== snapshot.results.length || STATE._loadedPage !== snapshot.loadedPage);if (changed) {readerReturnScrollState = null;restoreSearchViewSnapshot(saved.viewKey, false);readerReturnScrollState = { ...saved, route: location.href };}restoreReaderReturnScroll();}if (restoreScroll) readerReturnSnapshot = null;if (restoreFocus && returnFocus && returnFocus.isConnected) returnFocus.focus();return true;}function openReaderOverlay(url, addHistory = true) {readerOverlayRevision++;if (addHistory && !readerReturnScrollState) {readerReturnScrollState = captureReaderReturnScroll();readerReturnSnapshot = saveSearchViewSnapshot(readerReturnScrollState?.viewKey || getSearchViewKey());}readerOverlay = readerNavigation.mount(url);readerUiState = "base";readerClosing = false;if (addHistory) readerNavigation.remember(url, readerReturnScrollState);}function reconcileSearchDestination() {// remember() puts a Reader share URL in the parent history entry.// Only a search destination can be reconciled with the underlying view.if (location.pathname.split("/").filter(Boolean).length > 1 || history.state?.voiceReaderOverlay) return;const changed = location.pathname + location.search !== appliedSearchRoute;const overlay = readerOverlay;// Apply the destination before disposal; preserve an unchanged search owner.if (changed) ROUTER.apply(!!overlay);if (readerOverlay === overlay) closeReaderOverlay();}function restoreReaderOverlay(state) {if (!state || !state.voiceReaderOverlay || !state.readerUrl) {reconcileSearchDestination();return;}try {const url = readerNavigation.parse(state.readerUrl);const revision = readerOverlayRevision + (readerOverlay ? 1 : 0);closeReaderOverlay(false, false);if (readerOverlayRevision !== revision) return;openReaderOverlay(url, false);} catch (_) {}}function handleReaderMessage(event) {if (!readerNavigation.accepts(event)) return;const message = event.data || {};if (message.type === "voice-reader-close") {if (readerClosing) return;readerNavigation.persistProgress(message.progress);readerClosing = true;readerUiState = "base";readerNavigation.dismiss();let returnUrl = "/";try {const target = new URL(new URL(readerOverlay.src, location.origin).searchParams.get("return") || "/", location.origin);if (target.origin === location.origin) returnUrl = target.href;} catch (_) {}// Leave directly when the current entry is not this Reader's own overlay// entry: history.back() would otherwise leave the overlay open or reach an// unrelated page, and readerClosing would ignore every later Back tap.if (!history.state?.voiceReaderOverlay) {history.replaceState(history.state, "", returnUrl);reconcileSearchDestination();return;}const overlay = readerOverlay;history.back();// Back may still arrive: keep its Reader entry intact for Forward.setTimeout(() => {if (!readerClosing || readerOverlay !== overlay) return;readerNavigation.showCloseRecovery(returnUrl);}, 1000);return;}if (message.type === "voice-reader-ui-state") {if (readerClosing) return;if (["base", "panel", "full-search"].includes(message.state)) readerUiState = message.state;return;}if (message.type === "voice-reader-theme") {if (message.theme !== "dark" && message.theme !== "light") return;STATE.isDark = message.theme === "dark";applyTheme();writeSearchPreference("theme", message.theme);return;}if (message.type === "voice-reader-open") {try {readerOverlay = readerNavigation.replace(message.url, readerReturnScrollState);} catch (_) {}return;}if (message.type !== "voice-reader-navigate") return;try {const target = new URL(message.url, location.origin);if (target.origin !== location.origin || target.pathname.split("/").filter(Boolean).length !== 1) return;const mergedTarget = readerNavigation.mergeSearchParams(target, buildSearchURLParams(), {keys: READER_RETURN_SEARCH_KEYS});history.replaceState(null, "", mergedTarget.href);reconcileSearchDestination();} catch (_) {}}function navigateToReader(rawUrl, returnUrl) {let target;try { target = readerNavigation.parse(syncReaderFolderFilter(rawUrl)); }catch (_) { return false; }const open = () => {const url = readerNavigation.prepare(target.href, returnUrl || location.href);openReaderOverlay(url);};if (STATE.isMobile && (STATE.leftSidebarOpen || STATE.rightSidebarOpen)) {STATE.leftSidebarOpen = false;STATE.rightSidebarOpen = false;updateSidebarVisibility();syncStateToURL(true);open();} else open();return true;}const warmedReaderAssets = new Set();396 unmodified linesif (!sameSearchView) {if (routeInitialized) searchInputController.invalidateVisit();cancelPendingSearchControls();readerReturnRestoreGeneration++;if (!cancelActiveSearch()) return;}const owner = searchId;53 unmodified lines};function syncStateToURL(replace = true) {if (readerOverlay) return;const params = buildSearchURLParams();if (STATE.mode === "global") {STATE.filterRepos.forEach(r => {428 unmodified linesVSCROLL.renderStart = 0;VSCROLL.renderEnd = 0;pendingResultEntrance = animate;if (readerReturnScrollState && !readerOverlay) {setResultScrollTop(getVirtualOffset(readerReturnScrollState.index) + readerReturnScrollState.offset, true);restoreReaderReturnScroll(true);} else renderVisible();}1111 unmodified linesgeneration: searchRequestId, loadedPage: STATE._loadedPage, page: STATE.page,resultCount: STATE.results.length, hasMore: STATE.hasMore, loading: STATE.isLoading,suspended: !!snapshotCloneTask || !!positionRestore,inactive: document.hidden || !!readerOverlay, dragging: VSCROLL.isDraggingThumb,scrollTop: getResultScrollTop(), loadedHeight: getVirtualTotalHeight(),viewportHeight: DOM.resultsContainer ? DOM.resultsContainer.clientHeight : 0,appendScrollTop: STATE._pagingAppendScrollTop99 unmodified linesDOM.resultsContainer.addEventListener("scrollend", () => scheduleBottomLoad(), { passive: true });DOM.resultsContainer.addEventListener("scroll", () => {updateCurrentResultPosition();if (readerReturnScrollState && !readerReturnRestoreActive) { readerReturnRestoreGeneration++; readerReturnScrollState = null; }if (!VSCROLL.isDraggingThumb) ensureVirtualViewportCovered();scheduleVirtualRender(true);}, { passive: true });157 unmodified linesDOM.themeBtn.setAttribute('aria-label', STATE.isDark ? '切换到浅色主题' : '切换到深色主题');if (STATE.isDark) { document.body.classList.remove("light"); DOM.themeIconLight.style.display = "none"; DOM.themeIconDark.style.display = ""; }else { document.body.classList.add("light"); DOM.themeIconLight.style.display = ""; DOM.themeIconDark.style.display = "none"; }if (readerOverlay && readerOverlay.contentWindow) readerOverlay.contentWindow.postMessage({ type: "voice-reader-theme-state", theme: STATE.isDark ? "dark" : "light" }, location.origin);}function toggleMobile() { STATE.isMobile = !STATE.isMobile; applyMobileMode(); writeSearchPreference("mobileMode", STATE.isMobile ? "mobile" : "desktop"); }97 unmodified linesDOM.resultsContainer.focus({ preventScroll: true });});document.addEventListener("keydown", (e) => {if (e.defaultPrevented || e.isComposing || searchComposing || e.keyCode === 229 || readerOverlay) return;const target = e.target instanceof Element ? e.target : document.activeElement;if (e.key === 'Escape' && target.closest('.sidebar')) {e.preventDefault();762 unmodified lines763764765766767768769123 unmodified lines893894895896897898899111 unmodified lines1011101210131014101510161017406 unmodified lines142414251426142714281429143014311432856 unmodified lines22892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380396 unmodified lines277727782779278027812782278353 unmodified lines2837283828392840284128422843428 unmodified lines327232733274327532763277327832791111 unmodified lines439143924393439443954396439799 unmodified lines4497449844994500450145024503157 unmodified lines466146624663466446654666466797 unmodified lines4765476647674768476947704771762 unmodified linesconst view = displayedSearchView;const target = view && getReturnPositionTarget(view.key);if (target) return target;if (!view || positionRestore || readerHost.overlay || !view.results.length || !VSCROLL.heights.length) return null;if (STATE.results !== view.results || (STATE.isLoading && view.key !== getSearchViewKey())) return searchPositions.get(view.key) || null;const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);if (!view.results[index]) return searchPositions.get(view.key) || null;123 unmodified linesfor (const [page, data] of task.cachedPages || []) {if (!task.ready.has(page) && data.generation === lookup.generation && data.total === total) task.ready.set(page, data);}if (task.preview && !readerHost.overlay) {const latest = captureReaderReturnScroll(), record = STATE.results[latest.index];const anchorId = getResultStableId(record);if (anchorId && anchorId !== position.anchorId) {111 unmodified lines}function resumeResultRecovery() {if (document.hidden || !navigator.onLine || readerHost.overlay) return;if (positionRestore?.failed && isRecoverableSearchError(positionRestore.error)) {tryRestoreSearchPosition(positionRestore.key);return;406 unmodified linesVSCROLL.heightCache = new Map(snapshot.heightCache || []);for (const [id, value] of snapshot.heightRecords || []) VSCROLL.heightCache.set(id, value);const restoredScroll = restoreScroll && snapshot.scroll ? { ...snapshot.scroll, route: location.href, viewKey: key } : null;readerReturnPosition.setScroll(null);resetVirtualScrollState();readerReturnPosition.setScroll(restoredScroll);renderResults(false);updateStatusBar();updateLoadInfo();856 unmodified linesreturn readerUrl;}// Reader host owns overlay and return-position state. Effects resolve live host hooks.const readerReturnPosition = VoiceOfMLReaderReturn.create({readView: () => ({ hasContainer: !!DOM.resultsContainer, containerHeight: DOM.resultsContainer?.clientHeight || 0,resultCount: STATE.results.length, total: STATE.total, loading: STATE.isLoading, loadedPage: STATE._loadedPage,positionRestore: positionRestore && { preview: positionRestore.preview, key: positionRestore.key }, routeRevision: routeRenderId }),hasResult: index => !!STATE.results[index], getViewKey: () => getSearchViewKey(),getTop: () => getResultScrollTop(), setTop: top => setResultScrollTop(top),ensureHeights: () => ensureHeightTree(), findIndex: top => findVirtualIndex(top),getOffset: index => getVirtualOffset(index), getTotalHeight: () => getVirtualTotalHeight(),invalidateWindow: () => { VSCROLL.renderStart = -1; VSCROLL.renderEnd = -1; },renderVisible: () => renderVisible(), updateTrack: () => updateScrollTrack(),handoffReady: saved => readerSearchHandoffReady(saved),restoreScroll: (rendered, top) => restoreReaderReturnScroll(rendered, top)});const readerHost = VoiceOfMLReaderHost.create({hashRoute: false, position: readerReturnPosition,createNavigation: options => VoiceOfMLReaderNavigation.createNavigation("/static/reader.html", options),buildParams: () => buildSearchURLParams(),readQuery: () => DOM.searchInput ? DOM.searchInput.value : STATE.query,currentParams: () => buildSearchURLParams(),getViewKey: () => getSearchViewKey(), captureScroll: () => captureReaderReturnScroll(),restoreScroll: () => restoreReaderReturnScroll(), saveSnapshot: key => saveSearchViewSnapshot(key),snapshotChanged: (snapshot, key) => {const source = searchSnapshotSources.get(snapshot), current = displayedSearchView;return key === getSearchViewKey() && !!source && !!current && current.key === key &¤t.revision === source.revision && searchViewSnapshots.get(key) === snapshot &&(STATE.results.length !== snapshot.results.length || STATE._loadedPage !== snapshot.loadedPage);},restoreSnapshot: key => restoreSearchViewSnapshot(key, false),routeChanged: () => location.pathname + location.search !== appliedSearchRoute,applyRoute: preserve => ROUTER.apply(preserve),closeMobileSidebars: () => {if (STATE.isMobile && (STATE.leftSidebarOpen || STATE.rightSidebarOpen)) {STATE.leftSidebarOpen = false;STATE.rightSidebarOpen = false;updateSidebarVisibility();syncStateToURL(true);}},applyTheme: theme => { STATE.isDark = theme === "dark"; applyTheme(); writeSearchPreference("theme", theme); },navigate: url => navigateToReader(url), handleMessage: event => handleReaderMessage(event),syncFolder: url => syncReaderFolderFilter(url), normalizeReturn: url => url,openOverlay: (url, addHistory) => openReaderOverlay(url, addHistory),closeOverlay: (focus, scroll) => closeReaderOverlay(focus, scroll), reconcile: () => reconcileSearchDestination()});const readerNavigation = readerHost.navigation;const READER_RETURN_SEARCH_KEYS = readerHost.keys;// Read-only compatibility projections for existing browser diagnostics.Object.defineProperties(window, {readerOverlay: { get: () => readerHost.overlay },readerClosing: { get: () => readerHost.closing },readerUiState: { get: () => readerHost.uiState },readerReturnSnapshot: { get: () => readerHost.returnSnapshot }});function syncReaderFolderFilter(rawUrl) {return readerHost.syncReaderFolderFilter(rawUrl);}function captureReaderReturnScroll() {return readerReturnPosition.capture();}function readerSearchHandoffReady(saved) {return readerReturnPosition.ready(saved);}function restoreReaderSearchHandoff() {readerReturnPosition.restoreHandoff(readerNavigation);}function restoreReaderReturnScroll(windowRendered = false, restoreTop = false) {readerReturnPosition.restore(windowRendered, restoreTop);}function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {return readerHost.closeReaderOverlay(restoreFocus, restoreScroll);}function openReaderOverlay(url, addHistory = true) {readerHost.openReaderOverlay(url, addHistory);}function reconcileSearchDestination() {readerHost.reconcileSearchDestination();}function restoreReaderOverlay(state) {readerHost.restoreReaderOverlay(state);}function handleReaderMessage(event) {readerHost.handleReaderMessage(event);}function navigateToReader(rawUrl, returnUrl) {return readerHost.navigateToReader(rawUrl, returnUrl);}const warmedReaderAssets = new Set();396 unmodified linesif (!sameSearchView) {if (routeInitialized) searchInputController.invalidateVisit();cancelPendingSearchControls();readerReturnPosition.invalidate();if (!cancelActiveSearch()) return;}const owner = searchId;53 unmodified lines};function syncStateToURL(replace = true) {if (readerHost.overlay) return;const params = buildSearchURLParams();if (STATE.mode === "global") {STATE.filterRepos.forEach(r => {428 unmodified linesVSCROLL.renderStart = 0;VSCROLL.renderEnd = 0;pendingResultEntrance = animate;if (readerReturnPosition.scroll && !readerHost.overlay) {setResultScrollTop(getVirtualOffset(readerReturnPosition.scroll.index) + readerReturnPosition.scroll.offset, true);restoreReaderReturnScroll(true);} else renderVisible();}1111 unmodified linesgeneration: searchRequestId, loadedPage: STATE._loadedPage, page: STATE.page,resultCount: STATE.results.length, hasMore: STATE.hasMore, loading: STATE.isLoading,suspended: !!snapshotCloneTask || !!positionRestore,inactive: document.hidden || !!readerHost.overlay, dragging: VSCROLL.isDraggingThumb,scrollTop: getResultScrollTop(), loadedHeight: getVirtualTotalHeight(),viewportHeight: DOM.resultsContainer ? DOM.resultsContainer.clientHeight : 0,appendScrollTop: STATE._pagingAppendScrollTop99 unmodified linesDOM.resultsContainer.addEventListener("scrollend", () => scheduleBottomLoad(), { passive: true });DOM.resultsContainer.addEventListener("scroll", () => {updateCurrentResultPosition();readerReturnPosition.cancelOnScroll();if (!VSCROLL.isDraggingThumb) ensureVirtualViewportCovered();scheduleVirtualRender(true);}, { passive: true });157 unmodified linesDOM.themeBtn.setAttribute('aria-label', STATE.isDark ? '切换到浅色主题' : '切换到深色主题');if (STATE.isDark) { document.body.classList.remove("light"); DOM.themeIconLight.style.display = "none"; DOM.themeIconDark.style.display = ""; }else { document.body.classList.add("light"); DOM.themeIconLight.style.display = ""; DOM.themeIconDark.style.display = "none"; }if (readerHost.overlay && readerHost.overlay.contentWindow) readerHost.overlay.contentWindow.postMessage({ type: "voice-reader-theme-state", theme: STATE.isDark ? "dark" : "light" }, location.origin);}function toggleMobile() { STATE.isMobile = !STATE.isMobile; applyMobileMode(); writeSearchPreference("mobileMode", STATE.isMobile ? "mobile" : "desktop"); }97 unmodified linesDOM.resultsContainer.focus({ preventScroll: true });});document.addEventListener("keydown", (e) => {if (e.defaultPrevented || e.isComposing || searchComposing || e.keyCode === 229 || readerHost.overlay) return;const target = e.target instanceof Element ? e.target : document.activeElement;if (e.key === 'Escape' && target.closest('.sidebar')) {e.preventDefault();
337 unmodified lines338339340341342343337 unmodified lines<script src="/static/reader-resources.js"></script><script src="/static/reader/core/reader-contract.js"></script><script src="/static/search/reader-navigation.js"></script><script src="/static/search/search-session.js"></script><script src="/static/search/download-controller.js"></script><script src="/static/search/size-format.js"></script>337 unmodified lines338339340341342343344345337 unmodified lines<script src="/static/reader-resources.js"></script><script src="/static/reader/core/reader-contract.js"></script><script src="/static/search/reader-navigation.js"></script><script src="/static/search/reader-host/presentation/return-position.js"></script><script src="/static/search/reader-host/application/host.js"></script><script src="/static/search/search-session.js"></script><script src="/static/search/download-controller.js"></script><script src="/static/search/size-format.js"></script>
126 unmodified lines127128129130131132126 unmodified lines"reader/search/reader-chapter-search.mjs","reader/core/reader-contract.js","search/reader-navigation.js","reader/core/reader-store.js","reader/core/reader-request-manager.js","reader/formats/reader-chapter-repository.js",126 unmodified lines127128129130131132133126 unmodified lines"reader/search/reader-chapter-search.mjs","reader/core/reader-contract.js","search/reader-navigation.js","search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js","reader/core/reader-store.js","reader/core/reader-request-manager.js","reader/formats/reader-chapter-repository.js",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191// Coordinates the search/Reader handoff; reader-navigation owns iframe/history mechanics.(function () { /** @param {ReaderHostDependencies} deps */ function create(deps) { const position = deps.position; /** @type {HTMLIFrameElement | null} */ let overlay = null; let revision = 0, closing = false, uiState = "base"; /** @type {ReaderHostSnapshot | null} */ let snapshot = null; const keys = Object.freeze([ "q", "min_size", "max_size", "ext", "history", "mirror", "sort", "search_folders", "exact", ...(deps.hashRoute ? ["local"] : []), "sidebar", "filters", "wide" ]); const navigation = deps.createNavigation({ resume: url => deps.navigate(url), close: () => { if (overlay) deps.handleMessage({ origin: location.origin, source: overlay.contentWindow, data: { type: "voice-reader-close" } }); } }); function currentReaderSearchParams() { const params = deps.buildParams(); if (deps.hashRoute) { const query = deps.readQuery().trim(); if (query) params.set("q", query); } return params; } /** @param {string} rawUrl */ function normalizeReaderReturnUrl(rawUrl) { if (!deps.hashRoute) return rawUrl; try { const target = new URL(rawUrl || "/search/", location.origin); if (target.origin === location.origin && target.pathname === "/") return new URL("/search/", location.origin).href; return target.href; } catch (_) { return new URL("/search/", location.origin).href; } } /** @param {URL} target */ function merge(target) { return navigation.mergeSearchParams(target, deps.currentParams(), { hashRoute: deps.hashRoute, keys }); } /** @param {string} rawUrl */ function syncReaderFolderFilter(rawUrl) { try { const readerUrl = new URL(rawUrl, location.origin); const raw = readerUrl.searchParams.get("folder_url"); if (!raw) return readerUrl.href; readerUrl.searchParams.set("folder_url", merge(new URL(raw, location.origin)).href); return readerUrl.href; } catch (_) { return rawUrl; } } function closeReaderOverlay(restoreFocus = true, restoreScroll = true) { if (deps.hashRoute) { restoreFocus = restoreFocus !== false; restoreScroll = restoreScroll !== false; } if (!overlay) return false; revision++; closing = false; uiState = "base"; overlay = null; const returnFocus = navigation.unmount(); if (overlay) return true; if (restoreScroll) { const saved = position.scroll; if (saved && snapshot && deps.snapshotChanged(snapshot, saved.viewKey)) { position.setScroll(null); deps.restoreSnapshot(saved.viewKey); position.setScroll({ ...saved, route: location.href }); } deps.restoreScroll(); snapshot = null; } if (restoreFocus && returnFocus && returnFocus.isConnected) returnFocus.focus(); return true; } /** @param {URL} url @param {boolean} [addHistory] */ function openReaderOverlay(url, addHistory = true) { if (deps.hashRoute) addHistory = addHistory !== false; revision++; if (addHistory && !position.scroll) { const saved = deps.captureScroll(); position.setScroll(saved); snapshot = deps.saveSnapshot(saved?.viewKey || deps.getViewKey()); } overlay = navigation.mount(url); uiState = "base"; closing = false; if (addHistory) navigation.remember(url, /** @type {object} */ (position.scroll)); } function reconcileSearchDestination() { if ((deps.hashRoute ? location.pathname !== "/search/" : location.pathname.split("/").filter(Boolean).length > 1) || history.state?.voiceReaderOverlay) return; const previous = overlay, owner = revision; // Apply the destination before disposal can synchronously start new work. if (deps.routeChanged()) deps.applyRoute(deps.hashRoute || !!previous); if (overlay !== previous || (deps.hashRoute && revision !== owner)) return; deps.closeOverlay(); } /** @param {{voiceReaderOverlay?: boolean; readerUrl?: string} | null} state */ function restoreReaderOverlay(state) { if (!state || !state.voiceReaderOverlay || !state.readerUrl) { deps.reconcile(); return; } try { const url = navigation.parse(state.readerUrl); const owner = revision + (overlay ? 1 : 0); deps.closeOverlay(false, false); if (revision !== owner) return; deps.openOverlay(url, false); } catch (_) {} } /** @param {ReaderHostMessage} event */ function handleReaderMessage(event) { if (!navigation.accepts(/** @type {MessageEvent} */ (event))) return; const message = event.data || {}; if (message.type === "voice-reader-close") { if (closing) return; navigation.persistProgress(message.progress); closing = true; uiState = "base"; navigation.dismiss(); let returnUrl = deps.hashRoute ? "/search/" : "/"; try { const target = new URL(new URL(/** @type {HTMLIFrameElement} */ (overlay).src, location.origin).searchParams.get("return") || returnUrl, location.origin); if (target.origin === location.origin && (!deps.hashRoute || target.pathname === "/search/")) returnUrl = target.href; else if (deps.hashRoute) returnUrl = new URL("/search/", location.origin).href; } catch (_) {} if (!history.state?.voiceReaderOverlay) { const returnFocus = navigation.returnFocus; history.replaceState(history.state, "", returnUrl); deps.reconcile(); if (deps.hashRoute && returnFocus && returnFocus.isConnected) returnFocus.focus(); return; } const previous = overlay; history.back(); // A delayed Back still owns its Reader entry for Forward. setTimeout(() => { if (!closing || overlay !== previous) return; navigation.showCloseRecovery(returnUrl); }, 1000); return; } if (message.type === "voice-reader-ui-state") { if (closing) return; if (typeof message.state === "string" && ["base", "panel", "full-search"].includes(message.state)) uiState = message.state; return; } if (message.type === "voice-reader-theme") { if (message.theme !== "dark" && message.theme !== "light") return; deps.applyTheme(message.theme); return; } if (message.type === "voice-reader-open") { try { overlay = navigation.replace(/** @type {string} */ (message.url), /** @type {object} */ (position.scroll)); } catch (_) {} return; } if (message.type !== "voice-reader-navigate") return; try { const target = new URL(/** @type {string} */ (message.url), location.origin); if (target.origin !== location.origin || (deps.hashRoute ? target.pathname !== "/search/" : target.pathname.split("/").filter(Boolean).length !== 1)) return; history.replaceState(null, "", merge(target).href); deps.reconcile(); } catch (_) {} } /** @param {string} rawUrl @param {string} [returnUrl] */ function navigateToReader(rawUrl, returnUrl) { let target; try { target = navigation.parse(deps.syncFolder(rawUrl)); } catch (_) { return false; } deps.closeMobileSidebars(); const url = navigation.prepare(target.href, deps.normalizeReturn(returnUrl || location.href)); deps.openOverlay(url); return true; } function restoreReaderFromSession() { if (overlay) return; try { const saved = /** @type {{shareUrl?: string; readerUrl?: string; returnScroll?: ReaderReturnPosition} | null} */ (navigation.saved()); if (!saved || saved.shareUrl !== location.href || !saved.readerUrl) return; const url = navigation.parse(saved.readerUrl); position.setScroll(saved.returnScroll || null); history.replaceState({ voiceReaderOverlay: true, readerUrl: url.href }, "", saved.shareUrl); deps.openOverlay(url, false); } catch (_) {} } return Object.freeze({ navigation, keys, currentReaderSearchParams, normalizeReaderReturnUrl, syncReaderFolderFilter, closeReaderOverlay, openReaderOverlay, reconcileSearchDestination, restoreReaderOverlay, handleReaderMessage, navigateToReader, restoreReaderFromSession, get overlay() { return overlay; }, get closing() { return closing; }, get uiState() { return uiState; }, get returnSnapshot() { return snapshot; } }); } globalThis.VoiceOfMLReaderHost = Object.freeze({ create });})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120// Search geometry and focus handoff. The search host supplies only viewport operations.(function () { /** @param {ReaderReturnDependencies} deps */ function create(deps) { /** @type {ReaderReturnPosition | null} */ let scroll = null; let generation = 0, active = false; function captureReaderReturnScroll() { const view = deps.readView(); if (!view.hasContainer) return null; const top = deps.getTop(); let index = 0, offset = top; if (view.resultCount) { deps.ensureHeights(); index = deps.findIndex(top); offset = top - deps.getOffset(index); } const element = document.activeElement; const focus = element instanceof HTMLElement && element.id ? { id: element.id, start: element instanceof HTMLInputElement ? element.selectionStart : null, end: element instanceof HTMLInputElement ? element.selectionEnd : null, direction: element instanceof HTMLInputElement ? element.selectionDirection : null } : null; return { route: location.href, viewKey: deps.getViewKey(), top, index, offset, focus }; } /** @param {ReaderReturnPosition} saved */ function readerSearchHandoffReady(saved) { const view = deps.readView(); // A usable preview keeps ownership of its adjacent-page validation. if (view.loading || !view.loadedPage || !view.resultCount) return false; if (view.positionRestore && (!view.positionRestore.preview || view.positionRestore.key !== saved.viewKey)) return false; return deps.hasResult(Math.min(saved.index, Math.max(0, view.total - 1))); } function restoreReaderReturnScroll(windowRendered = false, restoreTop = false) { if (!scroll) return; const saved = scroll; if (saved.route && saved.route !== location.href) { scroll = null; return; } if (saved.viewKey && saved.viewKey !== deps.getViewKey()) { scroll = null; return; } const owner = ++generation; let attempts = 0; function restore() { if (owner !== generation || saved.viewKey !== deps.getViewKey() || saved.route !== location.href) return; const view = deps.readView(); if (!view.hasContainer || !view.resultCount) { if (++attempts < 20) requestAnimationFrame(restore); return; } deps.ensureHeights(); const index = Math.min(saved.index, view.resultCount - 1); const target = Math.max(0, restoreTop ? saved.top : deps.getOffset(index) + saved.offset); const max = Math.max(0, deps.getTotalHeight() - view.containerHeight); active = true; deps.setTop(Math.min(target, max)); if (!windowRendered) deps.invalidateWindow(); deps.renderVisible(); windowRendered = false; deps.updateTrack(); active = false; if (++attempts < 4 && Math.abs(deps.getTop() - target) > 1) requestAnimationFrame(restore); else scroll = null; } restore(); if (scroll === saved) requestAnimationFrame(() => requestAnimationFrame(restore)); } /** @param {ReturnType<SearchReaderNavigationApi['createNavigation']>} navigation */ function restoreReaderSearchHandoff(navigation) { /** @type {ReaderReturnPosition | null | undefined} */ let saved; try { const handoff = JSON.parse(sessionStorage.getItem("reader-navigation-restore") || "null"); sessionStorage.removeItem("reader-navigation-restore"); if (!handoff || handoff.returnUrl !== location.href) return; const current = /** @type {{readerUrl?: string; returnScroll?: ReaderReturnPosition} | null} */ (navigation.saved()); if (!current || current.readerUrl !== handoff.readerUrl) return; const url = navigation.parse(handoff.readerUrl); const token = url.searchParams.get("nav"); if (!token || sessionStorage.getItem("reader-return:" + token) !== location.href) return; saved = current.returnScroll; if (!saved || saved.route !== location.href || saved.viewKey !== deps.getViewKey() || !Number.isInteger(saved.index) || saved.index < 0 || !Number.isFinite(saved.offset) || !Number.isFinite(saved.top)) return; } catch (_) { return; } const position = saved; const route = location.href; let cancelled = false; const cancel = () => { cancelled = true; cleanup(); }; const events = ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"]; const cleanup = () => { for (const type of events) document.removeEventListener(type, cancel, true); }; for (const type of events) document.addEventListener(type, cancel, true); const revision = deps.readView().routeRevision; const deadline = Date.now() + 30000; const restore = () => { if (cancelled || revision !== deps.readView().routeRevision || location.href !== route || position.viewKey !== deps.getViewKey() || Date.now() > deadline) { cleanup(); return; } if (!deps.handoffReady(position)) { requestAnimationFrame(restore); return; } cleanup(); scroll = position; deps.restoreScroll(false, true); const focus = position.focus; const element = focus && document.getElementById(focus.id); if (!element || (document.activeElement !== document.body && document.activeElement !== element)) return; element.focus({ preventScroll: true }); if (element instanceof HTMLInputElement && Number.isInteger(focus.start) && Number.isInteger(focus.end) && focus.direction && ["forward", "backward", "none"].includes(focus.direction)) { try { element.setSelectionRange(focus.start, focus.end, focus.direction); } catch (_) {} } }; requestAnimationFrame(restore); } return Object.freeze({ capture: captureReaderReturnScroll, ready: readerSearchHandoffReady, restore: restoreReaderReturnScroll, restoreHandoff: restoreReaderSearchHandoff, get scroll() { return scroll; }, /** @param {ReaderReturnPosition | null} value */ setScroll(value) { scroll = value; }, invalidate() { generation++; }, cancelOnScroll() { if (scroll && !active) { generation++; scroll = null; } } }); } globalThis.VoiceOfMLReaderReturn = Object.freeze({ create });})();93 unmodified lines94959697989993 unmodified lines"/static/reader-resources.js","/static/reader/core/reader-contract.js","/static/search/reader-navigation.js","/static/search/input/domain/ownership.js","/static/search/input/application/controller.js","/static/search/sidebar/presentation/filter-list.js",93 unmodified lines94959697989910010193 unmodified lines"/static/reader-resources.js","/static/reader/core/reader-contract.js","/static/search/reader-navigation.js","/static/search/reader-host/presentation/return-position.js","/static/search/reader-host/application/host.js","/static/search/input/domain/ownership.js","/static/search/input/application/controller.js","/static/search/sidebar/presentation/filter-list.js",
581 unmodified lines582583584585586587588384 unmodified lines973974975976977978979980981982983581 unmodified linesself.assertIn('.reader-panel-tabs', reader_css)self.assertIn('function syncCurrentPageFromMarker', reader)self.assertNotIn('reader-docx-page', reader)self.assertIn('message.type === "voice-reader-open"', self.js)self.assertNotIn('loadFoliateDocument', reader)self.assertIn('async function renderFoliate', reader)foliate = (ROOT / "static/reader/formats/reader-foliate-format.mjs").read_text(encoding="utf-8")384 unmodified lines"function restoreReaderReturnScroll","viewKey: \"\"","heightCache: new Map()","readerNavigation.remember(url, readerReturnScrollState)","if (saved.viewKey && saved.viewKey !== getSearchViewKey())","if (readerReturnScrollState && !readerReturnRestoreActive)",):self.assertIn(value, self.js)self.assertIn("searchWithInitialFallback();", self.js)self.assertIn("validSearchViewport(viewport, position)", self.js)self.assertIn("return searchWithInitialFallbackFresh(intent);", self.js)581 unmodified lines582583584585586587588589590384 unmodified lines975976977978979980981982983984985986987988581 unmodified linesself.assertIn('.reader-panel-tabs', reader_css)self.assertIn('function syncCurrentPageFromMarker', reader)self.assertNotIn('reader-docx-page', reader)self.assertIn('message.type === "voice-reader-open"',(ROOT / "static/search/reader-host/application/host.js").read_text())self.assertIn('readerHost.handleReaderMessage(event)', self.js)self.assertNotIn('loadFoliateDocument', reader)self.assertIn('async function renderFoliate', reader)foliate = (ROOT / "static/reader/formats/reader-foliate-format.mjs").read_text(encoding="utf-8")384 unmodified lines"function restoreReaderReturnScroll","viewKey: \"\"","heightCache: new Map()","readerReturnPosition.cancelOnScroll()",):self.assertIn(value, self.js)host = (ROOT / "static/search/reader-host/application/host.js").read_text()position = (ROOT / "static/search/reader-host/presentation/return-position.js").read_text()self.assertIn("navigation.remember(url, /** @type {object} */ (position.scroll))", host)self.assertIn("if (saved.viewKey && saved.viewKey !== deps.getViewKey())", position)self.assertIn("if (scroll && !active) { generation++; scroll = null; }", position)self.assertIn("searchWithInitialFallback();", self.js)self.assertIn("validSearchViewport(viewport, position)", self.js)self.assertIn("return searchWithInitialFallbackFresh(intent);", self.js)
1 unmodified line234567241 unmodified lines2492502512522532541 unmodified lineimport asyncioimport unittestfrom types import SimpleNamespacefrom backend import appfrom tests.proxy.test_async_proxy import FakeResponse, FakeSession241 unmodified linesself.assertEqual(len(session.urls),2)self.assertEqual([first.status_code,second.status_code],[304,304])async def test_shutdown_stops_active_shared_body_and_releases_pool(self):upstream = GatedResponse()app.app.state.http_session = FakeSession([upstream])1 unmodified line2345678241 unmodified lines2502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034041 unmodified lineimport asyncioimport unittestfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, Mock, patchfrom backend import appfrom tests.proxy.test_async_proxy import FakeResponse, FakeSession241 unmodified linesself.assertEqual(len(session.urls),2)self.assertEqual([first.status_code,second.status_code],[304,304])async def test_queued_document_resolves_opener_and_session_after_admission(self):entered = asyncio.Event()class Gate(asyncio.Semaphore):async def acquire(self):entered.set()return await super().acquire()semaphore = app.app.state.upstream_semaphore = Gate(0)upstream = FakeResponse(200, {'Content-Length': '4'}, (b'abcd',))request = SimpleNamespace(method='GET', headers={})with patch.object(app, 'open_download_response', AsyncMock()) as stale:pending = asyncio.create_task(app._stream_reader_document(request, URL))await asyncio.wait_for(entered.wait(), 1)session = app.app.state.http_session = object()with patch.object(app, 'open_download_response', AsyncMock(return_value=upstream)) as current:semaphore.release()response = await asyncio.wait_for(pending, 1)self.assertIs(current.call_args.args[0], session)self.assertIs(current.call_args.kwargs['url_validator'], app.validate_reader_redirect_url)stale.assert_not_called()self.assertEqual(await self.drain(response), b'abcd')self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)async def test_suspended_headers_resolve_compression_isolation_and_response_hooks(self):entered, resume = asyncio.Event(), asyncio.Event()upstream = FakeResponse(200, {'Content-Length': '4', 'ETag': '"strong"'}, (b'abcd',))app.app.state.http_session = object()async def opener(*_args, **_kwargs):entered.set()await resume.wait()return upstreamwith patch.object(app, 'open_download_response', opener):pending = asyncio.create_task(app._stream_reader_document(SimpleNamespace(method='GET', headers={}), URL))await asyncio.wait_for(entered.wait(), 1)original_browser, original_timing = app.reader_document_browser_headers, app.reader_proxy_timingwith patch.object(app, 'READER_ISOLATION_HEADERS', {'X-Live-Isolation': 'yes'}), \patch.object(app, 'READER_UPSTREAM_RESPONSE_HEADERS', ('Content-Length', 'ETag')), \patch.object(app, 'reader_body_allows_compression', return_value=True) as compression, \patch.object(app, 'reader_document_browser_headers', wraps=original_browser) as browser, \patch.object(app, 'reader_proxy_timing', wraps=original_timing) as timing:resume.set()response = await asyncio.wait_for(pending, 1)self.assertEqual(response.headers['etag'], 'W/"strong"')self.assertEqual(response.headers['x-live-isolation'], 'yes')self.assertNotIn('content-encoding', response.headers)self.assertIn('reader_cache;desc="miss"', response.headers['server-timing'])compression.assert_called_once()browser.assert_called_once()timing.assert_called_once()self.assertEqual(await self.drain(response), b'abcd')self.assertTrue(upstream.released)self.assertEqual(app.app.state.upstream_semaphore._value, 2)async def test_body_limit_keeps_captured_cap_and_resolves_live_error_hook(self):upstream = GatedResponse()upstream.status = 200upstream.headers = {}app.app.state.http_session = FakeSession([upstream])with patch.object(app, 'READER_DOCUMENT_MAX_BYTES', 3):response = await app._stream_reader_document(SimpleNamespace(method='GET', headers={}), URL)self.assertEqual(await anext(response.body_iterator), b'ab')class CurrentLimitError(ValueError):passwith patch.object(app, 'READER_DOCUMENT_MAX_BYTES', 100), \patch.object(app, 'ReaderDocumentLimitError', CurrentLimitError):upstream.resume.set()with self.assertRaisesRegex(CurrentLimitError, '阅读文件过大'):await self.drain(response)self.assertEqual(upstream.release_count, 1)self.assertEqual(app.app.state.upstream_semaphore._value, 2)self.assertFalse(app.app.state.reader_range_cache)async def test_cache_admission_at_iteration_and_eviction_after_suspended_body(self):for stage in ('admission', 'completion'):with self.subTest(stage=stage):upstream = GatedResponse()app.app.state.http_session = FakeSession([upstream])response = await app._stream_reader_document(SimpleNamespace(method='GET', headers={'Range': 'bytes=0-3'}), URL, _share_range=False)if stage == 'admission':with patch.object(app, 'READER_RANGE_CACHE_MAX_ITEM_BYTES', 3):self.assertEqual(await anext(response.body_iterator), b'ab')upstream.resume.set()self.assertEqual(await self.drain(response), b'cd')else:self.assertEqual(await anext(response.body_iterator), b'ab')# Publication follows the live cache and budget after the await.cache = app.app.state.reader_range_cache = app.OrderedDict()app.app.state.reader_range_cache_bytes = 0with patch.object(app, 'READER_RANGE_CACHE_MAX_BYTES', 3):upstream.resume.set()self.assertEqual(await self.drain(response), b'cd')self.assertIs(app.app.state.reader_range_cache, cache)self.assertEqual(upstream.release_count, 1)self.assertEqual(app.app.state.upstream_semaphore._value, 2)self.assertFalse(app.app.state.reader_range_cache)self.assertEqual(app.app.state.reader_range_cache_bytes, 0)async def test_replaced_validator_identity_cannot_authorize_old_policy_cache(self):key = (URL, 'bytes=0-3', app.READER_DOCUMENT_MAX_BYTES, None)headers = {'Content-Length': '4', 'Content-Range': 'bytes 0-3/10'}app.app.state.reader_range_cache[key] = (app.time.monotonic(), b'old!', headers)app.app.state.reader_range_cache_bytes = 4original = app.validate_reader_redirect_url# Defaults capture the original function; policy checks must see the live function.with patch.object(app, 'validate_reader_redirect_url', lambda value: original(value)):upstream = GatedResponse()session = app.app.state.http_session = FakeSession([upstream])response = await self.open()upstream.resume.set()self.assertEqual(await self.drain(response), b'abcd')self.assertEqual(len(session.urls), 1)self.assertEqual(app.app.state.reader_range_cache[key][1], b'old!')original_bucket = app.validate_reader_bucket_redirect_urlwith patch.object(app, 'validate_reader_bucket_redirect_url', lambda value, _source: value):upstream = GatedResponse()session = app.app.state.http_session = FakeSession([upstream])response = await self.open(url_validator=lambda value: value,validation_scope=(original_bucket, URL))upstream.resume.set()self.assertEqual(await self.drain(response), b'abcd')self.assertEqual(len(session.urls), 1)self.assertEqual(app.app.state.reader_range_cache[key][1], b'old!')async def test_shared_producer_selects_stream_hook_when_task_starts(self):request = SimpleNamespace(method='GET', headers={'Range': 'bytes=0-3'})options = app.ReaderStreamOptions(url_validator=app.validate_reader_redirect_url,cache_control=None, max_bytes=100, media_type=None, validation_scope=None)key = (URL, 'bytes=0-3', 100, None)# Replacement happens after flight admission, before its task runs.response = app.Response(b'abcd', status_code=206, headers=app.reader_proxy_timing({}, cache='miss'))current = AsyncMock(return_value=response)stale = Mock(side_effect=AssertionError('captured the stream hook at admission'))patcher = patch.object(app, '_stream_reader_document', current)def switch_hook():patcher.start()return 1.0with patch.object(app, '_stream_reader_document', stale), \patch.object(app, 'time', SimpleNamespace(monotonic=switch_hook)):try:selected = await app.shared_reader_range_response(request, URL, key, options)self.assertEqual(await self.drain(selected), b'abcd')current.assert_awaited_once_with(request, URL, _share_range=False, **options)stale.assert_not_called()finally:patcher.stop()self.assertFalse(app.app.state.reader_range_flights)self.assertFalse(app.app.state.reader_range_flight_owners)async def test_shutdown_stops_active_shared_body_and_releases_pool(self):upstream = GatedResponse()app.app.state.http_session = FakeSession([upstream])
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119import assert from 'node:assert/strict';import fs from 'node:fs';import vm from 'node:vm';import test from 'node:test';import {APP_DEPENDENCIES, stripBundledScripts} from '../../../scripts/build/compose_app.mjs';
const paths = ['search/reader-host/presentation/return-position.js', 'search/reader-host/application/host.js'];function context(values = {}) { const c = vm.createContext({URL, URLSearchParams, ...values}); for (const path of paths) vm.runInContext(fs.readFileSync('static/' + path, 'utf8'), c); return c;}
test('reader host dependencies are composed, cached and loaded before the app', () => { const html = fs.readFileSync('static/index.html', 'utf8'), c = context(); vm.runInContext(fs.readFileSync('static/reader-resources.js', 'utf8'), c); for (const path of paths) { assert.ok(APP_DEPENDENCIES.indexOf(path) > APP_DEPENDENCIES.indexOf('search/reader-navigation.js')); assert.ok(html.indexOf(path) > html.indexOf('search/reader-navigation.js')); assert.ok(html.indexOf(path) < html.indexOf('static/app.js')); assert.ok(!stripBundledScripts(html).includes(path)); assert.ok(fs.readFileSync('static/sw.js', 'utf8').includes('/static/' + path)); for (const site of ['github', 'huggingface']) assert.ok(c.VoiceOfMLReaderResources.buildFiles(site).includes(path)); const source = fs.readFileSync('static/' + path, 'utf8'); assert.doesNotMatch(source, /\bSTATE\b|\bVSCROLL\b|\bDOM\b|new Proxy/); }});
test('return position owns scroll cancellation and retires queued route restores', () => { const frames = [], writes = []; const location = new URL('https://example.test/search/'); const c = context({location, requestAnimationFrame: fn => frames.push(fn)}); let view = {hasContainer:true, containerHeight:100, resultCount:5}, position, render; const deps = {readView:()=>view, getViewKey:()=> 'view', ensureHeights(){}, getOffset:i=>i*100, getTotalHeight:()=>500, setTop:top=>{writes.push(top);position.cancelOnScroll();}, getTop:()=>110, invalidateWindow(){}, renderVisible:()=>render?.(), updateTrack(){}}; position = c.VoiceOfMLReaderReturn.create(deps); const saved = {route:location.href,viewKey:'view',index:1,offset:10,top:110,focus:null}; position.setScroll(saved); position.restore(); assert.deepEqual(writes,[110], 'synchronous scroll event cannot cancel the active restoration'); view = {...view,resultCount:0}; position.setScroll(saved);position.restore(); position.invalidate();view.resultCount=5; while(frames.length) frames.shift()(); assert.deepEqual(writes,[110], 'route invalidation retires callbacks already queued'); position.cancelOnScroll();assert.equal(position.scroll,null); render=()=>writes.push('new renderer'); position.setScroll(saved);position.restore(); assert.equal(writes.at(-1),'new renderer','effects resolve the current host hook');});
test('handoff requires the matching session token and yields to input ownership', () => { for (const mode of ['valid','missing-token','blocked-storage','input','new-route']) { const frames=[],listeners=new Map(),writes=[],focused=[]; const location=new URL('https://example.test/search/'); class Input { focus(options){focused.push(options);} setSelectionRange(...args){focused.push(args);} } const input=new Input(),body={}; const saved={route:location.href,viewKey:'view',index:0,offset:3,top:3, focus:{id:'query',start:1,end:3,direction:'backward'}}; const readerUrl='https://example.test/reader?nav=token'; const stored=new Map([ ['reader-navigation-restore',JSON.stringify({returnUrl:location.href,readerUrl})], ['reader-return:token',location.href] ]); if(mode==='missing-token') stored.delete('reader-return:token'); const c=context({location,HTMLInputElement:Input,requestAnimationFrame:fn=>frames.push(fn), sessionStorage:{getItem(key){if(mode==='blocked-storage') throw Error('blocked');return stored.get(key);},removeItem:key=>stored.delete(key)}, document:{body,activeElement:body,getElementById:()=>input, addEventListener:(type,fn)=>listeners.set(type,fn),removeEventListener:type=>listeners.delete(type)}}); let revision=1; const position=c.VoiceOfMLReaderReturn.create({ readView:()=>({hasContainer:true,containerHeight:100,resultCount:1,total:1,loading:false,loadedPage:1, positionRestore:{key:'view',preview:true},routeRevision:revision}), hasResult:()=>true,getViewKey:()=> 'view',ensureHeights(){},getOffset:()=>0,getTotalHeight:()=>500, setTop:top=>writes.push(top),getTop:()=>3,invalidateWindow(){},renderVisible(){},updateTrack(){}, handoffReady:saved=>position.ready(saved),restoreScroll:(rendered,top)=>position.restore(rendered,top) }); position.restoreHandoff({saved:()=>({readerUrl,returnScroll:saved}),parse:raw=>new URL(raw)}); if(mode==='input') listeners.get('input')(); if(mode==='new-route') revision++; while(frames.length) frames.shift()(); assert.equal(listeners.size,0,'interaction listeners are released'); if(mode==='valid') { assert.deepEqual(writes,[3]); assert.equal(focused[0].preventScroll,true); assert.deepEqual(focused[1],[1,3,'backward']); } else {assert.deepEqual(writes,[]);assert.deepEqual(focused,[]);} }});
test('host release is synchronous and disposal reentry keeps the newer reader', () => { for (const hashRoute of [false,true]) { const location = new URL('https://example.test' + (hashRoute ? '/search/' : '/')); const history = {state:null,replaceState(state, unused, url){this.state=state;location.href=url;}}; const c = context({location,history}); let scroll=null,host,onUnmount,focuses=0,restores=0; const position = {get scroll(){return scroll;},setScroll:value=>{scroll=value;}}; const navigation = {parse:raw=>new URL(raw,location),mount:url=>({src:url.href,contentWindow:{}}), unmount(){onUnmount?.();return {isConnected:true,focus(){focuses++;}};},remember(){}, accepts:event=>!!host.overlay && event.origin===location.origin && event.source===host.overlay.contentWindow}; const deps = {hashRoute,position,createNavigation:()=>navigation,getViewKey:()=> 'view', captureScroll:()=>null,saveSnapshot:()=>null,restoreScroll:()=>restores++, openOverlay:(...args)=>host.openReaderOverlay(...args),closeOverlay:(...args)=>host.closeReaderOverlay(...args), reconcile:()=>host.reconcileSearchDestination(),routeChanged:()=>false,applyTheme(){throw Error('unexpected theme');}}; host=c.VoiceOfMLReaderHost.create(deps); host.openReaderOverlay(new URL('/reader?id=old',location)); const first=host.overlay; host.handleReaderMessage({origin:'https://other.test',source:first.contentWindow,data:{type:'voice-reader-theme',theme:'dark'}}); host.handleReaderMessage({origin:location.origin,source:{},data:{type:'voice-reader-theme',theme:'dark'}}); assert.equal(host.overlay,first); onUnmount=()=>{assert.equal(host.overlay,null);host.openReaderOverlay(new URL('/reader?id=new',location),false);}; host.restoreReaderOverlay({voiceReaderOverlay:true,readerUrl:'/reader?id=stale'}); assert.equal(new URL(host.overlay.src).searchParams.get('id'),'new'); assert.equal(restores,0);assert.equal(focuses,0); onUnmount=null;host.closeReaderOverlay(); assert.equal(host.overlay,null);assert.equal(restores,1);assert.equal(focuses,1); }});3 unmodified lines4567892 unmodified lines1213141516173 unmodified linesimport fs from 'node:fs';import vm from 'node:vm';import test from 'node:test';import '../paging/result_window_contracts.mjs';import { installClassicSearchModules } from '../../support/classic_search_modules.js';import { APP_DEPENDENCIES, stripBundledScripts } from '../../../scripts/build/compose_app.mjs';2 unmodified linesfunction fixture(names, values = {}) {const context = vm.createContext({AbortController, searchTransport:undefined, searchPagePrefetch:undefined, ...values});installClassicSearchModules(process.cwd(), context);for (const name of names) {const match = source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));assert.ok(match, name);3 unmodified lines456789102 unmodified lines1314151617181920212223243 unmodified linesimport fs from 'node:fs';import vm from 'node:vm';import test from 'node:test';import './host_contracts.mjs';import '../paging/result_window_contracts.mjs';import { installClassicSearchModules } from '../../support/classic_search_modules.js';import { APP_DEPENDENCIES, stripBundledScripts } from '../../../scripts/build/compose_app.mjs';2 unmodified linesfunction fixture(names, values = {}) {const context = vm.createContext({AbortController, searchTransport:undefined, searchPagePrefetch:undefined, ...values});installClassicSearchModules(process.cwd(), context);context.readerHost = {overlay: null};context.readerReturnPosition = context.VoiceOfMLReaderReturn.create({readView: () => ({loading: context.STATE.isLoading, loadedPage: context.STATE._loadedPage,resultCount: context.STATE.results.length, total: context.STATE.total, positionRestore: context.positionRestore}),hasResult: index => !!context.STATE.results[index]});for (const name of names) {const match = source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));assert.ok(match, name);
5 unmodified lines678910115 unmodified linesconst vm = require("vm");const MODULES = ["static/search/folder-selection.js", "static/search/domain/height-index.js","static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js","static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"];const sources = new Map();5 unmodified lines67891011125 unmodified linesconst vm = require("vm");const MODULES = ["static/search/folder-selection.js", "static/search/domain/height-index.js","static/search/reader-host/presentation/return-position.js", "static/search/reader-host/application/host.js","static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js","static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"];const sources = new Map();
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253interface ReaderReturnPosition { route: string; viewKey: string; top: number; index: number; offset: number; focus: { id: string; start: number | null; end: number | null; direction: "forward" | "backward" | "none" | null } | null;}interface ReaderReturnDependencies { readView(): { hasContainer: boolean; containerHeight: number; resultCount: number; total: number; loading: boolean; loadedPage: number; positionRestore: { preview?: boolean; key: string } | null; routeRevision: number }; hasResult(index: number): boolean; getViewKey(): string; getTop(): number; setTop(top: number): void; ensureHeights(): void; findIndex(top: number): number; getOffset(index: number): number; getTotalHeight(): number; invalidateWindow(): void; renderVisible(): void; updateTrack(): void; handoffReady(saved: ReaderReturnPosition): boolean; restoreScroll(rendered: boolean, top: boolean): void;}interface ReaderReturnController { capture(): ReaderReturnPosition | null; ready(saved: ReaderReturnPosition): boolean; restore(windowRendered?: boolean, restoreTop?: boolean): void; restoreHandoff(navigation: ReturnType<SearchReaderNavigationApi['createNavigation']>): void; readonly scroll: ReaderReturnPosition | null; setScroll(value: ReaderReturnPosition | null): void; invalidate(): void; cancelOnScroll(): void;}// The snapshot is an opaque identity handle; only the host reads its payload.interface ReaderHostSnapshot { readonly results: readonly unknown[]; readonly loadedPage: number }interface ReaderHostMessage { origin: string; source: MessageEventSource | null; data: { type?: string; state?: string; theme?: string; url?: string; progress?: {url?: unknown; closeTime?: unknown} | null };}interface ReaderHostDependencies { hashRoute: boolean; position: ReaderReturnController; createNavigation(options: {resume(url: string): void; close(): void}): ReturnType<SearchReaderNavigationApi['createNavigation']>; buildParams(): URLSearchParams; readQuery(): string; currentParams(): URLSearchParams; getViewKey(): string; captureScroll(): ReaderReturnPosition | null; restoreScroll(): void; saveSnapshot(key: string): ReaderHostSnapshot | null; snapshotChanged(snapshot: ReaderHostSnapshot, key: string): boolean; restoreSnapshot(key: string): void; routeChanged(): boolean; applyRoute(preserve: boolean): void; closeMobileSidebars(): void; applyTheme(theme: "dark" | "light"): void; navigate(url: string): void; handleMessage(event: ReaderHostMessage): void; syncFolder(url: string): string; normalizeReturn(url: string): string; openOverlay(url: URL, addHistory?: boolean): void; closeOverlay(focus?: boolean, scroll?: boolean): void; reconcile(): void;}declare var VoiceOfMLReaderReturn: { create(deps: ReaderReturnDependencies): ReaderReturnController };declare var VoiceOfMLReaderHost: { create(deps: ReaderHostDependencies): { readonly navigation: ReturnType<SearchReaderNavigationApi['createNavigation']>; readonly keys: readonly string[]; readonly overlay: HTMLIFrameElement | null; readonly closing: boolean; readonly uiState: string; readonly returnSnapshot: ReaderHostSnapshot | null; currentReaderSearchParams(): URLSearchParams; normalizeReaderReturnUrl(raw: string): string; syncReaderFolderFilter(raw: string): string; closeReaderOverlay(focus?: boolean, scroll?: boolean): boolean; openReaderOverlay(url: URL, addHistory?: boolean): void; reconcileSearchDestination(): void; restoreReaderOverlay(state: {voiceReaderOverlay?: boolean; readerUrl?: string} | null): void; handleReaderMessage(event: ReaderHostMessage): void; navigateToReader(raw: string, returnUrl?: string): boolean; restoreReaderFromSession(): void;} };backend/app.py+49-378
backend/reader/document/__init__.pyAdded+1
backend/reader/document/application/__init__.pyAdded+1
backend/reader/document/application/ranges.pyAdded+127
backend/reader/document/domain/__init__.pyAdded+1
backend/reader/document/domain/policy.pyAdded+36
backend/reader/document/http/__init__.pyAdded+1
backend/reader/document/http/transport.pyAdded+331
config/types/jsconfig.check.json+3
config/types/jsconfig.search-exact.json+3
config/types/jsconfig.strict.json+3
eslint.config.mjs+1-1
pyrightconfig.strict.json+7
scripts/build/check_reader_release.mjs+1
scripts/build/compose_app.mjs+1
static/app.js+79-274
static/index.html+2
static/reader-resources.js+1
static/search/reader-host/application/host.jsAdded+191
static/search/reader-host/presentation/return-position.jsAdded+120
static/sw.js+2
tests/gates/test_static_contract.py+9-4
tests/reader/backend/test_reader_range_flights.py+150
tests/search/reader-navigation/host_contracts.mjsAdded+119
tests/search/reader-navigation/test_search_history_races.mjs+7
tests/support/classic_search_modules.js+1
typings/search-reader-host.d.tsAdded+53