vomebook commited on
Commit ·
7fa8ea9
1
Parent(s): adf992d
Layer Reader bucket resources and result-window page loading
Browse filesFiles changed (27)
- backend/app.py+52-190
- backend/reader/bucket/__init__.pyAdded+1
- backend/reader/bucket/application/__init__.pyAdded+1
- backend/reader/bucket/application/resources.pyAdded+125
- backend/reader/bucket/domain/__init__.pyAdded+1
- backend/reader/bucket/domain/policy.pyAdded+65
- backend/reader/bucket/http/__init__.pyAdded+1
- backend/reader/bucket/http/routes.pyAdded+98
- config/types/jsconfig.check.json+2
- config/types/jsconfig.search-exact.json+2
- config/types/jsconfig.strict.json+2
- eslint.config.mjs+1-1
- pyrightconfig.strict.json+7
- scripts/build/check_reader_release.mjs+2
- scripts/build/compose_app.mjs+1
- static/app.js+24-87
- static/index.html+2
- static/reader-resources.js+2
- static/search/results/window/application/page-loader.jsAdded+76
- static/search/results/window/presentation/status.jsAdded+43
- static/sw.js+2
- tests/gates/test_static_contract.py+4-1
- tests/reader/backend/test_reader_backend.py+227
- tests/search/paging/result_window_contracts.mjsAdded+180
- tests/search/reader-navigation/test_search_history_races.mjs+1
- tests/support/classic_search_modules.js+2-1
- typings/reader-globals.d.ts+38
18 unmodified lines192021222324251680 unmodified lines17061707170817091710171143 unmodified lines175517561757175817591760176117621763176417651 unmodified line176717681769177017711772177317741775177617771778177917801781178217834 unmodified lines1788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318444 unmodified lines1849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193151 unmodified lines19831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204818 unmodified linesimport zipfile as zipfileimport zlibfrom pathlib import Pathfrom typing import BinaryIO, Optional, Protocol, Sequence, TypedDict, TypeVar, castfrom urllib.parse import unquote, quote, urlparse, parse_qsimport aiohttpimport orjson1680 unmodified linesrun_worker as _run_reader_archive_worker, get_archive as _get_reader_archive,)from backend.reader.archive.http.routes import ArchiveRouteDependencies, reader_resource as _reader_resourceclass _LiveReaderArchiveLimits:43 unmodified lines"mp4": "video/mp4", "mov": "video/quicktime", "swf": "application/x-shockwave-flash", "gz": "application/gzip",}def initialize_reader_bucket_state(target_app: FastAPI) -> None:target_app.state.reader_bucket_cache = OrderedDict()target_app.state.reader_bucket_cache_bytes = 0target_app.state.reader_bucket_inflight = {}target_app.state.reader_bucket_workers = set()target_app.state.reader_bucket_semaphore = asyncio.Semaphore(READER_BUCKET_MAX_CONCURRENT_READS)target_app.state.reader_ocr_cache = OrderedDict()target_app.state.reader_ocr_cache_bytes = 0target_app.state.reader_ocr_inflight = {}1 unmodified lineasync def shutdown_reader_bucket_state(target_app: FastAPI) -> None:tasks = list(target_app.state.reader_bucket_inflight.values())target_app.state.reader_bucket_inflight.clear()for task in tasks:task.cancel()if tasks:await asyncio.gather(*tasks, return_exceptions=True)workers = list(target_app.state.reader_bucket_workers)if workers:await asyncio.gather(*workers, return_exceptions=True)target_app.state.reader_bucket_cache.clear()target_app.state.reader_bucket_cache_bytes = 0target_app.state.reader_ocr_cache.clear()target_app.state.reader_ocr_cache_bytes = 0ocr_tasks = list(getattr(target_app.state, "reader_ocr_inflight", {}).values())4 unmodified linesawait asyncio.gather(*ocr_tasks, return_exceptions=True)def is_reader_bucket_cacheable(path: str) -> bool:return (path.endswith("/page-manifest.json") or path.endswith("/ocr-manifest.json")or path.endswith('/reading-manifest.json') or path.endswith('/page-map.json.gz')or path.endswith("/ocr/book-text.json.gz") or path.endswith("/pages/page-000001.webp")or (path.startswith("objects/") and path.rsplit("/", 1)[-1].startswith("document."))or (path.startswith("chapters/ebook/") and any(path.endswith(suffix) for suffix in ("/chapter-manifest.json", "/epub-search-index.json.gz",))))def reader_bucket_cache_control(path: str) -> str:# Page paths contain the source digest and an optional asset version, so a# generated image can be cached immutably even though the manifest moves.if re.search(r"/pages/page-[0-9]{6}\.(?:webp|jxl|png)$", path):return "public, max-age=31536000, immutable"if re.fullmatch(r"objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:preview|text)/.+", path):return "public, max-age=31536000, immutable"if path.startswith("objects/") and path.rsplit("/", 1)[-1].startswith("document."):return "public, max-age=31536000, immutable"if "/ebook-chapters/" in path:return "public, max-age=31536000, immutable"return "public, max-age=3600"def reader_bucket_for_path(path: str) -> str:if (path.startswith(("documents/", "chapters/", "media/", "pages/image/", "native/"))):return "vomebook/reader-assets-v2"return "vomebook/pdf-pages-v2"def reader_bucket_source_url(path: str) -> str:bucket = reader_bucket_for_path(path)return f"https://huggingface.co/buckets/{bucket}/resolve/{quote(path, safe='/')}"class ReaderBucketBusyError(RuntimeError):"""Retryable admission failure: too many distinct bucket reads in flight."""READER_BUSY_HEADERS = {"Cache-Control": "no-store", "Retry-After": "1"}class ReaderIntegrity(TypedDict, total=False):"""Pinned page-image checksum forwarded to stream_reader_document."""expected_sha256: strexpected_bytes: intclass ReaderStreamOptions(TypedDict):"""Transport policy shared by every subscriber of one range flight."""url_validator: Callable[[str], str]4 unmodified linesdef validate_reader_bucket_redirect_url(url: str, source_url: str) -> str:try:return validate_fixed_source_redirect_url(url, source_url)except ValueError as exc:raise ValueError("上游重定向超出允许的阅读资源范围") from excclass _BucketFileSystem(Protocol):"""The one HfFileSystem method used here, typed because the library stub leaves it unknown."""def open(self, path: str, mode: str) -> BinaryIO: ...def read_reader_bucket_resource(path: str, max_bytes: int = READER_RESOURCE_MAX_BYTES) -> bytes:filesystem = cast(_BucketFileSystem, HfFileSystem())bucket = reader_bucket_for_path(path)with filesystem.open(f"hf://buckets/{bucket}/{path}", "rb") as stream:payload = stream.read(max_bytes + 1)if len(payload) > max_bytes:raise ValueError("阅读资源过大")return payloadasync def get_reader_bucket_resource(path: str, max_bytes: int = READER_RESOURCE_MAX_BYTES) -> bytes:state = app.statecache_key = pathif is_reader_bucket_cacheable(path):cached = state.reader_bucket_cache.get(cache_key)if cached:cached_at, payload = cachedif time.monotonic() - cached_at < READER_BUCKET_CACHE_TTL_SECONDS:state.reader_bucket_cache.move_to_end(cache_key)return payloadstate.reader_bucket_cache.pop(cache_key)state.reader_bucket_cache_bytes -= len(payload)task = state.reader_bucket_inflight.get(cache_key)if task is None:if len(state.reader_bucket_inflight) >= READER_BUCKET_MAX_INFLIGHT:raise ReaderBucketBusyError("too many reader bucket requests")async def load() -> bytes:try:payload = await run_reader_bucket_read(path, max_bytes)if is_reader_bucket_cacheable(path) and len(payload) <= READER_BUCKET_CACHE_MAX_ITEM_BYTES:previous = state.reader_bucket_cache.pop(cache_key, None)if previous:state.reader_bucket_cache_bytes -= len(previous[1])state.reader_bucket_cache[cache_key] = (time.monotonic(), payload)state.reader_bucket_cache_bytes += len(payload)while state.reader_bucket_cache_bytes > READER_BUCKET_CACHE_MAX_BYTES:_, (_, evicted) = state.reader_bucket_cache.popitem(last=False)state.reader_bucket_cache_bytes -= len(evicted)return payloadfinally:if state.reader_bucket_inflight.get(cache_key) is asyncio.current_task():state.reader_bucket_inflight.pop(cache_key, None)task = asyncio.create_task(load())task.add_done_callback(lambda done: None if done.cancelled() else done.exception())state.reader_bucket_inflight[cache_key] = taskreturn await asyncio.shield(task)async def run_reader_bucket_read(path: str, max_bytes: int) -> bytes:state = app.statesemaphore = state.reader_bucket_semaphoreawait semaphore.acquire()worker = asyncio.create_task(asyncio.to_thread(read_reader_bucket_resource, path, max_bytes))state.reader_bucket_workers.add(worker)def finished(done: "asyncio.Task[bytes]") -> None:# Cancelling an async caller cannot stop its filesystem thread.state.reader_bucket_workers.discard(done)semaphore.release()if not done.cancelled():done.exception()worker.add_done_callback(finished)return await asyncio.shield(worker)def parse_reader_ocr_book(raw: bytes) -> tuple[list[OcrPage], int]:51 unmodified lines@app.api_route("/api/reader-bucket-resource", methods=["GET", "HEAD"])async def api_reader_bucket_resource(path: str = Query(...), request: Request = cast(Request, None)):# The query value is already decoded once by the framework, matching the# single quote() applied by every generator; a literal "%41" stays literal.resource_path = path.replace("\\", "/").lstrip("/")try:traversal = any(part in (".", "..") for part in decode_url_path(resource_path).split("/"))except ValueError:traversal = Trueif traversal or not READER_BUCKET_PATH_RE.fullmatch(resource_path):return JSONResponse({"error": "不允许的阅读资源路径"}, status_code=400,headers={"Cache-Control": "no-store"})suffix = resource_path.rsplit(".", 1)[-1].lower()media_type = READER_RESOURCE_TYPES.get(suffix, "application/octet-stream")integrity: ReaderIntegrity = {}pinned_png = suffix == 'png' and resource_path.startswith('objects/') and '/pages/page-' in resource_pathif suffix == 'jxl' or pinned_png:query = getattr(request, 'query_params', {})expected_sha = query.get('sha256', '')expected_size = query.get('bytes', '')if (not re.fullmatch(r'[0-9a-f]{64}', expected_sha)or not re.fullmatch(r'[0-9]{1,10}', expected_size)or not 0 < int(expected_size) <= READER_RESOURCE_MAX_BYTESor any(name in getattr(request, 'headers', {})for name in ('Range', 'If-Range', 'If-None-Match', 'If-Modified-Since'))):return JSONResponse({'error': '阅读页图缺少完整校验信息'}, status_code=400,headers={'Cache-Control': 'no-store'})integrity = {'expected_sha256': expected_sha, 'expected_bytes': int(expected_size)}# Uncached body resources must release transport on close, including office,# text and chapter bodies. Shared metadata/index cache reads remain bounded.if cast("Request | None", request) is not None and (suffix in {"pdf", "djvu"} or media_type.startswith(("audio/", "video/", "image/"))or not is_reader_bucket_cacheable(resource_path)):source_url = reader_bucket_source_url(resource_path)return await stream_reader_document(request, source_url,url_validator=lambda url: validate_reader_bucket_redirect_url(url, source_url),validation_scope=(validate_reader_bucket_redirect_url, source_url),cache_control=reader_bucket_cache_control(resource_path),max_bytes=(None if media_type.startswith(("audio/", "video/")) elseREADER_PDF_MAX_BYTES if suffix == "pdf" elseREADER_DOCUMENT_MAX_BYTES if suffix == "djvu" else READER_RESOURCE_MAX_BYTES),media_type=media_type,**integrity,)try:payload = await get_reader_bucket_resource(resource_path)except FileNotFoundError:return JSONResponse({"error": "阅读资源不存在"}, status_code=404,headers={"Cache-Control": "no-store"})except ReaderBucketBusyError:return JSONResponse({"error": "阅读资源请求过多,请稍后重试"}, status_code=503,headers=READER_BUSY_HEADERS)except Exception:return JSONResponse({"error": "阅读资源加载失败"}, status_code=502,headers={"Cache-Control": "no-store"})return Response(content=b"" if cast("Request | None", request) is not None and request.method == "HEAD" else payload,media_type=media_type,headers={**READER_ISOLATION_HEADERS,"Cache-Control": reader_bucket_cache_control(resource_path),"Content-Length": str(len(payload)),**({} if reader_body_allows_compression(resource_path, request) else {"Content-Encoding": "identity"})})def initialize_reader_archive_state(target_app: FastAPI) -> None:18 unmodified lines192021222324251680 unmodified lines17061707170817091710171117121713171417151716171717181719172017211722172317241725172643 unmodified lines17701771177217731774177517761 unmodified line17781779178017811782178317844 unmodified lines17891790179117921793179417951796179717981799180018014 unmodified lines18061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183551 unmodified lines18871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191018 unmodified linesimport zipfile as zipfileimport zlibfrom pathlib import Pathfrom typing import Optional, Sequence, TypedDict, TypeVar, castfrom urllib.parse import unquote, quote, urlparse, parse_qsimport aiohttpimport orjson1680 unmodified linesrun_worker as _run_reader_archive_worker, get_archive as _get_reader_archive,)from backend.reader.archive.http.routes import ArchiveRouteDependencies, reader_resource as _reader_resourcefrom backend.reader.bucket.domain.policy import (ReaderBucketBusyError as ReaderBucketBusyError,is_cacheable as is_reader_bucket_cacheable, cache_control as reader_bucket_cache_control,bucket_for_path as reader_bucket_for_path, source_url as _reader_bucket_source_url,resource_path as _reader_bucket_resource_path, validate_redirect_url as _validate_reader_bucket_redirect_url,)from backend.reader.bucket.application.resources import (BucketFileSystem as _BucketFileSystem, BucketState, BucketDependencies,initialize_state as _initialize_reader_bucket_state, shutdown_state as _shutdown_reader_bucket_state,read_resource as _read_reader_bucket_resource, get_resource as _get_reader_bucket_resource,run_read as _run_reader_bucket_read,)from backend.reader.bucket.http.routes import (ReaderIntegrity as ReaderIntegrity, BucketRouteDependencies, bucket_resource as _bucket_resource,)class _LiveReaderArchiveLimits:43 unmodified lines"mp4": "video/mp4", "mov": "video/quicktime", "swf": "application/x-shockwave-flash", "gz": "application/gzip",}def initialize_reader_bucket_state(target_app: FastAPI) -> None:_initialize_reader_bucket_state(cast(BucketState, target_app.state), READER_BUCKET_MAX_CONCURRENT_READS)target_app.state.reader_ocr_cache = OrderedDict()target_app.state.reader_ocr_cache_bytes = 0target_app.state.reader_ocr_inflight = {}1 unmodified lineasync def shutdown_reader_bucket_state(target_app: FastAPI) -> None:await _shutdown_reader_bucket_state(lambda: cast(BucketState, target_app.state))target_app.state.reader_ocr_cache.clear()target_app.state.reader_ocr_cache_bytes = 0ocr_tasks = list(getattr(target_app.state, "reader_ocr_inflight", {}).values())4 unmodified linesawait asyncio.gather(*ocr_tasks, return_exceptions=True)def reader_bucket_source_url(path: str) -> str:return _reader_bucket_source_url(path, lambda value: reader_bucket_for_path(value))READER_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]4 unmodified linesdef 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))def read_reader_bucket_resource(path: str, max_bytes: int = READER_RESOURCE_MAX_BYTES) -> bytes:return _read_reader_bucket_resource(path, max_bytes, lambda: cast(_BucketFileSystem, HfFileSystem()),lambda value: reader_bucket_for_path(value))async def get_reader_bucket_resource(path: str, max_bytes: int = READER_RESOURCE_MAX_BYTES) -> bytes:return await _get_reader_bucket_resource(cast(BucketState, app.state), path, max_bytes, BucketDependencies(cacheable=lambda value: is_reader_bucket_cacheable(value),run_read=lambda value, limit: run_reader_bucket_read(value, limit),cache_ttl=lambda: READER_BUCKET_CACHE_TTL_SECONDS,cache_max_item_bytes=lambda: READER_BUCKET_CACHE_MAX_ITEM_BYTES,cache_max_bytes=lambda: READER_BUCKET_CACHE_MAX_BYTES,max_inflight=lambda: READER_BUCKET_MAX_INFLIGHT,clock=lambda: time.monotonic(),))async def run_reader_bucket_read(path: str, max_bytes: int) -> bytes:return await _run_reader_bucket_read(cast(BucketState, app.state), path, max_bytes,lambda: read_reader_bucket_resource)def parse_reader_ocr_book(raw: bytes) -> tuple[list[OcrPage], int]:51 unmodified lines@app.api_route("/api/reader-bucket-resource", methods=["GET", "HEAD"])async def api_reader_bucket_resource(path: str = Query(...), request: Request = cast(Request, None)) -> Response:return await _bucket_resource(path, request, BucketRouteDependencies(resource_path=lambda value: _reader_bucket_resource_path(value, lambda target: decode_url_path(target), lambda: READER_BUCKET_PATH_RE),resource_types=lambda: READER_RESOURCE_TYPES,resource_max_bytes=lambda: READER_RESOURCE_MAX_BYTES,pdf_max_bytes=lambda: READER_PDF_MAX_BYTES,document_max_bytes=lambda: READER_DOCUMENT_MAX_BYTES,cacheable=lambda value: is_reader_bucket_cacheable(value),source_url=lambda value: reader_bucket_source_url(value),redirect_validator=lambda: validate_reader_bucket_redirect_url,cache_control=lambda value: reader_bucket_cache_control(value),stream=lambda: stream_reader_document,get_resource=lambda value: get_reader_bucket_resource(value),busy_headers=lambda: READER_BUSY_HEADERS,isolation_headers=lambda: READER_ISOLATION_HEADERS,allows_compression=lambda value, req: reader_body_allows_compression(value, req),))def initialize_reader_archive_state(target_app: FastAPI) -> None:
1"""Reader bucket resource delivery."""1"""Bucket read and cache lifecycle."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""Bounded bucket reads, shared loads, and ownership of filesystem workers."""import asynciofrom collections import OrderedDictfrom collections.abc import Awaitable, Callablefrom dataclasses import dataclassfrom typing import BinaryIO, Protocol
from backend.reader.bucket.domain.policy import ReaderBucketBusyError
class BucketFileSystem(Protocol): def open(self, path: str, mode: str) -> BinaryIO: ...
class BucketState(Protocol): reader_bucket_cache: OrderedDict[str, tuple[float, bytes]] reader_bucket_cache_bytes: int reader_bucket_inflight: dict[str, asyncio.Task[bytes]] reader_bucket_workers: set[asyncio.Task[bytes]] reader_bucket_semaphore: asyncio.Semaphore
@dataclass(frozen=True)class BucketDependencies: """Resolve hooks and limits where used, including after a suspended read."""
cacheable: Callable[[str], bool] run_read: Callable[[str, int], Awaitable[bytes]] cache_ttl: Callable[[], float] cache_max_item_bytes: Callable[[], int] cache_max_bytes: Callable[[], int] max_inflight: Callable[[], int] clock: Callable[[], float]
def initialize_state(state: BucketState, max_reads: int) -> None: state.reader_bucket_cache = OrderedDict() state.reader_bucket_cache_bytes = 0 state.reader_bucket_inflight = {} state.reader_bucket_workers = set() state.reader_bucket_semaphore = asyncio.Semaphore(max_reads)
async def shutdown_state(state: Callable[[], BucketState]) -> None: tasks = list(state().reader_bucket_inflight.values()) state().reader_bucket_inflight.clear() for task in tasks: task.cancel() if tasks: await asyncio.gather(*tasks, return_exceptions=True) workers = list(state().reader_bucket_workers) if workers: await asyncio.gather(*workers, return_exceptions=True) state().reader_bucket_cache.clear() state().reader_bucket_cache_bytes = 0
def read_resource(path: str, max_bytes: int, filesystem: Callable[[], BucketFileSystem], bucket: Callable[[str], str]) -> bytes: fs = filesystem() name = bucket(path) with fs.open(f"hf://buckets/{name}/{path}", "rb") as stream: payload = stream.read(max_bytes + 1) if len(payload) > max_bytes: raise ValueError("阅读资源过大") return payload
async def get_resource(state: BucketState, path: str, max_bytes: int, deps: BucketDependencies) -> bytes: cache_key = path if deps.cacheable(path): cached = state.reader_bucket_cache.get(cache_key) if cached: cached_at, payload = cached if deps.clock() - cached_at < deps.cache_ttl(): state.reader_bucket_cache.move_to_end(cache_key) return payload state.reader_bucket_cache.pop(cache_key) state.reader_bucket_cache_bytes -= len(payload)
task = state.reader_bucket_inflight.get(cache_key) if task is None: if len(state.reader_bucket_inflight) >= deps.max_inflight(): raise ReaderBucketBusyError("too many reader bucket requests")
async def load() -> bytes: try: payload = await deps.run_read(path, max_bytes) if deps.cacheable(path) and len(payload) <= deps.cache_max_item_bytes(): previous = state.reader_bucket_cache.pop(cache_key, None) if previous: state.reader_bucket_cache_bytes -= len(previous[1]) state.reader_bucket_cache[cache_key] = (deps.clock(), payload) state.reader_bucket_cache_bytes += len(payload) while state.reader_bucket_cache_bytes > deps.cache_max_bytes(): _, (_, evicted) = state.reader_bucket_cache.popitem(last=False) state.reader_bucket_cache_bytes -= len(evicted) return payload finally: if state.reader_bucket_inflight.get(cache_key) is asyncio.current_task(): state.reader_bucket_inflight.pop(cache_key, None)
task = asyncio.create_task(load()) task.add_done_callback(lambda done: None if done.cancelled() else done.exception()) state.reader_bucket_inflight[cache_key] = task return await asyncio.shield(task)
async def run_read(state: BucketState, path: str, max_bytes: int, reader: Callable[[], Callable[[str, int], bytes]]) -> bytes: semaphore = state.reader_bucket_semaphore await semaphore.acquire() # Select the live hook after admission, before scheduling the thread. worker = asyncio.create_task(asyncio.to_thread(reader(), path, max_bytes)) state.reader_bucket_workers.add(worker)
def finished(done: asyncio.Task[bytes]) -> None: # Cancelling an async caller cannot stop its filesystem thread. state.reader_bucket_workers.discard(done) semaphore.release() if not done.cancelled(): done.exception()
worker.add_done_callback(finished) return await asyncio.shield(worker)1"""Bucket resource policy."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Bucket placement, cache policy, and delivery path/redirect gates."""import refrom collections.abc import Callablefrom urllib.parse import quote
class ReaderBucketBusyError(RuntimeError): """Retryable admission failure: too many distinct bucket reads in flight."""
def is_cacheable(path: str) -> bool: return ( path.endswith("/page-manifest.json") or path.endswith("/ocr-manifest.json") or path.endswith('/reading-manifest.json') or path.endswith('/page-map.json.gz') or path.endswith("/ocr/book-text.json.gz") or path.endswith("/pages/page-000001.webp") or (path.startswith("objects/") and path.rsplit("/", 1)[-1].startswith("document.")) or (path.startswith("chapters/ebook/") and any( path.endswith(suffix) for suffix in ( "/chapter-manifest.json", "/epub-search-index.json.gz", ))) )
def cache_control(path: str) -> str: # Generated page and versioned object bodies are immutable; manifests move. if re.search(r"/pages/page-[0-9]{6}\.(?:webp|jxl|png)$", path): return "public, max-age=31536000, immutable" if re.fullmatch(r"objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:preview|text)/.+", path): return "public, max-age=31536000, immutable" if path.startswith("objects/") and path.rsplit("/", 1)[-1].startswith("document."): return "public, max-age=31536000, immutable" if "/ebook-chapters/" in path: return "public, max-age=31536000, immutable" return "public, max-age=3600"
def bucket_for_path(path: str) -> str: if path.startswith(("documents/", "chapters/", "media/", "pages/image/", "native/")): return "vomebook/reader-assets-v2" return "vomebook/pdf-pages-v2"
def source_url(path: str, bucket: Callable[[str], str]) -> str: name = bucket(path) return f"https://huggingface.co/buckets/{name}/resolve/{quote(path, safe='/')}"
def resource_path(path: str, decode: Callable[[str], str], pattern: Callable[[], re.Pattern[str]]) -> str: # Framework query decoding already consumed the generator's single quote(). # Decode only for traversal detection; literal percent escapes stay literal. normalized = path.replace("\\", "/").lstrip("/") try: traversal = any(part in (".", "..") for part in decode(normalized).split("/")) except ValueError: traversal = True if traversal or not pattern().fullmatch(normalized): raise ValueError("不允许的阅读资源路径") return normalized
def validate_redirect_url(url: str, source: str, validate: Callable[[str, str], str]) -> str: try: return validate(url, source) except ValueError as exc: raise ValueError("上游重定向超出允许的阅读资源范围") from exc1"""Bucket HTTP delivery adapter."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""HTTP delivery policy for cached metadata and streamed bucket bodies."""import refrom collections.abc import Awaitable, Callable, Hashable, Mappingfrom dataclasses import dataclassfrom typing import Protocol, TypedDict
from fastapi import Requestfrom fastapi.responses import JSONResponse, Response
from backend.reader.bucket.domain.policy import ReaderBucketBusyError
class ReaderIntegrity(TypedDict, total=False): """Pinned page-image checksum forwarded to stream_reader_document.""" expected_sha256: str expected_bytes: int
class DocumentStream(Protocol): def __call__(self, request: Request, target_url: str, *, url_validator: Callable[[str], str], validation_scope: Hashable | None, cache_control: str | None, max_bytes: int | None, media_type: str | None, expected_sha256: str | None = None, expected_bytes: int | None = None) -> Awaitable[Response]: ...
@dataclass(frozen=True)class BucketRouteDependencies: resource_path: Callable[[str], str] resource_types: Callable[[], Mapping[str, str]] resource_max_bytes: Callable[[], int] pdf_max_bytes: Callable[[], int] document_max_bytes: Callable[[], int] cacheable: Callable[[str], bool] source_url: Callable[[str], str] redirect_validator: Callable[[], Callable[[str, str], str]] cache_control: Callable[[str], str] stream: Callable[[], DocumentStream] get_resource: Callable[[str], Awaitable[bytes]] busy_headers: Callable[[], Mapping[str, str]] isolation_headers: Callable[[], Mapping[str, str]] allows_compression: Callable[[str, Request | None], bool]
async def bucket_resource(path: str, request: Request | None, deps: BucketRouteDependencies) -> Response: try: resource_path = deps.resource_path(path) except ValueError: return JSONResponse({"error": "不允许的阅读资源路径"}, status_code=400, headers={"Cache-Control": "no-store"}) suffix = resource_path.rsplit(".", 1)[-1].lower() media_type = deps.resource_types().get(suffix, "application/octet-stream") integrity: ReaderIntegrity = {} pinned_png = suffix == 'png' and resource_path.startswith('objects/') and '/pages/page-' in resource_path if suffix == 'jxl' or pinned_png: query = getattr(request, 'query_params', {}) expected_sha = query.get('sha256', '') expected_size = query.get('bytes', '') if (not re.fullmatch(r'[0-9a-f]{64}', expected_sha) or not re.fullmatch(r'[0-9]{1,10}', expected_size) or not 0 < int(expected_size) <= deps.resource_max_bytes() or any(name in getattr(request, 'headers', {}) for name in ('Range', 'If-Range', 'If-None-Match', 'If-Modified-Since'))): return JSONResponse({'error': '阅读页图缺少完整校验信息'}, status_code=400, headers={'Cache-Control': 'no-store'}) integrity = {'expected_sha256': expected_sha, 'expected_bytes': int(expected_size)} # Body streams retain transport ownership/cancellation in the document adapter. if request is not None and (suffix in {"pdf", "djvu"} or media_type.startswith(("audio/", "video/", "image/")) or not deps.cacheable(resource_path)): source_url = deps.source_url(resource_path) return await deps.stream()( request, source_url, url_validator=lambda url: deps.redirect_validator()(url, source_url), # Scope captures the actual hook now; callback resolves it when used. validation_scope=(deps.redirect_validator(), source_url), cache_control=deps.cache_control(resource_path), max_bytes=(None if media_type.startswith(("audio/", "video/")) else deps.pdf_max_bytes() if suffix == "pdf" else deps.document_max_bytes() if suffix == "djvu" else deps.resource_max_bytes()), media_type=media_type, **integrity, ) try: payload = await deps.get_resource(resource_path) except FileNotFoundError: return JSONResponse({"error": "阅读资源不存在"}, status_code=404, headers={"Cache-Control": "no-store"}) except ReaderBucketBusyError: return JSONResponse({"error": "阅读资源请求过多,请稍后重试"}, status_code=503, headers=deps.busy_headers()) except Exception: return JSONResponse({"error": "阅读资源加载失败"}, status_code=502, headers={"Cache-Control": "no-store"}) return Response(content=b"" if request is not None and request.method == "HEAD" else payload, media_type=media_type, headers={**deps.isolation_headers(), "Cache-Control": deps.cache_control(resource_path), "Content-Length": str(len(payload)), **({} if deps.allows_compression(resource_path, request) else {"Content-Encoding": "identity"})})100 unmodified lines101102103104105106100 unmodified lines"../../static/search/requests/infrastructure/shared-transport.js","../../static/search/requests/application/prefetch-controller.js","../../static/search/results/presentation/paging-status.js","../../static/search/domain/height-index.js","../../static/search/domain/stable-stringify.js","../../static/search/domain/search-view-key.js",100 unmodified lines101102103104105106107108100 unmodified lines"../../static/search/requests/infrastructure/shared-transport.js","../../static/search/requests/application/prefetch-controller.js","../../static/search/results/presentation/paging-status.js","../../static/search/results/window/application/page-loader.js","../../static/search/results/window/presentation/status.js","../../static/search/domain/height-index.js","../../static/search/domain/stable-stringify.js","../../static/search/domain/search-view-key.js",
23 unmodified lines24252627282923 unmodified lines"../../static/search/requests/infrastructure/shared-transport.js","../../static/search/requests/application/prefetch-controller.js","../../static/search/results/presentation/paging-status.js","../../static/search/domain/height-index.js","../../static/search/domain/stable-stringify.js","../../static/search/domain/search-view-key.js",23 unmodified lines242526272829303123 unmodified lines"../../static/search/requests/infrastructure/shared-transport.js","../../static/search/requests/application/prefetch-controller.js","../../static/search/results/presentation/paging-status.js","../../static/search/results/window/application/page-loader.js","../../static/search/results/window/presentation/status.js","../../static/search/domain/height-index.js","../../static/search/domain/stable-stringify.js","../../static/search/domain/search-view-key.js",
83 unmodified lines84858687888983 unmodified lines"../../static/search/requests/infrastructure/shared-transport.js","../../static/search/requests/application/prefetch-controller.js","../../static/search/results/presentation/paging-status.js","../../static/search/domain/height-index.js","../../static/search/domain/stable-stringify.js","../../static/search/domain/search-view-key.js",83 unmodified lines848586878889909183 unmodified lines"../../static/search/requests/infrastructure/shared-transport.js","../../static/search/requests/application/prefetch-controller.js","../../static/search/results/presentation/paging-status.js","../../static/search/results/window/application/page-loader.js","../../static/search/results/window/presentation/status.js","../../static/search/domain/height-index.js","../../static/search/domain/stable-stringify.js","../../static/search/domain/search-view-key.js",
39 unmodified lines4041424344454639 unmodified linesbytesToDisplay: "readonly", fmtSizeUrl: "readonly", parseSizeStr: "readonly", formatSize: "readonly",buildRecordRelativePath: "readonly", encodeRecordPath: "readonly",escapeHTML: "readonly", getHighlightRegex: "readonly", highlightText: "readonly", BoundedResponseCache: "readonly", VoiceOfMLSearchFileTypes: "readonly", VoiceOfMLSearchValidation: "readonly", VoiceOfMLSearchIdentity: "readonly",VoiceOfMLSearchFolderSelection: "readonly", VoiceOfMLSearchHeightIndex: "readonly", VoiceOfMLSearchCanonical: "readonly", VoiceOfMLSearchViewKey: "readonly", VoiceOfMLSearchRecovery: "readonly", VoiceOfMLSearchWindowPage: "readonly", VoiceOfMLSearchSidebarRender: "readonly", VoiceOfMLSearchInput: "readonly", VoiceOfMLSearchInputOwnership: "readonly", VoiceOfMLPagingPolicy: "readonly", VoiceOfMLPagingController: "readonly", VoiceOfMLPagingStatus: "readonly", VoiceOfMLSearchTransport: "readonly", VoiceOfMLSearchPrefetch: "readonly"} } },{ files: ["static/**/*.mjs", "static/**/reader.js", "static/**/reader-pdf-text.js", "static/**/reader-book-text.js"],languageOptions: { sourceType: "module" } },39 unmodified lines4041424344454639 unmodified linesbytesToDisplay: "readonly", fmtSizeUrl: "readonly", parseSizeStr: "readonly", formatSize: "readonly",buildRecordRelativePath: "readonly", encodeRecordPath: "readonly",escapeHTML: "readonly", getHighlightRegex: "readonly", highlightText: "readonly", BoundedResponseCache: "readonly", VoiceOfMLSearchFileTypes: "readonly", VoiceOfMLSearchValidation: "readonly", VoiceOfMLSearchIdentity: "readonly",VoiceOfMLSearchFolderSelection: "readonly", VoiceOfMLSearchHeightIndex: "readonly", VoiceOfMLSearchCanonical: "readonly", VoiceOfMLSearchViewKey: "readonly", VoiceOfMLSearchRecovery: "readonly", VoiceOfMLSearchWindowPage: "readonly", VoiceOfMLSearchSidebarRender: "readonly", VoiceOfMLSearchInput: "readonly", VoiceOfMLSearchInputOwnership: "readonly", VoiceOfMLPagingPolicy: "readonly", VoiceOfMLPagingController: "readonly", VoiceOfMLPagingStatus: "readonly", VoiceOfMLSearchTransport: "readonly", VoiceOfMLSearchPrefetch: "readonly", VoiceOfMLResultWindowLoader: "readonly", VoiceOfMLResultWindowStatus: "readonly"} } },{ files: ["static/**/*.mjs", "static/**/reader.js", "static/**/reader-pdf-text.js", "static/**/reader-book-text.js"],languageOptions: { sourceType: "module" } },
50 unmodified lines51525354555650 unmodified lines"backend/reader/archive/domain/content.py","backend/reader/archive/http/__init__.py","backend/reader/archive/http/routes.py","backend/app.py"],"pythonVersion": "3.11",50 unmodified lines5152535455565758596061626350 unmodified lines"backend/reader/archive/domain/content.py","backend/reader/archive/http/__init__.py","backend/reader/archive/http/routes.py","backend/reader/bucket/__init__.py","backend/reader/bucket/domain/__init__.py","backend/reader/bucket/domain/policy.py","backend/reader/bucket/application/__init__.py","backend/reader/bucket/application/resources.py","backend/reader/bucket/http/__init__.py","backend/reader/bucket/http/routes.py","backend/app.py"],"pythonVersion": "3.11",
261 unmodified lines262263264265266267261 unmodified lines"search/requests/infrastructure/shared-transport.js","search/requests/application/prefetch-controller.js","search/results/presentation/paging-status.js","search/domain/height-index.js","search/domain/stable-stringify.js","search/domain/search-view-key.js",261 unmodified lines262263264265266267268269261 unmodified lines"search/requests/infrastructure/shared-transport.js","search/requests/application/prefetch-controller.js","search/results/presentation/paging-status.js","search/results/window/application/page-loader.js","search/results/window/presentation/status.js","search/domain/height-index.js","search/domain/stable-stringify.js","search/domain/search-view-key.js",
9 unmodified lines1011121314159 unmodified lines"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","search/requests/infrastructure/shared-transport.js", "search/requests/application/prefetch-controller.js","search/results/domain/paging-policy.js", "search/results/application/paging-controller.js", "search/results/presentation/paging-status.js","search/folder-selection.js", "search/domain/height-index.js", "search/domain/stable-stringify.js", "search/domain/search-view-key.js", "search/domain/search-recovery.js", "search/domain/search-window-page.js", "search/presentation/sidebar-render.js"]);9 unmodified lines101112131415169 unmodified lines"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","search/requests/infrastructure/shared-transport.js", "search/requests/application/prefetch-controller.js","search/results/window/application/page-loader.js", "search/results/window/presentation/status.js","search/results/domain/paging-policy.js", "search/results/application/paging-controller.js", "search/results/presentation/paging-status.js","search/folder-selection.js", "search/domain/height-index.js", "search/domain/stable-stringify.js", "search/domain/search-view-key.js", "search/domain/search-recovery.js", "search/domain/search-window-page.js", "search/presentation/sidebar-render.js"]);
982 unmodified lines9839849859869879889899909919929939949959969979989991000100110021003100410051006100710081 unmodified line101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104616 unmodified lines1063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109783 unmodified lines118111821183118411851186118711881189119011911192119311941195119611971198119912001201982 unmodified lines}function updateResultWindowStatus() {let status = document.getElementById("search-window-status");if (!status && resultWindow && (resultWindow.invalid || resultWindow.failures.size)) {status = document.createElement("div");status.id = "search-window-status";status.setAttribute("role", "status");status.innerHTML = '<span></span> <button type="button" class="text-btn-sm"></button>';status.querySelector("button").onclick = () => {if (!resultWindow) return;if (resultWindow.invalid) return restartResultWindow();const pages = [...resultWindow.failures.keys()];resultWindow.failures.clear(); updateResultWindowStatus();pages.forEach(page => loadResultWindowPage(page));};DOM.resultsContainer.parentElement.appendChild(status);}if (status) {status.hidden = !resultWindow || (!resultWindow.invalid && !resultWindow.failures.size);status.querySelector("span").textContent = resultWindow?.invalid ? "搜索数据已更新" : "部分结果暂时无法加载";status.querySelector("button").textContent = resultWindow?.invalid ? "重新定位" : "重试加载";}}function isRecoverableSearchError(error) {1 unmodified line}function waitForSearchRecovery(signal, delay, local) {return /** @type {Promise<void>} */ (new Promise((resolve, reject) => {let elapsed = false;const cleanup = () => {clearTimeout(timer);signal.removeEventListener("abort", abort);document.removeEventListener("visibilitychange", ready);window.removeEventListener("online", ready);window.removeEventListener("pageshow", ready);};const abort = () => { cleanup(); reject(new DOMException("Cancelled", "AbortError")); };const ready = () => {if (elapsed && !document.hidden && (local || navigator.onLine)) { cleanup(); resolve(); }};const timer = setTimeout(() => { elapsed = true; ready(); }, delay);signal.addEventListener("abort", abort, { once: true });document.addEventListener("visibilitychange", ready);window.addEventListener("online", ready);window.addEventListener("pageshow", ready);if (signal.aborted) abort();}));}async function fetchPositionPageWithRecovery(query, page, signal, anchorId, demanded = () => true) {for (let attempt = 0; ; attempt++) {if (signal.aborted) throw new DOMException("Cancelled", "AbortError");try { return await fetchPositionPage(query, page, signal, anchorId); }catch (error) {if (signal.aborted || attempt >= 2 || !demanded() || !isRecoverableSearchError(error)) throw error;await waitForSearchRecovery(signal, (attempt + 1) * 750, query.useLocalMode);}}}function resumeResultRecovery() {16 unmodified lines}function requestResultWindowPage(window, page, prefetch = false) {if (window.prefetched?.has(page)) return Promise.resolve(window.prefetched.get(page));if (window.pending.has(page)) {const request = window.pending.get(page);if (!prefetch && !request.demanded) { request.demanded = true; request.diskWait?.abort(); }return request;}if (prefetch && window.prefetchFailures?.has(page)) return Promise.resolve(null);if (window.pending.size >= 3 || window.failures.has(page) || window.invalid) return Promise.resolve(null);const diskWait = new AbortController();const releaseDisk = () => diskWait.abort();window.controller.signal.addEventListener("abort", releaseDisk, { once: true });if (window.controller.signal.aborted) releaseDisk();const request = (async () => {const cached = await readRecentSearchPage(window.key, page, window, prefetch ? 150 : 25, diskWait.signal);if (!resultWindowCurrent(window)) return null;return cached || fetchPositionPageWithRecovery(window.query, page, window.controller.signal, undefined, () => request.demanded);})().then(data => {if (!data) return null;validatePositionWindowPage(data, page, window.query.pageSize, window);return data;}).finally(() => {window.controller.signal.removeEventListener("abort", releaseDisk);window.pending.delete(page);if (resultWindowCurrent(window)) scheduleVirtualRender();});window.pending.set(page, request);request.demanded = !prefetch;request.diskWait = diskWait;return request;}async function loadResultWindowPage(page, prefetch = false) {83 unmodified linesfunction createResultWindowPlaceholder(index) {const page = Math.floor(index / STATE.pageSize) + 1;const row = document.createElement("div");row.className = "result-item result-window-placeholder";row.dataset.index = String(index);row.dataset.contentVersion = String(VSCROLL.contentVersion);row.style.height = (VSCROLL.heights[index] || VSCROLL.estimatedHeight) + "px";if (resultWindow?.invalid || resultWindow?.failures.has(page)) {const button = document.createElement("button");button.className = "text-btn-sm"; button.dataset.windowPage = String(page);button.textContent = resultWindow.invalid ? "数据已更新,点击重新定位" : "加载失败,点击重试";row.appendChild(button);} else {row.setAttribute("aria-label", "正在加载结果");row.innerHTML = '<div class="window-placeholder-lines" aria-hidden="true"><i></i><i></i></div>';}return row;}async function fetchPositionPage(query, page, signal, anchorId) {982 unmodified lines9839849859869879889899909919929939949959969979981 unmodified line100010011002100310041005100610071008100910101011101210131014101516 unmodified lines103210331034103510361037103810391040104110421043104483 unmodified lines11281129113011311132113311341135113611371138982 unmodified lines}function updateResultWindowStatus() {VoiceOfMLResultWindowStatus.update({window: resultWindow, getHost: () => DOM.resultsContainer.parentElement,retry: () => {if (!resultWindow) return;if (resultWindow.invalid) return restartResultWindow();const pages = [...resultWindow.failures.keys()];resultWindow.failures.clear(); updateResultWindowStatus();pages.forEach(page => loadResultWindowPage(page));},});}function isRecoverableSearchError(error) {1 unmodified line}function waitForSearchRecovery(signal, delay, local) {return VoiceOfMLResultWindowLoader.waitForRecovery(signal, delay, local);}async function fetchPositionPageWithRecovery(query, page, signal, anchorId, demanded = () => true) {return VoiceOfMLResultWindowLoader.fetchWithRecovery({fetchPage: (query, page, signal, anchorId) => fetchPositionPage(query, page, signal, anchorId),isRecoverable: error => isRecoverableSearchError(error),isLocal: query => query.useLocalMode,wait: (signal, delay, local) => waitForSearchRecovery(signal, delay, local),}, query, page, signal, anchorId, demanded);}function resumeResultRecovery() {16 unmodified lines}function requestResultWindowPage(window, page, prefetch = false) {return VoiceOfMLResultWindowLoader.requestPage({readRecent: (key, page, expected, delay, signal) => readRecentSearchPage(key, page, expected, delay, signal),isCurrent: window => resultWindowCurrent(window),fetchPage: (query, page, signal, anchorId, demanded) => fetchPositionPageWithRecovery(query, page, signal, anchorId, demanded),validate: (data, page, size, expected) => validatePositionWindowPage(data, page, size, expected),scheduleRender: () => scheduleVirtualRender(),}, window, page, prefetch);}async function loadResultWindowPage(page, prefetch = false) {83 unmodified linesfunction createResultWindowPlaceholder(index) {const page = Math.floor(index / STATE.pageSize) + 1;return VoiceOfMLResultWindowStatus.createPlaceholder({index, page, contentVersion: VSCROLL.contentVersion,height: VSCROLL.heights[index] || VSCROLL.estimatedHeight,invalid: resultWindow?.invalid, failed: resultWindow?.failures.has(page),});}async function fetchPositionPage(query, page, signal, anchorId) {
354 unmodified lines355356357358359360354 unmodified lines<script src="/static/search/requests/infrastructure/shared-transport.js"></script><script src="/static/search/requests/application/prefetch-controller.js"></script><script src="/static/search/results/presentation/paging-status.js"></script><script src="/static/search/domain/height-index.js"></script><script src="/static/search/domain/stable-stringify.js"></script><script src="/static/search/domain/search-view-key.js"></script>354 unmodified lines355356357358359360361362354 unmodified lines<script src="/static/search/requests/infrastructure/shared-transport.js"></script><script src="/static/search/requests/application/prefetch-controller.js"></script><script src="/static/search/results/presentation/paging-status.js"></script><script src="/static/search/results/window/application/page-loader.js"></script><script src="/static/search/results/window/presentation/status.js"></script><script src="/static/search/domain/height-index.js"></script><script src="/static/search/domain/stable-stringify.js"></script><script src="/static/search/domain/search-view-key.js"></script>
256 unmodified lines257258259260261262256 unmodified lines"search/requests/infrastructure/shared-transport.js","search/requests/application/prefetch-controller.js","search/results/presentation/paging-status.js","search/domain/height-index.js","search/domain/stable-stringify.js","search/domain/search-view-key.js",256 unmodified lines257258259260261262263264256 unmodified lines"search/requests/infrastructure/shared-transport.js","search/requests/application/prefetch-controller.js","search/results/presentation/paging-status.js","search/results/window/application/page-loader.js","search/results/window/presentation/status.js","search/domain/height-index.js","search/domain/stable-stringify.js","search/domain/search-view-key.js",
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576// Owns recovery waits and the bounded sparse-page request lifecycle. The host// supplies transport, cache and current-window checks; it commits result pages.(function () { /** @param {AbortSignal} signal @param {number} delay @param {boolean | number | undefined} local */ function waitForRecovery(signal, delay, local) { return /** @type {Promise<void>} */ (new Promise((resolve, reject) => { let elapsed = false; const cleanup = () => { clearTimeout(timer); signal.removeEventListener("abort", abort); document.removeEventListener("visibilitychange", ready); window.removeEventListener("online", ready); window.removeEventListener("pageshow", ready); }; const abort = () => { cleanup(); reject(new DOMException("Cancelled", "AbortError")); }; const ready = () => { if (elapsed && !document.hidden && (local || navigator.onLine)) { cleanup(); resolve(); } }; const timer = setTimeout(() => { elapsed = true; ready(); }, delay); signal.addEventListener("abort", abort, { once: true }); document.addEventListener("visibilitychange", ready); window.addEventListener("online", ready); window.addEventListener("pageshow", ready); if (signal.aborted) abort(); })); }
/** @param {VoiceOfMLWindowRecoveryDependencies} deps @param {VoiceOfMLSearchViewProjection} query * @param {number} page @param {AbortSignal} signal @param {string | undefined} anchorId @param {() => boolean} demanded */ async function fetchWithRecovery(deps, query, page, signal, anchorId, demanded = () => true) { for (let attempt = 0; ; attempt++) { if (signal.aborted) throw new DOMException("Cancelled", "AbortError"); try { return await deps.fetchPage(query, page, signal, anchorId); } catch (error) { if (signal.aborted || attempt >= 2 || !demanded() || !deps.isRecoverable(error)) throw error; await deps.wait(signal, (attempt + 1) * 750, deps.isLocal(query)); } } }
/** @param {VoiceOfMLWindowRequestDependencies} deps @param {VoiceOfMLResultWindow} window * @param {number} page @param {boolean} prefetch */ function requestPage(deps, window, page, prefetch = false) { if (window.prefetched?.has(page)) return Promise.resolve(window.prefetched.get(page)); if (window.pending.has(page)) { const request = /** @type {VoiceOfMLWindowRequest} */ (window.pending.get(page)); if (!prefetch && !request.demanded) { request.demanded = true; request.diskWait?.abort(); } return request; } if (prefetch && window.prefetchFailures?.has(page)) return Promise.resolve(null); if (window.pending.size >= 3 || window.failures.has(page) || window.invalid) return Promise.resolve(null); const diskWait = new AbortController(); const releaseDisk = () => diskWait.abort(); window.controller.signal.addEventListener("abort", releaseDisk, { once: true }); if (window.controller.signal.aborted) releaseDisk(); const request = /** @type {VoiceOfMLWindowRequest} */ ((async () => { const cached = await deps.readRecent(window.key, page, window, prefetch ? 150 : 25, diskWait.signal); if (!deps.isCurrent(window)) return null; return cached || deps.fetchPage(window.query, page, window.controller.signal, undefined, () => request.demanded); })().then(data => { if (!data) return null; deps.validate(data, page, window.query.pageSize, window); return data; }).finally(() => { window.controller.signal.removeEventListener("abort", releaseDisk); window.pending.delete(page); if (deps.isCurrent(window)) deps.scheduleRender(); })); window.pending.set(page, request); request.demanded = !prefetch; request.diskWait = diskWait; return request; }
globalThis.VoiceOfMLResultWindowLoader = { waitForRecovery, fetchWithRecovery, requestPage };})();12345678910111213141516171819202122232425262728293031323334353637383940414243// Owns result-window feedback markup. Layout values and retry actions come// from the host, so this view does not read scroll state or commit results.(function () { /** @param {VoiceOfMLWindowStatusOptions} options */ function update(options) { const window = options.window; let status = document.getElementById("search-window-status"); if (!status && window && (window.invalid || window.failures.size)) { status = document.createElement("div"); status.id = "search-window-status"; status.setAttribute("role", "status"); status.innerHTML = '<span></span> <button type="button" class="text-btn-sm"></button>'; /** @type {HTMLButtonElement} */ (status.querySelector("button")).onclick = options.retry; options.getHost().appendChild(status); } if (status) { status.hidden = !window || (!window.invalid && !window.failures.size); /** @type {HTMLSpanElement} */ (status.querySelector("span")).textContent = window?.invalid ? "搜索数据已更新" : "部分结果暂时无法加载"; /** @type {HTMLButtonElement} */ (status.querySelector("button")).textContent = window?.invalid ? "重新定位" : "重试加载"; } }
/** @param {VoiceOfMLWindowPlaceholderOptions} options */ function createPlaceholder(options) { const {index, page, contentVersion, height, invalid, failed} = options; const row = document.createElement("div"); row.className = "result-item result-window-placeholder"; row.dataset.index = String(index); row.dataset.contentVersion = String(contentVersion); row.style.height = height + "px"; if (invalid || failed) { const button = document.createElement("button"); button.className = "text-btn-sm"; button.dataset.windowPage = String(page); button.textContent = invalid ? "数据已更新,点击重新定位" : "加载失败,点击重试"; row.appendChild(button); } else { row.setAttribute("aria-label", "正在加载结果"); row.innerHTML = '<div class="window-placeholder-lines" aria-hidden="true"><i></i><i></i></div>'; } return row; } globalThis.VoiceOfMLResultWindowStatus = { update, createPlaceholder };})();100 unmodified lines101102103104105106100 unmodified lines"/static/search/requests/infrastructure/shared-transport.js","/static/search/requests/application/prefetch-controller.js","/static/search/results/presentation/paging-status.js","/static/app.js","/data/initial/manifest.json","/data/sidebar/manifest.json",100 unmodified lines101102103104105106107108100 unmodified lines"/static/search/requests/infrastructure/shared-transport.js","/static/search/requests/application/prefetch-controller.js","/static/search/results/presentation/paging-status.js","/static/search/results/window/application/page-loader.js","/static/search/results/window/presentation/status.js","/static/app.js","/data/initial/manifest.json","/data/sidebar/manifest.json",
657 unmodified lines658659660661662663664657 unmodified linesself.assertIn("bootstrap.extensions", self.js)self.assertIn("data.sidebar", self.js)self.assertIn("if (sidebarInitialPending.has(key)) return sidebarInitialPending.get(key)", self.js)self.assertIn("controller.groupKey !== groupKey", self.js)def test_empty_repository_extensions_are_not_replaced_with_global_extensions(self):self.assertNotIn('fallbackResp = await fetch("/api/extensions")', self.js)657 unmodified lines658659660661662663664665666667657 unmodified linesself.assertIn("bootstrap.extensions", self.js)self.assertIn("data.sidebar", self.js)self.assertIn("if (sidebarInitialPending.has(key)) return sidebarInitialPending.get(key)", self.js)prefetch = (ROOT / "static/search/requests/application/prefetch-controller.js").read_text(encoding="utf-8")self.assertIn("controller.groupKey !== groupKey", prefetch)self.assertIn("VoiceOfMLSearchPrefetch.create", self.js)self.assertIn("return prefetch.prefetch(base, template)", self.js)def test_empty_repository_extensions_are_not_replaced_with_global_extensions(self):self.assertNotIn('fallbackResp = await fetch("/api/extensions")', self.js)
1150 unmodified lines1151115211531154115511561150 unmodified linesself.assertTrue(upstream.released)self.assertEqual(app.app.state.upstream_semaphore._value, 1)async def test_bucket_get_head_direct_and_by_source_id(self):self.assets["f"][app.build_reader_asset_key(self.record)] = {"s": 2, "m": "p", "p": BUCKET_PATH.replace('page-manifest.json', 'reading-manifest.json'), "b": "vomebook/pdf-pages-v2"}body = b'{"kind":"pdf-pages"}'1150 unmodified lines115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831150 unmodified linesself.assertTrue(upstream.released)self.assertEqual(app.app.state.upstream_semaphore._value, 1)async def test_bucket_suspended_read_uses_live_cache_fields_policy_and_limits(self):from collections import OrderedDictstate = app.app.statefor cacheable, item_limit, total_limit, retained in ((True, 4, 4, True), (False, 4, 4, False),(True, 3, 4, False), (True, 4, 3, False),):with self.subTest(cacheable=cacheable, item_limit=item_limit, total_limit=total_limit):app.initialize_reader_bucket_state(app.app)started, release = asyncio.Event(), asyncio.Event()async def read(path, limit):started.set()await release.wait()return b'four'with patch.object(app, 'run_reader_bucket_read', side_effect=read):pending = asyncio.create_task(app.get_reader_bucket_resource(BUCKET_PATH))await asyncio.wait_for(started.wait(), 1)old_cache = state.reader_bucket_cachereplacement = OrderedDict([(BUCKET_PATH, (0, b'old'))])state.reader_bucket_cache = replacementstate.reader_bucket_cache_bytes = 3with patch.object(app, 'is_reader_bucket_cacheable', return_value=cacheable), \patch.object(app, 'READER_BUCKET_CACHE_MAX_ITEM_BYTES', item_limit), \patch.object(app, 'READER_BUCKET_CACHE_MAX_BYTES', total_limit):release.set()self.assertEqual(await asyncio.wait_for(pending, 1), b'four')self.assertFalse(old_cache)self.assertIs(state.reader_bucket_cache, replacement)if retained:self.assertEqual(replacement[BUCKET_PATH][1], b'four')self.assertEqual(state.reader_bucket_cache_bytes, 4)elif cacheable and item_limit == 4:self.assertFalse(replacement)self.assertEqual(state.reader_bucket_cache_bytes, 0)else:self.assertEqual(replacement[BUCKET_PATH][1], b'old')self.assertEqual(state.reader_bucket_cache_bytes, 3)self.assertFalse(state.reader_bucket_inflight)async def test_bucket_cache_byte_lru_ttl_and_path_only_identity(self):state = app.app.statepaths = [BUCKET_PATH.replace('b' * 16, digit * 16) for digit in 'bcd']now = [100.0]with patch.object(app, 'run_reader_bucket_read', AsyncMock(return_value=b'1234')) as read, \patch.object(app, 'READER_BUCKET_CACHE_MAX_BYTES', 8), \patch.object(app, 'READER_BUCKET_CACHE_MAX_ITEM_BYTES', 4), \patch.object(app, 'READER_BUCKET_CACHE_TTL_SECONDS', 10), \patch.object(app, 'time', SimpleNamespace(monotonic=lambda: now[0])):for path in paths[:2]:self.assertEqual(await app.get_reader_bucket_resource(path, 4), b'1234')# Historical cache/flight identity is the path, not the requested limit.self.assertEqual(await app.get_reader_bucket_resource(paths[0], 1), b'1234')await app.get_reader_bucket_resource(paths[2], 4)self.assertEqual(list(state.reader_bucket_cache), [paths[0], paths[2]])self.assertEqual(state.reader_bucket_cache_bytes, 8)now[0] += 10await app.get_reader_bucket_resource(paths[0], 4)self.assertEqual(read.await_count, 4)self.assertEqual(list(state.reader_bucket_cache), [paths[2], paths[0]])self.assertEqual(state.reader_bucket_cache_bytes, 8)async def test_bucket_shared_read_shields_cancel_and_enforces_distinct_admission(self):started, release = asyncio.Event(), asyncio.Event()async def read(path, limit):started.set()await release.wait()return b'shared'with patch.object(app, 'run_reader_bucket_read', side_effect=read) as reader, \patch.object(app, 'READER_BUCKET_MAX_INFLIGHT', 1):first = asyncio.create_task(app.get_reader_bucket_resource(BUCKET_PATH, 6))await asyncio.wait_for(started.wait(), 1)second = asyncio.create_task(app.get_reader_bucket_resource(BUCKET_PATH, 1))await asyncio.sleep(0)first.cancel()with self.assertRaises(asyncio.CancelledError):await firstwith self.assertRaises(app.ReaderBucketBusyError):await app.get_reader_bucket_resource(BUCKET_PATH.replace('page-manifest', 'ocr-manifest'))release.set()self.assertEqual(await asyncio.wait_for(second, 1), b'shared')reader.assert_called_once_with(BUCKET_PATH, 6)self.assertFalse(app.app.state.reader_bucket_inflight)async def test_bucket_worker_selects_live_reader_after_admission_and_owns_cancelled_thread(self):state = app.app.statesemaphore = asyncio.Semaphore(0)state.reader_bucket_semaphore = semaphorestarted, release = threading.Event(), threading.Event()def read(path, limit):started.set()if not release.wait(2):raise AssertionError('worker was not released')return b'body'try:with patch.object(app, 'read_reader_bucket_resource') as original:pending = asyncio.create_task(app.run_reader_bucket_read(BUCKET_PATH, 4))await asyncio.sleep(0)with patch.object(app, 'read_reader_bucket_resource', side_effect=read) as current:semaphore.release()self.assertTrue(await asyncio.to_thread(started.wait, 1))pending.cancel()with self.assertRaises(asyncio.CancelledError):await pendingworkers = list(state.reader_bucket_workers)self.assertEqual(len(workers), 1)self.assertEqual(semaphore._value, 0)# Completion must use the current workers field, but original semaphore.state.reader_bucket_workers = set(workers)state.reader_bucket_semaphore = asyncio.Semaphore(7)release.set()await asyncio.gather(*workers)current.assert_called_once_with(BUCKET_PATH, 4)original.assert_not_called()self.assertFalse(state.reader_bucket_workers)self.assertEqual(semaphore._value, 1)self.assertEqual(state.reader_bucket_semaphore._value, 7)finally:release.set()async def test_bucket_read_bounds_and_live_filesystem_bucket_selection(self):for size in (3, 4, 5):stream = io.BytesIO(b'x' * size)filesystem = SimpleNamespace(open=lambda uri, mode: stream)with patch.object(app, 'HfFileSystem', return_value=filesystem), \patch.object(app, 'reader_bucket_for_path', return_value='vomebook/reader-assets-v2'), \patch.object(stream, 'read', wraps=stream.read) as read:if size > 4:with self.assertRaisesRegex(ValueError, '阅读资源过大'):app.read_reader_bucket_resource(BUCKET_PATH, 4)else:self.assertEqual(app.read_reader_bucket_resource(BUCKET_PATH, 4), b'x' * size)read.assert_called_once_with(5)self.assertTrue(stream.closed)path = 'documents/%41/书 ?.txt'with patch.object(app, 'reader_bucket_for_path', return_value='chosen'):self.assertEqual(app.reader_bucket_source_url(path),'https://huggingface.co/buckets/chosen/resolve/documents/%2541/%E4%B9%A6%20%3F.txt')async def test_bucket_shutdown_rereads_state_and_keeps_ocr_cleanup_after_workers(self):from collections import OrderedDictfrom starlette.datastructures import Statetarget = SimpleNamespace(state=State())app.initialize_reader_bucket_state(target)initial = target.stateevents = []worker_release = asyncio.Event()async def worker():await worker_release.wait()events.append('worker')task = asyncio.create_task(worker())replacement = State()app.initialize_reader_bucket_state(SimpleNamespace(state=replacement))replacement.reader_bucket_workers.add(task)replacement.reader_bucket_cache = OrderedDict([(BUCKET_PATH, (0, b'new'))])replacement.reader_bucket_cache_bytes = 3replacement.reader_ocr_cache['ocr'] = (0, [], 3)async def load():try:await asyncio.Event().wait()finally:events.append('load')target.state = replacementload_task = asyncio.create_task(load())initial.reader_bucket_inflight[BUCKET_PATH] = load_taskawait asyncio.sleep(0)closing = asyncio.create_task(app.shutdown_reader_bucket_state(target))await asyncio.sleep(0)await asyncio.sleep(0)self.assertFalse(initial.reader_bucket_inflight)self.assertTrue(replacement.reader_ocr_cache)worker_release.set()await asyncio.wait_for(closing, 1)self.assertEqual(events, ['load', 'worker'])self.assertFalse(replacement.reader_bucket_cache)self.assertEqual(replacement.reader_bucket_cache_bytes, 0)self.assertFalse(replacement.reader_ocr_cache)async def test_bucket_stream_scope_captures_hook_but_callback_resolves_live_hook(self):path = OBJECT + '/' + 'b' * 16 + '/document.pdf'validator = app.validate_reader_bucket_redirect_urlwith patch.object(app, 'stream_reader_document', AsyncMock(return_value=app.Response())) as stream:for _ in range(2):await app.api_reader_bucket_resource(path, SimpleNamespace(method='GET', headers={}))first, second = [call.kwargs for call in stream.call_args_list]source = app.reader_bucket_source_url(path)self.assertEqual(first['validation_scope'], (validator, source))self.assertEqual(first['validation_scope'], second['validation_scope'])self.assertIs(first['validation_scope'][0], validator)with patch.object(app, 'validate_reader_bucket_redirect_url', return_value='live') as current:self.assertEqual(first['url_validator']('redirect'), 'live')current.assert_called_once_with('redirect', source)self.assertIs(first['validation_scope'][0], validator)async def test_bucket_http_errors_and_headers_resolve_after_suspended_load(self):from backend.reader.bucket.domain.policy import ReaderBucketBusyErrorself.assertIs(app.ReaderBucketBusyError, ReaderBucketBusyError)async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app.app), base_url='http://test') as client:for error, status, message in ((FileNotFoundError(), 404, '阅读资源不存在'),(ReaderBucketBusyError(), 503, '阅读资源请求过多,请稍后重试'),(OSError('private transport detail'), 502, '阅读资源加载失败'),):with patch.object(app, 'get_reader_bucket_resource', AsyncMock(side_effect=error)):response = await client.get('/api/reader-bucket-resource', params={'path': BUCKET_PATH})self.assertEqual(response.status_code, status)self.assertEqual(response.json(), {'error': message})self.assertEqual(response.headers['cache-control'], 'no-store')self.assertEqual(response.headers.get('retry-after'), '1' if status == 503 else None)started, release = asyncio.Event(), asyncio.Event()async def load(path):started.set()await release.wait()return b'body'with patch.object(app, 'get_reader_bucket_resource', side_effect=load):pending = asyncio.create_task(client.get('/api/reader-bucket-resource', params={'path': BUCKET_PATH}))await asyncio.wait_for(started.wait(), 1)with patch.object(app, 'reader_bucket_cache_control', return_value='public, max-age=17'), \patch.object(app, 'READER_ISOLATION_HEADERS', {'X-Live-Policy': 'yes'}), \patch.object(app, 'reader_body_allows_compression', return_value=False):release.set()response = await asyncio.wait_for(pending, 1)self.assertEqual(response.content, b'body')self.assertEqual(response.headers['cache-control'], 'public, max-age=17')self.assertEqual(response.headers['x-live-policy'], 'yes')self.assertEqual(response.headers['content-encoding'], 'identity')self.assertEqual(response.headers['content-length'], '4')async def test_bucket_get_head_direct_and_by_source_id(self):self.assets["f"][app.build_reader_asset_key(self.record)] = {"s": 2, "m": "p", "p": BUCKET_PATH.replace('page-manifest.json', 'reading-manifest.json'), "b": "vomebook/pdf-pages-v2"}body = b'{"kind":"pdf-pages"}'
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180import assert from 'node:assert/strict';import fs from 'node:fs';import vm from 'node:vm';import test from 'node:test';import {installClassicSearchModules} from '../../support/classic_search_modules.js';import {APP_DEPENDENCIES, stripBundledScripts} from '../../../scripts/build/compose_app.mjs';
const source = fs.readFileSync('static/app.js', 'utf8');function fixture(names, values = {}) { const c = vm.createContext({AbortController, DOMException, ...values}); installClassicSearchModules(process.cwd(), c); for (const name of names) { const match = source.match(new RegExp('^(?:async )?function ' + name + '\\([^]*?^}', 'm')); assert.ok(match, name); vm.runInContext(match[0], c); } return c;}
function target() { const listeners = new Map(); return {listeners, addEventListener(name, fn) {listeners.set(name, fn);}, removeEventListener(name, fn) {if (listeners.get(name) === fn) listeners.delete(name);}, emit(name) {listeners.get(name)?.();}};}
test('recovery wait requires elapsed delay, visibility and connectivity, and cleans every listener', async () => { for (const mode of ['online', 'local', 'abort', 'already-aborted']) { const document = Object.assign(target(), {hidden: true}), window = target(), signal = target(); const timers = new Map(); signal.aborted = mode === 'already-aborted'; const c = fixture(['waitForSearchRecovery'], {document, window, navigator: {onLine: false}, setTimeout(fn, delay) {timers.set(1, {fn, delay});return 1;}, clearTimeout(id) {timers.delete(id);}}); let settled = false; const pending = c.waitForSearchRecovery(signal, 750, mode === 'local').then(() => {settled = true;}, error => error.name); if (mode === 'already-aborted') assert.equal(await pending, 'AbortError'); else { assert.equal(timers.get(1).delay, 750); window.emit('online'); await Promise.resolve(); assert.equal(settled, false); timers.get(1).fn(); await Promise.resolve(); assert.equal(settled, false); document.hidden = false; document.emit('visibilitychange'); await Promise.resolve(); assert.equal(settled, mode === 'local'); if (mode === 'abort') {signal.aborted = true; signal.emit('abort'); assert.equal(await pending, 'AbortError');} else {c.navigator.onLine = true; window.emit('pageshow'); await pending; assert.equal(settled, true);} } assert.equal(timers.size, 0); assert.equal(signal.listeners.size, 0); assert.equal(document.listeners.size, 0); assert.equal(window.listeners.size, 0); }});
test('recovery adapters retain 750/1500 retries, demand gating, anchor and each site local policy', async () => { for (const scenario of ['remote', 'local', 'self', 'subtree', 'unavailable', 'prefetch', 'fatal', 'aborted']) { const owner = new AbortController(), error = new Error('temporary'), waits = [], calls = []; const query = {useLocalMode: scenario === 'local', folders: {self: scenario === 'self' ? ['a'] : [], subtree: scenario === 'subtree' ? ['a'] : []}}; const c = fixture(['fetchPositionPageWithRecovery'], {apiAvailable: scenario !== 'unavailable', fetchPositionPage(...args) {calls.push(args); throw error;}, isRecoverableSearchError: () => scenario !== 'fatal', waitForSearchRecovery(signal, delay, local) {assert.equal(signal, owner.signal);waits.push([delay, !!local]);}}); if (scenario === 'aborted') owner.abort(); await assert.rejects(c.fetchPositionPageWithRecovery(query, 7, owner.signal, 'anchor', () => scenario !== 'prefetch'), scenario === 'aborted' ? {name: 'AbortError'} : value => value === error); const retry = !['prefetch', 'fatal', 'aborted'].includes(scenario); assert.equal(calls.length, scenario === 'aborted' ? 0 : retry ? 3 : 1); for (const args of calls) assert.deepEqual(args, [query, 7, owner.signal, 'anchor']); const pages = source.includes('isLocal: query => query.useLocalMode ||'); const local = scenario === 'local' || (pages && ['self', 'subtree', 'unavailable'].includes(scenario)); assert.deepEqual(waits, retry ? [[750, local], [1500, local]] : []); }});
test('promotion during an in-flight fetch enables recovery and abort during wait prevents another fetch', async () => { const owner = new AbortController(); let demanded = false, rejectFetch, calls = 0; const c = fixture(['fetchPositionPageWithRecovery'], {apiAvailable: true, fetchPositionPage() {calls++;return new Promise((resolve, reject) => {rejectFetch = reject;});}, isRecoverableSearchError: () => true, waitForSearchRecovery() {owner.abort();}}); const pending = c.fetchPositionPageWithRecovery({folders: {self: [], subtree: []}}, 2, owner.signal, undefined, () => demanded); demanded = true; rejectFetch(new Error('temporary')); await assert.rejects(pending, {name: 'AbortError'}); assert.equal(calls, 1);});
test('request gates, validation failures and stale completion preserve pending cleanup', async () => { const owner = new AbortController(), data = {results: [], page: 2}; let current = true, reads = 0, renders = 0, rejectValidation = false; const window = {key: 'query', query: {pageSize: 100}, pending: new Map(), failures: new Map(), controller: owner}; const c = fixture(['requestResultWindowPage'], { readRecentSearchPage: async () => {reads++;return data;}, resultWindowCurrent: () => current, fetchPositionPageWithRecovery() {assert.fail('cache hit must avoid transport');}, validatePositionWindowPage() {if (rejectValidation) throw new Error('RESTORE_PAGE_CHANGED');}, scheduleVirtualRender() {renders++;}}); window.prefetched = new Map([[2, data]]); assert.equal(await c.requestResultWindowPage(window, 2), data); assert.equal(reads, 0); window.prefetched.clear(); window.prefetchFailures = new Set([2]); assert.equal(await c.requestResultWindowPage(window, 2, true), null); assert.equal(reads, 0); assert.equal(await c.requestResultWindowPage(window, 2), data); assert.equal(reads, 1); for (const blocked of ['failure', 'invalid']) { window.failures.clear(); window.invalid = blocked === 'invalid'; if (blocked === 'failure') window.failures.set(2, new Error()); assert.equal(await c.requestResultWindowPage(window, 2), null); assert.equal(reads, 1); } window.invalid = false; window.failures.clear(); rejectValidation = true; await assert.rejects(c.requestResultWindowPage(window, 2), /RESTORE_PAGE_CHANGED/); assert.equal(window.pending.size, 0); assert.equal(renders, 2); current = false; assert.equal(await c.requestResultWindowPage(window, 2), null); assert.equal(window.pending.size, 0); assert.equal(renders, 2);});
test('host keeps prefetch failures bounded and generation changes invalidate even prefetch', async () => { const window = {key: 'query', total: 1000, query: {pageSize: 1}, controller: new AbortController(), pages: new Set(), failures: new Map()}; let error = new Error('temporary'), renders = 0, statuses = 0; const c = fixture(['loadResultWindowPage'], {resultWindow: window, positionRestore: null, resultWindowCurrent: () => true, requestResultWindowPage: async () => {throw error;}, updateResultWindowStatus() {statuses++;}, scheduleVirtualRender() {renders++;}, DOM: {resultsList: {querySelectorAll: () => []}}, VSCROLL: {}}); for (let page = 1; page <= 65; page++) assert.equal(await c.loadResultWindowPage(page, true), false); assert.equal(window.prefetchFailures.size, 64); assert.equal(window.prefetchFailures.has(1), false); assert.equal(window.failures.size, 0); assert.equal(statuses, 0); assert.equal(renders, 0); error = new Error('RESTORE_PAGE_CHANGED'); assert.equal(await c.loadResultWindowPage(66, true), false); assert.equal(window.invalid, true); assert.equal(window.failures.get(66), error); assert.equal(statuses, 1); assert.equal(renders, 1);});
function documentFixture() { const elements = []; function element(tag) { const node = {tag, dataset: {}, style: {}, children: [], attributes: {}, appendChild(child) {this.children.push(child);}, setAttribute(key, value) {this.attributes[key] = value;}, querySelector(tag) {return this.children.find(child => child.tag === tag);}}; Object.defineProperty(node, 'innerHTML', {set(value) { this.markup = value; if (value.includes('<span>')) this.children = [element('span'), element('button')]; }}); elements.push(node); return node; } return {createElement: element, getElementById: id => elements.find(node => node.id === id)};}
test('status action reads the current window and placeholders retain loading, retry and invalid markup', () => { const document = documentFixture(), host = document.createElement('div'), loaded = []; let restarted = 0; const c = fixture(['updateResultWindowStatus', 'createResultWindowPlaceholder'], {document, DOM: {resultsContainer: {parentElement: host}}, resultWindow: null, STATE: {pageSize: 100}, VSCROLL: {contentVersion: 9, heights: [72], estimatedHeight: 60}, restartResultWindow() {restarted++;}, loadResultWindowPage(page) {loaded.push(page);}}); c.updateResultWindowStatus(); assert.equal(host.children.length, 0); const loading = c.createResultWindowPlaceholder(0); assert.equal(loading.style.height, '72px'); assert.equal(loading.dataset.contentVersion, '9'); assert.equal(loading.attributes['aria-label'], '正在加载结果'); assert.ok(loading.markup.includes('aria-hidden="true"')); c.resultWindow = {failures: new Map([[2, new Error()]])}; c.updateResultWindowStatus(); const status = host.children[0], button = status.querySelector('button'); assert.equal(status.attributes.role, 'status'); assert.equal(button.textContent, '重试加载'); const failed = c.createResultWindowPlaceholder(100); assert.equal(failed.style.height, '60px'); assert.equal(failed.dataset.index, '100'); assert.equal(failed.children[0].dataset.windowPage, '2'); assert.equal(failed.children[0].textContent, '加载失败,点击重试'); c.resultWindow = {failures: new Map([[3, new Error()]])}; button.onclick(); assert.deepEqual(loaded, [3]); assert.equal(status.hidden, true); c.resultWindow.invalid = true; c.updateResultWindowStatus(); button.onclick(); assert.equal(restarted, 1); assert.equal(status.querySelector('span').textContent, '搜索数据已更新'); assert.equal(button.textContent, '重新定位'); assert.equal(c.createResultWindowPlaceholder(100).children[0].textContent, '数据已更新,点击重新定位'); c.resultWindow = null; button.onclick(); c.updateResultWindowStatus(); assert.equal(status.hidden, true); assert.equal(host.children.length, 1);});
test('window modules load once in source, composition, resources, SW and all three type projects', () => { const html = fs.readFileSync('static/index.html', 'utf8'), worker = fs.readFileSync('static/sw.js', 'utf8'); const c = vm.createContext({}); vm.runInContext(fs.readFileSync('static/reader-resources.js', 'utf8'), c); for (const name of ['search/results/window/application/page-loader.js', 'search/results/window/presentation/status.js']) { assert.equal(APP_DEPENDENCIES.filter(path => path === name).length, 1); assert.equal(html.split(name).length - 1, 1); assert.ok(html.indexOf(name) < html.indexOf('static/app.js')); assert.equal(stripBundledScripts(html).includes(name), false); assert.equal(worker.split('/static/' + name).length - 1, 1); for (const site of ['github', 'huggingface']) assert.equal(c.VoiceOfMLReaderResources.buildFiles(site).filter(path => path === name).length, 1); for (const config of ['check', 'strict', 'search-exact']) assert.equal(JSON.parse(fs.readFileSync(`config/types/jsconfig.${config}.json`, 'utf8')).files.filter(path => path === '../../static/' + name).length, 1); }});3 unmodified lines4567893 unmodified linesimport fs from 'node:fs';import vm from 'node:vm';import test from 'node:test';import { installClassicSearchModules } from '../../support/classic_search_modules.js';import { APP_DEPENDENCIES, stripBundledScripts } from '../../../scripts/build/compose_app.mjs';3 unmodified lines456789103 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';
5 unmodified lines67891011125 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"];const sources = new Map();const installed = new WeakMap();5 unmodified lines6789101112135 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();const installed = new WeakMap();
48 unmodified lines49505152535448 unmodified linesonFailure(error: Error): void;}declare var VoiceOfMLSearchPrefetch: {create(deps: VoiceOfMLSearchPrefetchDependencies): {prefetch(base: string, template: VoiceOfMLSearchRequestBody): Promise<void>}};declare var VoiceOfMLSearchIdentity: {getResultStableId(result: unknown): string};declare var VoiceOfMLSearchFileTypes: {orderedExtensions: string[]; fileIconMap: Record<string, string | object>};interface VoiceOfMLFolderSelectionNode {48 unmodified lines495051525354555657585960616263646566676869707172737475767778798081828384858687888990919248 unmodified linesonFailure(error: Error): void;}declare var VoiceOfMLSearchPrefetch: {create(deps: VoiceOfMLSearchPrefetchDependencies): {prefetch(base: string, template: VoiceOfMLSearchRequestBody): Promise<void>}};interface VoiceOfMLWindowRequest extends Promise<VoiceOfMLSearchWindowPageData | null> {demanded: boolean; diskWait: AbortController;}interface VoiceOfMLResultWindow {key: string; query: VoiceOfMLSearchViewProjection; total: number; generation: string;controller: AbortController; pending: Map<number, VoiceOfMLWindowRequest>; failures: Map<number, unknown>;invalid?: boolean | undefined; prefetched?: Map<number, VoiceOfMLSearchWindowPageData> | undefined;prefetchFailures?: Set<number> | undefined;}interface VoiceOfMLWindowRecoveryDependencies {fetchPage(query: VoiceOfMLSearchViewProjection, page: number, signal: AbortSignal, anchorId: string | undefined): Promise<VoiceOfMLSearchWindowPageData>;isRecoverable(error: unknown): boolean; isLocal(query: VoiceOfMLSearchViewProjection): boolean | number | undefined;wait(signal: AbortSignal, delay: number, local: boolean | number | undefined): Promise<void>;}interface VoiceOfMLWindowRequestDependencies {readRecent(key: string, page: number, expected: VoiceOfMLResultWindow, delay: number, signal: AbortSignal): Promise<VoiceOfMLSearchWindowPageData | null>;isCurrent(window: VoiceOfMLResultWindow): boolean;fetchPage(query: VoiceOfMLSearchViewProjection, page: number, signal: AbortSignal, anchorId: string | undefined, demanded: () => boolean): Promise<VoiceOfMLSearchWindowPageData>;validate(data: VoiceOfMLSearchWindowPageData, page: number, size: number, expected: VoiceOfMLResultWindow): void;scheduleRender(): void;}declare var VoiceOfMLResultWindowLoader: {waitForRecovery(signal: AbortSignal, delay: number, local: boolean | number | undefined): Promise<void>;fetchWithRecovery(deps: VoiceOfMLWindowRecoveryDependencies, query: VoiceOfMLSearchViewProjection, page: number, signal: AbortSignal, anchorId: string | undefined, demanded?: () => boolean): Promise<VoiceOfMLSearchWindowPageData>;requestPage(deps: VoiceOfMLWindowRequestDependencies, window: VoiceOfMLResultWindow, page: number, prefetch?: boolean): Promise<VoiceOfMLSearchWindowPageData | null | undefined>;};interface VoiceOfMLWindowStatusOptions {window: {invalid?: boolean | undefined; failures: ReadonlyMap<number, unknown>} | null;getHost(): HTMLElement; retry(): void;}interface VoiceOfMLWindowPlaceholderOptions {index: number; page: number; contentVersion: number; height: number;invalid: boolean | undefined; failed: boolean | undefined;}declare var VoiceOfMLResultWindowStatus: {update(options: VoiceOfMLWindowStatusOptions): void;createPlaceholder(options: VoiceOfMLWindowPlaceholderOptions): HTMLDivElement;};declare var VoiceOfMLSearchIdentity: {getResultStableId(result: unknown): string};declare var VoiceOfMLSearchFileTypes: {orderedExtensions: string[]; fileIconMap: Record<string, string | object>};interface VoiceOfMLFolderSelectionNode {
backend/app.py+52-190
backend/reader/bucket/__init__.pyAdded+1
backend/reader/bucket/application/__init__.pyAdded+1
backend/reader/bucket/application/resources.pyAdded+125
backend/reader/bucket/domain/__init__.pyAdded+1
backend/reader/bucket/domain/policy.pyAdded+65
backend/reader/bucket/http/__init__.pyAdded+1
backend/reader/bucket/http/routes.pyAdded+98
config/types/jsconfig.check.json+2
config/types/jsconfig.search-exact.json+2
config/types/jsconfig.strict.json+2
eslint.config.mjs+1-1
pyrightconfig.strict.json+7
scripts/build/check_reader_release.mjs+2
scripts/build/compose_app.mjs+1
static/app.js+24-87
static/index.html+2
static/reader-resources.js+2
static/search/results/window/application/page-loader.jsAdded+76
static/search/results/window/presentation/status.jsAdded+43
static/sw.js+2
tests/gates/test_static_contract.py+4-1
tests/reader/backend/test_reader_backend.py+227
tests/search/paging/result_window_contracts.mjsAdded+180
tests/search/reader-navigation/test_search_history_races.mjs+1
tests/support/classic_search_modules.js+2-1
typings/reader-globals.d.ts+38