"""FastAPI application, routes and process-owned search state.""" import asyncio import gzip import hashlib import json import random import re import sys import time import functools import threading import weakref from collections import OrderedDict from collections.abc import AsyncGenerator, Awaitable, Callable, Hashable, Iterable, Mapping, MutableSequence from array import array from uuid import uuid4 import io import zipfile import zlib from pathlib import Path from typing import Annotated, BinaryIO, Literal, Optional, Protocol, Sequence, TypedDict, TypeVar, cast from urllib.parse import unquote, quote, urlparse, parse_qs import aiohttp from huggingface_hub import HfFileSystem import jieba from fastapi import FastAPI, HTTPException, Query, Request from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware from starlette.types import Scope from pydantic import BaseModel, Field from contextlib import asynccontextmanager from backend.cache_core import cached as _bounded_cache from backend.folder_tree import build_folder_tree as _build_folder_tree from backend.folder_contents import get_folder_contents as _get_folder_contents from backend.search_bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_results from backend.search_candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidates from backend.search_projection import public_record as _public_record, trim_results as _trim_results from backend.reader_identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE, canonical_reader_source_url as canonical_reader_source_url, reader_short_id as reader_short_id) from backend.reader_index import ReaderIndexBuild, advance_build, new_build from backend.reader_ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text, parse_reader_ocr_book as _parse_reader_ocr_book, search_reader_ocr_pages as search_reader_ocr_pages) from backend.search_filters import (apply_filters as _apply_filters, apply_mixed_folder_filters as _apply_mixed_folder_filters, mixed_folder_index_candidates as _mixed_folder_index_candidates, score_record as _score_record) from backend.search_words import (build_vocab_by_len as _build_vocab_by_len, build_word_index as _build_word_index, matches_file_query as _matches_file_query, matches_file_token as _matches_file_token, records_digest as _records_digest, tokenize as _tokenize) from 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, UpstreamLease from backend.search_execution import SearchBusy, SearchExecutor from backend.search_indexes import ( NGRAM_MAGIC as NGRAM_MAGIC, WORD_INDEX_MAGIC as WORD_INDEX_MAGIC, WORD_INDEX_TOKENIZER as WORD_INDEX_TOKENIZER, Posting, PostingIndex, decode_postings as decode_postings, decode_varint as decode_varint, load_ngram_index, load_word_index, resolve_postings, ) from backend.reader_assets import ( READER_ASSET_FILENAMES as READER_ASSET_FILENAMES, READER_BUCKET_PATH_RE, decode_reader_assets, ) from backend.reader_v3_catalog import load_reading_catalog, merge_sidecar as merge_v3_sidecar from backend.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell from backend.data_formats import ( decode_browser_entry as decode_browser_entry, decode_folder_browser_data, decode_folder_tree_data, decode_search_payload, decode_tree_node as decode_tree_node, ) from backend.record_metadata import ( READER_ASSET_MODES as READER_ASSET_MODES, add_reader_assets, build_browser_file_name as build_browser_file_name, build_reader_asset_key, build_record_link, build_record_path_url, build_record_relative_path, dataset_file_url, enrich_browser_entry, enrich_reader_record, reader_asset_url as reader_asset_url, reader_extension_for_asset as reader_extension_for_asset, reader_resolved_record, ) from backend.upstream_http import ( ALLOWED_DOWNLOAD_HOSTS as ALLOWED_DOWNLOAD_HOSTS, ALLOWED_DOWNLOAD_HOST_SUFFIXES as ALLOWED_DOWNLOAD_HOST_SUFFIXES, MAX_REDIRECTS as MAX_REDIRECTS, READER_ASSET_PATH_RE as READER_ASSET_PATH_RE, VOICEOFML_READER_SOURCE_RE as VOICEOFML_READER_SOURCE_RE, decode_url_path, is_allowed_download_host as is_allowed_download_host, normalize_download_url as normalize_download_url, open_download_response, source_url_scope as source_url_scope, validate_download_url as validate_download_url, validate_path_safety, validate_reader_redirect_url, validate_fixed_source_redirect_url, validate_reader_source_url, validate_voiceofml_redirect_url, validate_voiceofml_source_url, ) MAX_ARCHIVE_NAME_LENGTH = 240 DATA_PATH = Path("data/search_data.json.gz") NGRAM_PATHS = {2: Path("data/search_ngrams_2.bin.gz"), 3: Path("data/search_ngrams_3.bin.gz")} WORD_INDEX_PATH = Path("data/search_words.bin.gz") FOLDER_TREE_PATH = Path("data/folder_tree.json.gz") FOLDER_BROWSER_PATH = Path("data/folder_browser.json.gz") READER_ASSETS_URL = "https://huggingface.co/buckets/vomebook/reader-assets-v2/resolve/reader-index/reader_assets.json.gz" READER_ASSETS_CACHE_TTL_SECONDS = 300 READER_ASSETS_MAX_COMPRESSED_BYTES = 5 * 1024 * 1024 READER_ASSETS_MAX_DECOMPRESSED_BYTES = 50 * 1024 * 1024 READER_ASSET_ROUTING_CONTRACT_VERSION = "reader-buckets-v2-pdf-primary-only-v1" # Decoded corpus records share the heterogeneous mapping used by the typed helpers. SearchRecord = dict[str, object] JsonObject = dict[str, object] # 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") class RepoSummary(TypedDict): name: str count: int class ReaderJoinCache(TypedDict): all: dict[int, JsonObject] repos: dict[str, dict[int, JsonObject]] class IndexedRecord(TypedDict, total=False): """Typed view of a corpus record after build_indexes adds its derived fields.""" Repo: str File: str Extension: str Folder: list[str] _file_lower: str _folder_path_lower: str _repo_lower: str records: list[SearchRecord] = [] folder_tree_data: dict[str, list[JsonObject]] = {} folder_browser_data: dict[str, dict[str, JsonObject]] = {} word_index: Mapping[str, Posting] = {} word_index_buffer = b"" folder_index: dict[str, dict[str, IndexPostings]] = {} extension_counts: dict[str, int] = {} repo_counts: dict[str, int] = {} repo_list: list[RepoSummary] = [] extension_list: list[str] = [] repo_extension_counts: dict[str, dict[str, int]] = {} vocab_by_len: dict[int, list[str]] = {} repo_records_map: dict[str, IndexPostings] = {} sorted_by_name: Sequence[int] = [] sorted_by_size: Sequence[int] = [] repo_sorted_by_name: dict[str, IndexPostings] = {} repo_sorted_by_size: dict[str, IndexPostings] = {} READER_EXTENSIONS = frozenset({"pdf", "djvu", "caj", "kdh", "epub", "mobi", "azw", "azw3", "fb2", "fbz", "html", "htm", "txt", "md", "markdown", "vcf", "ini", "jpg", "jpeg", "png", "gif", "bmp", "tif", "tiff", "webp", "mp3", "mp4", "wav", "m4a", "flac", "mov", "mpga", "wma", "ape", "amr"}) reader_record_indices: Sequence[int] = [] repo_reader_record_indices: dict[str, Sequence[int]] = {} reader_record_key_indices: dict[str, int] = {} reader_source_id_indices: dict[str, list[int]] = {} reader_legacy_source_id_indices: dict[str, list[int]] = {} _reader_indexes_ready = False _reader_indexes_lock = threading.Lock() _reader_index_build: ReaderIndexBuild | None = None READER_INDEX_BATCH_RECORDS = 256 READER_INDEX_BATCH_SECONDS = .008 READER_INDEX_WARM_DELAY_SECONDS = 5 READER_INDEX_IDLE_SECONDS = 5 initial_payload_global: JsonObject | None = None initial_payload_by_repo: dict[str, JsonObject] = {} API_CACHE_TTL_SECONDS = 120 RESPONSE_CACHE_BYTES_MAX = 16 * 1024 * 1024 RESPONSE_CACHE_ENTRY_BYTES_MAX = 2 * 1024 * 1024 _api_response_cache_lock = threading.Lock() api_response_cache: dict[Hashable, tuple[float, object] | tuple[float, object, int]] = {} _data_generation = 0 SEARCH_CACHE_TTL_SECONDS = 120 _search_cache: dict[Hashable, tuple[float, object] | tuple[float, object, int]] = {} _search_instance = uuid4().hex # Bump when matching, filtering, ordering or public record semantics change. SEARCH_SEMANTICS_VERSION = "hf-search-v5" _search_generation: str | None = None _search_logged_generation: int | None = None SearchOrderKey = tuple[Hashable, ...] # array[int] is not subscriptable at runtime on Python 3.11, so keep these annotations lazy. _search_order_cache: "OrderedDict[SearchOrderKey, tuple[float, array[int]]]" = OrderedDict() SEARCH_ORDER_CACHE_MAX = 32 SEARCH_ORDER_CACHE_BYTES_MAX = 16 * 1024 * 1024 SEARCH_ORDER_CACHE_TTL_SECONDS = 600 _search_anchor_cache: "OrderedDict[int, tuple[weakref.ref[array[int]], OrderedDict[str, int]]]" = OrderedDict() SEARCH_ANCHOR_ORDER_MAX = 8 SEARCH_ANCHOR_PER_ORDER_MAX = 8 SEARCH_ANCHOR_KEY_MAX = 4096 METADATA_CACHE_HEADERS = { "Cache-Control": "public, max-age=300, stale-while-revalidate=1800", } ngram_postings: dict[int, PostingIndex] = {} ngram_posting_buffers: dict[int, bytes] = {} injected_html_cache: dict[str | None, str] = {} last_user_request_at = time.monotonic() reader_assets_cache: JsonObject = {"v": 1, "f": {}} reader_assets_cache_at = 0.0 reader_assets_revision = hashlib.sha256(b'{"v":1,"f":{}}').hexdigest() reader_join_cache_key: CacheKey | None = None reader_join_cache: ReaderJoinCache = {"all": {}, "repos": {}} reader_pool_cache_key: CacheKey | None = None reader_pool_cache: "dict[str | None, array[int]]" = {} def _cached(store: dict[Hashable, tuple[float, object] | tuple[float, object, int]], key: Hashable, builder: Callable[[], object], ttl: float, limit: int) -> object: return _bounded_cache(store, key, builder, ttl, limit, max_entry_bytes=RESPONSE_CACHE_ENTRY_BYTES_MAX, max_total_bytes=RESPONSE_CACHE_BYTES_MAX) def cached_payload(key: Hashable, builder: Callable[[], object]) -> object: with _api_response_cache_lock: return _cached(api_response_cache, key, builder, API_CACHE_TTL_SECONDS, 500) def cached_json_response(key: Hashable, builder: Callable[[], object], headers: dict[str, str] | None = None) -> Response: # Encode once, measure the actual body and reuse it within the existing budget. body = cached_payload(("json", key), lambda: JSONResponse(builder()).body) return Response(cast(bytes, body), media_type="application/json", headers=headers) async def get_reader_assets(*, wait: bool = True) -> JsonObject: if reader_assets_cache_at != 0 and time.monotonic() - reader_assets_cache_at < READER_ASSETS_CACHE_TTL_SECONDS: return reader_assets_cache task = getattr(app.state, "reader_assets_task", None) if task is None or task.done(): task = asyncio.create_task(refresh_reader_assets()) app.state.reader_assets_task = task # Search can enrich with the last snapshot while an owned refresh runs. return await asyncio.shield(task) if wait else reader_assets_cache async def _load_reader_asset_base(session: object) -> tuple[bytes, JsonObject]: """Read the fixed mutable base sidecar; never publish a partial response.""" source_url = f"{READER_ASSETS_URL}?v={int(time.time())}" response = await open_download_response( session, source_url, aiohttp.ClientTimeout(total=20, connect=8, sock_read=10), url_validator=lambda target: validate_fixed_source_redirect_url(target, source_url), cache_redirects=False, ) try: if response.status == 404: raise RuntimeError("reader assets bucket and legacy sources unavailable") if response.status != 200: raise RuntimeError(f"reader assets HTTP {response.status}") chunks = bytearray() async for chunk in response.content.iter_chunked(64 * 1024): chunks.extend(chunk) if len(chunks) > READER_ASSETS_MAX_COMPRESSED_BYTES: raise ValueError("reader assets response is too large") raw = bytes(chunks) return raw, await asyncio.to_thread(decode_reader_assets, raw) finally: response.release() async def refresh_reader_assets() -> JsonObject: global reader_assets_cache, reader_assets_cache_at, reader_assets_revision now = time.monotonic() if reader_assets_cache_at != 0 and now - reader_assets_cache_at < READER_ASSETS_CACHE_TTL_SECONDS: return reader_assets_cache async with app.state.reader_assets_lock: now = time.monotonic() if reader_assets_cache_at != 0 and now - reader_assets_cache_at < READER_ASSETS_CACHE_TTL_SECONDS: return reader_assets_cache base_task = asyncio.create_task(_load_reader_asset_base(app.state.http_session)) v3_task = asyncio.create_task(load_reading_catalog(app.state.http_session)) try: # These two fixed, validated metadata reads are independent. The # existing all-or-nothing publication and v3 pinning remain below. (raw, decoded), v3_catalog = await asyncio.gather(base_task, v3_task) if v3_catalog is None and reader_assets_cache.get("v3"): raise ValueError("previously published v3 pointer disappeared") decoded = merge_v3_sidecar(decoded, v3_catalog) reader_assets_cache = decoded revision_body = raw + json.dumps(decoded["v3"], sort_keys=True).encode() if v3_catalog else raw reader_assets_revision = hashlib.sha256(revision_body).hexdigest() reader_assets_cache_at = time.monotonic() except Exception as exc: print(f"reader assets refresh failed: {exc}") # Retain last-known assets, but retry failures after a short backoff. reader_assets_cache_at = time.monotonic() - READER_ASSETS_CACHE_TTL_SECONDS + 5 finally: for task in (base_task, v3_task): if not task.done(): task.cancel() await asyncio.gather(base_task, v3_task, return_exceptions=True) return reader_assets_cache def records_digest() -> bytes: return _records_digest(records) def word_postings(token: str) -> set[int]: value = word_index.get(token) return resolve_postings(value, word_index_buffer) if value is not None else set() def word_posting_count(token: str) -> int: value = word_index.get(token) if value is None: return 0 if isinstance(value, tuple): return value[2] return len(value) def _candidate_postings() -> dict[int, PostingIndex]: return ngram_postings def _candidate_buffers() -> dict[int, bytes]: return ngram_posting_buffers def _candidate_repos() -> dict[str, IndexPostings]: return repo_records_map def _candidate_records() -> list[SearchRecord]: return records def _candidate_resolver() -> Callable[[Posting, bytes], set[int]]: return resolve_postings def literal_candidates(query: str, repos: Iterable[str] | None = None) -> set[int] | None: return _literal_candidates(query, repos, _candidate_postings, _candidate_buffers, _candidate_repos, _candidate_records, _candidate_resolver) INITIAL_PAGE_SIZE = 100 SIDEBAR_DATA_PATH = Path("data/sidebar") RECORD_KEY_MAP = { "r": "Repo", "f": "File", "e": "Extension", "d": "Folder", "s": "Size", "t": "HasTxt", } TREE_KEY_MAP = { "n": "name", "c": "count", "df": "hasDirectFiles", "ch": "children", } BROWSER_ENTRY_KEY_MAP = { "d": "folders", "f": "files", } BROWSER_FOLDER_ITEM_KEY_MAP = { "n": "name", "c": "count", } BROWSER_FILE_ITEM_KEY_MAP = { "n": "name", "e": "ext", "t": "hasTxt", "s": "size", } READER_SHORT_ID_RE = re.compile(r"^[0-9a-z]{13}$") # Only lowercase escapes, encoded unreserved ASCII and malformed percent signs # require normalization. Canonical reserved/UTF-8 escapes can pass through. def sanitize_archive_name(value: object) -> str: name = str(value or "file").replace("\\", "/").rsplit("/", 1)[-1] name = "".join(ch for ch in name if ord(ch) >= 32 and ch != "\x7f").strip() if not name or name in (".", ".."): name = "file" return name[:MAX_ARCHIVE_NAME_LENGTH] def tokenize(text: str) -> list[str]: return _tokenize(text, jieba.lcut) def matches_exact_query(text: str, query: str) -> bool: return compile_exact_matcher(query)(text) def matches_file_token(record: Mapping[str, object], token: str) -> bool: return _matches_file_token(record, token) def scoped_word_postings(token: str, search_folders: bool) -> set[int]: postings = word_postings(token) if search_folders: return postings return {index for index in postings if matches_file_token(records[index], token)} def matches_file_query(record: dict[str, object], tokens: Iterable[str], fuzzy_tokens: set[str]) -> bool: return _matches_file_query(record, tokens, fuzzy_tokens, tokenize_text=tokenize, file_match=matches_file_token, fuzzy_match=is_fuzzy_match) def build_word_index(): global word_index, word_index_buffer, vocab_by_len index: dict[str, set[int]] = {} word_index = index word_index_buffer = b"" _build_word_index(records, index, tokenize) vocab_by_len = {} _build_vocab_by_len(word_index, vocab_by_len) def build_vocab_by_len(): global vocab_by_len vocab_by_len = {} _build_vocab_by_len(word_index, vocab_by_len) def _advance_reader_indexes(limit: int = READER_INDEX_BATCH_RECORDS, budget: float = READER_INDEX_BATCH_SECONDS) -> bool: global reader_record_indices, repo_reader_record_indices global reader_record_key_indices, reader_source_id_indices, reader_legacy_source_id_indices, _reader_indexes_ready global _reader_index_build with _reader_indexes_lock: if _reader_indexes_ready: return True if _reader_index_build is None or _reader_index_build["generation"] != _data_generation: _reader_index_build = new_build(_data_generation, records) build = _reader_index_build deadline = time.perf_counter() + budget if not advance_build(build, limit, deadline, now=time.perf_counter, source_id=reader_short_id, asset_key=build_reader_asset_key, record_link=build_record_link, dataset_url=dataset_file_url, reader_extensions=READER_EXTENSIONS): return False if build["generation"] != _data_generation or build["records"] is not records: _reader_index_build = None return False reader_record_indices = array('I', build["indices"]) repo_reader_record_indices = {key: array('I', indices) for key, indices in build["repos"].items()} reader_record_key_indices = build["keys"] reader_source_id_indices = build["ids"] reader_legacy_source_id_indices = build["legacy_ids"] _reader_indexes_ready = True _reader_index_build = None return True def _build_reader_indexes(): while not _advance_reader_indexes(len(records), float("inf")): pass def ensure_reader_indexes(): global _reader_indexes_ready if _reader_indexes_ready: return _build_reader_indexes() async def ensure_reader_indexes_async(): """Join the shared background build, or start one for an early Reader request.""" if _reader_indexes_ready: return task = getattr(app.state, "reader_index_build_task", None) if task is None or task.done(): async def build(): while not _reader_indexes_ready: executor = getattr(app.state, "search_executor", None) if executor is None: await asyncio.to_thread(_advance_reader_indexes) else: try: await executor.run(_advance_reader_indexes, background=True) except SearchBusy: await asyncio.sleep(.02) continue await asyncio.sleep(0) task = asyncio.create_task(build()) app.state.reader_index_build_task = task await asyncio.shield(task) async def warm_reader_indexes(): """Prepare Reader routing during a quiet period without delaying startup.""" await asyncio.sleep(READER_INDEX_WARM_DELAY_SECONDS) while not _reader_indexes_ready: while time.monotonic() - last_user_request_at < READER_INDEX_IDLE_SECONDS: await asyncio.sleep(READER_INDEX_IDLE_SECONDS) try: await ensure_reader_indexes_async() except SearchBusy: await asyncio.sleep(READER_INDEX_IDLE_SECONDS) def build_indexes(build_words: bool = True, build_reader: bool = True): global _reader_index_build global reader_source_id_indices, reader_legacy_source_id_indices, _search_generation global _data_generation, word_index, word_index_buffer, folder_index, extension_counts, repo_counts, repo_list, extension_list, repo_extension_counts, repo_records_map, sorted_by_name, sorted_by_size, repo_sorted_by_name, repo_sorted_by_size, reader_record_indices, repo_reader_record_indices, reader_record_key_indices, _reader_indexes_ready _data_generation += 1 _search_generation = None _search_order_cache.clear() _search_anchor_cache.clear() _search_cache.clear() word_index = {} word_index_buffer = b"" folder_index = {} extension_counts = {} repo_extension_counts = {} repo_counts = {} repo_records_map = {} repo_sorted_by_name = {} repo_sorted_by_size = {} reader_record_indices = [] repo_reader_record_indices = {} reader_record_key_indices = {} reader_source_id_indices = {} reader_legacy_source_id_indices = {} _reader_indexes_ready = False _reader_index_build = None for idx, rec in enumerate(records): repo = cast(str, rec.get("Repo", "")) repo_counts[repo] = repo_counts.get(repo, 0) + 1 ext = cast(str, rec.get("Extension") or "").lower() if ext: extension_counts[ext] = extension_counts.get(ext, 0) + 1 repo_ext = repo_extension_counts.setdefault(repo, {}) repo_ext[ext] = repo_ext.get(ext, 0) + 1 file_name = cast(str, rec.get("File", "")) folders = cast(list[str], rec.get("Folder", [])) if repo not in folder_index: folder_index[repo] = {} for depth in range(len(folders) + 1): folder_path = "/".join(folders[:depth]) if depth > 0 else "" folder_index[repo].setdefault(folder_path, []).append(idx) repo_records_map.setdefault(repo, []).append(idx) folders_lower = [f.lower() for f in (folders or [])] rec["_file_lower"] = file_name.lower() rec["_folders_lower"] = folders_lower rec["_folder_text"] = " ".join(folders_lower) rec["_folder_path_lower"] = "/".join(folders_lower) rec["_folder_path"] = "/".join(folders) rec["_ext_lower"] = ext rec["_repo_lower"] = repo.lower() repo_list = sorted( [RepoSummary(name=r, count=c) for r, c in repo_counts.items()], key=lambda x: x["name"], ) if build_words: build_word_index() else: word_index = {} global vocab_by_len vocab_by_len = {} extension_list = sorted(extension_counts.keys()) all_indices = list(range(len(records))) sorted_by_name = sorted(all_indices, key=lambda i: cast(str, records[i].get("File") or "").lower()) sorted_by_size = sorted(all_indices, key=lambda i: ( -_record_size(records[i]), cast(str, records[i].get("File") or "").lower(), )) for repo, repo_indices in repo_records_map.items(): repo_sorted_by_name[repo] = sorted(repo_indices, key=lambda i: cast(str, records[i].get("File") or "").lower()) repo_sorted_by_size[repo] = sorted(repo_indices, key=lambda i: ( -_record_size(records[i]), cast(str, records[i].get("File") or "").lower(), )) # These complete, ordered postings are read-only after publication. # Packed IDs avoid retaining a Python pointer (and often an int) per slot. sorted_by_name = array('I', sorted_by_name) sorted_by_size = array('I', sorted_by_size) for mapping in (repo_records_map, repo_sorted_by_name, repo_sorted_by_size, *folder_index.values()): for key, indices in mapping.items(): mapping[key] = array('I', indices) if build_reader: _build_reader_indexes() def search_data_generation(raw: bytes, index_paths: Iterable[Path]) -> str: digest = hashlib.sha256() digest.update(SEARCH_SEMANTICS_VERSION.encode()) digest.update(str(sys.version_info[:3]).encode()) digest.update(jieba.__version__.encode()) digest.update(hashlib.sha256(raw).digest()) for path in index_paths: # Index content matters too; file timestamps and process IDs do not. digest.update(path.name.encode()) digest.update(hashlib.sha256(path.read_bytes()).digest() if path.exists() else b"missing") return "api:" + digest.hexdigest() def load_data(): global records, folder_tree_data, folder_browser_data, ngram_postings, ngram_posting_buffers, word_index, word_index_buffer, _search_generation start = time.perf_counter() stage_start = start timings = {} if DATA_PATH.exists(): raw = gzip.decompress(DATA_PATH.read_bytes()) records = decode_search_payload(json.loads(raw.decode("utf-8"))) else: print("⚠ 数据文件不存在") records = [] return if FOLDER_TREE_PATH.exists(): folder_tree_data = decode_folder_tree_data(json.loads(gzip.decompress(FOLDER_TREE_PATH.read_bytes()).decode("utf-8"))) else: folder_tree_data = {} if FOLDER_BROWSER_PATH.exists(): folder_browser_data = decode_folder_browser_data(json.loads(gzip.decompress(FOLDER_BROWSER_PATH.read_bytes()).decode("utf-8"))) else: folder_browser_data = {} timings["data_ms"] = round((time.perf_counter() - stage_start) * 1000, 2) print(f"📖 已加载 {len(records)} 条记录 ({time.perf_counter() - start:.2f}s)") stage_start = time.perf_counter() # Reader ID/pool indexes are built on first Reader use; normal search does # not need to scan every record to prepare them during cold startup. build_indexes(build_words=False, build_reader=False) digest = records_digest() timings["metadata_ms"] = round((time.perf_counter() - stage_start) * 1000, 2) stage_start = time.perf_counter() word_index, word_index_buffer = load_word_index(WORD_INDEX_PATH, len(records), digest, materialize=False) word_index_source = "generated" if word_index else "rebuilt" if word_index: build_vocab_by_len() else: word_index_buffer = b"" build_word_index() timings["words_ms"] = round((time.perf_counter() - stage_start) * 1000, 2) stage_start = time.perf_counter() loaded_ngrams = { width: load_ngram_index(path, width, len(records), digest) for width, path in NGRAM_PATHS.items() } ngram_postings = {width: loaded[0] for width, loaded in loaded_ngrams.items()} ngram_posting_buffers = {width: loaded[1] for width, loaded in loaded_ngrams.items()} timings["ngrams_ms"] = round((time.perf_counter() - stage_start) * 1000, 2) stage_start = time.perf_counter() _search_generation = search_data_generation(raw, [WORD_INDEX_PATH, *NGRAM_PATHS.values()]) timings["fingerprint_ms"] = round((time.perf_counter() - stage_start) * 1000, 2) print(f"🧭 已加载词索引: {len(word_index)}") print(f"🔎 已加载 ngram 索引: 2={len(ngram_postings[2])}, 3={len(ngram_postings[3])}") build_initial_payloads() precompute_injected_html() del raw stage_start = time.perf_counter() # A generated postings file avoids corpus tokenization, but query tokenization # still needs jieba's dictionary. Prepare it before accepting the first query, # after releasing the decoded source and finishing index-loading temporaries. jieba.initialize() timings["tokenizer_ms"] = round((time.perf_counter() - stage_start) * 1000, 2) timings["total_ms"] = round((time.perf_counter() - start) * 1000, 2) print("search_performance " + json.dumps({"stage": "startup", "word_index": word_index_source, **timings})) def score_record(rec_idx: int, query_tokens: Iterable[str], search_folders: bool = True) -> int: return _score_record(records[rec_idx], query_tokens, search_folders) def apply_filters(indices: Iterable[int], repos: Sequence[str] | None = None, extensions: Sequence[str] | None = None, folders: Sequence[str] | None = None, min_size: int | float | None = None, max_size: int | float | None = None, folder_match_mode: str = "prefix") -> list[int]: return _apply_filters(records, indices, repos, extensions, folders, min_size, max_size, folder_match_mode) def public_record(record: SearchRecord) -> SearchRecord: return _public_record(record, lambda item: build_record_link(item), lambda item: build_record_path_url(item)) def trim_results(raw: Iterable[SearchRecord]) -> list[SearchRecord]: return _trim_results(raw, lambda record: public_record(record)) def sort_key_name(idx: int) -> str: return cast(str, records[idx].get("File") or "").lower() def _record_size(record: SearchRecord) -> int | float: size = record.get("Size") return size if isinstance(size, (int, float)) else 0 def sort_key_size(idx: int) -> tuple[int | float, str]: return ( -_record_size(records[idx]), cast(str, records[idx].get("File") or "").lower(), ) def paginate_indices(indices: Sequence[int], page: int, page_size: int) -> tuple[int, list[SearchRecord]]: total = len(indices) start = (page - 1) * page_size return total, [records[i] for i in indices[start:start + page_size]] def canonical_repos(repos: Iterable[str] | None) -> list[str] | None: """Repository filters are sets: request order and repetition never matter.""" return sorted(set(repos)) if repos else None def get_initial_indices(repos: Iterable[str] | None = None) -> Sequence[int]: if repos: repos = canonical_repos(repos) or [] indices: list[int] = [] for repo in repos: indices.extend(repo_records_map.get(repo, [])) if len(repos) > 1: # Corpus order, matching the sorted literal n-gram candidate path. indices.sort() return indices return range(len(records)) def _term_literal_candidates(term: str, repos: Iterable[str] | None = None) -> Sequence[int]: """Candidates whose searched fields contain the literal term (corpus order).""" if not term: return [] candidates = literal_candidates(term.lower(), repos) if candidates is None: return get_initial_indices(repos) return sorted(candidates) def _term_matches_literal(rec: SearchRecord, term: str, search_folders: bool) -> bool: lowered = term.lower() indexed = cast(IndexedRecord, rec) return ( lowered in indexed.get("_file_lower", "") or lowered in indexed.get("_repo_lower", "") or (search_folders and lowered in indexed.get("_folder_path_lower", "")) ) def _term_is_plain(term: str) -> bool: """True when a term contains only letters/digits/CJK (no literal punctuation).""" return all(char.isalnum() or char.isspace() for char in term) def _term_candidates(term: str, query_token_count: int, posting_cache: dict[str, set[int]], search_folders: bool = True) -> tuple[set[int], set[str]]: """Existing jieba/fuzzy candidate semantics for one ordinary query term.""" query_tokens = tokenize(term) fuzzy_candidate_limit = 200 if query_token_count == 1 else None fuzzy_tokens: set[str] = set() def query_postings(token: str) -> set[int]: if token not in posting_cache: posting_cache[token] = scoped_word_postings(token, search_folders=search_folders) return posting_cache[token] exact_constraint: set[int] | None = None for tok in query_tokens: if tok not in word_index: continue postings = query_postings(tok) if not postings: continue exact_constraint = set(postings) if exact_constraint is None else exact_constraint.intersection(postings) token_candidates: list[set[int]] = [] for tok in query_tokens: candidates: set[int] = query_postings(tok) if tok in word_index else set() if not candidates: fuzzy_tokens.add(tok) fuzzy_candidates: set[int] = set() if exact_constraint is not None: for idx in sorted(exact_constraint): rec = records[idx] record_tokens = tokenize(" ".join([cast(str, rec.get("File", "")), *(cast(list[str], rec.get("Folder", []) or []) if search_folders else [])])) if any(is_fuzzy_match(tok, word) for word in record_tokens): fuzzy_candidates.add(idx) if fuzzy_candidate_limit is not None and len(fuzzy_candidates) >= fuzzy_candidate_limit: break else: tok_len = len(tok) for delta in (-2, -1, 0, 1, 2): for vocab_word in vocab_by_len.get(tok_len + delta, []): if is_fuzzy_match(tok, vocab_word): fuzzy_candidates.update(query_postings(vocab_word)) if fuzzy_candidate_limit is not None and len(fuzzy_candidates) >= fuzzy_candidate_limit: break if fuzzy_candidate_limit is not None and len(fuzzy_candidates) >= fuzzy_candidate_limit: break candidates = fuzzy_candidates if not candidates: return set(), fuzzy_tokens token_candidates.append(candidates) if not token_candidates: return set(), fuzzy_tokens token_candidates.sort(key=len) matched = set(token_candidates[0]) for candidates in token_candidates[1:]: matched.intersection_update(candidates) if not matched: break return matched, fuzzy_tokens def search_generation() -> str: return _search_generation or f"api:{_search_instance}:{_data_generation}" def build_response(results: list[SearchRecord], total: int, page: int, page_size: int) -> JsonObject: return { "results": trim_results(results), "total": total, "page": page, "page_size": page_size, "generation": search_generation(), } def trim_initial_results(raw: Sequence[SearchRecord]) -> list[SearchRecord]: return _trim_initial_results(raw) def _bootstrap_page_size() -> int: return INITIAL_PAGE_SIZE def _bootstrap_trim() -> Callable[[Sequence[SearchRecord]], list[SearchRecord]]: return trim_initial_results def _bootstrap_generation() -> Callable[[], str]: return search_generation def build_initial_payload(repo: str | None = None) -> JsonObject: return _build_initial_payload(repo, _bootstrap_page_size, _candidate_repos, _candidate_records, _bootstrap_trim, _bootstrap_generation) def build_initial_payloads() -> None: global initial_payload_global, initial_payload_by_repo initial_payload_global = build_initial_payload(None) initial_payload_by_repo = { repo: build_initial_payload(repo) for repo in repo_records_map } def precompute_injected_html() -> None: global injected_html_cache, seo_catalog_cache try: # Corpus decoding supplies the SEO fields; startup still owns the # legacy heterogeneous record mapping used by the search engine. seo_catalog_cache = build_seo_catalog(cast(list[CatalogRecord], records), project="hf", corpus_identity=search_generation()) except ValueError: # SEO failure must not replace search data or publish a partial catalog. seo_catalog_cache = None print("seo_catalog=unavailable reason=source_contract", flush=True) index_path = Path("static/index.html") if not index_path.exists(): injected_html_cache = {} return html = index_path.read_text(encoding="utf-8") injected_html_cache = {None: inject_initial_payload(html, None)} for repo in repo_records_map: injected_html_cache[repo] = inject_initial_payload(html, repo.split("/")[-1]) def load_sidebar_payload(path: Path) -> object: if not path.exists() or not path.is_file(): return None try: return json.loads(path.read_text(encoding="utf-8")) except Exception: return None def build_global_bootstrap() -> JsonObject: sidebar: object = load_sidebar_payload(SIDEBAR_DATA_PATH / "global.json") or {} return { "generation": search_generation(), "repos": repo_list, "extensions": [{"name": name, "count": extension_counts[name]} for name in sorted(extension_counts)], "sidebar": sidebar, } def inject_initial_payload(html: str, repo_short: str | None = None) -> str: repo = f"VoiceOfML/{repo_short}" if repo_short else None html = enrich_search_shell(html, repo, repo_counts.get(repo) if repo else None) payload = initial_payload_by_repo.get(repo) if repo else initial_payload_global if not payload: return html script = ( '" ) app_script = re.search(r'', html) if app_script: return html[:app_script.start()] + script + "\n" + app_script.group(0) + html[app_script.end():] return html.replace("", script + "\n") def apply_mixed_folder_filters(indices: Sequence[int], self_folders: Sequence[str] | None = None, subtree_folders: Sequence[str] | None = None) -> Sequence[int]: return _apply_mixed_folder_filters(records, indices, self_folders, subtree_folders) def mixed_folder_index_candidates(repos: Sequence[str] | None, self_folders: Sequence[str] | None = None, subtree_folders: Sequence[str] | None = None) -> list[int] | None: """Return a small corpus-ordered superset, or None to retain the full scan. The directory index is built from actual Folder component boundaries for the current corpus. It contains each subtree, so it is also a safe superset for direct-only selections. The existing predicate remains the authority on direct vs descendant semantics (including unusual names). """ return _mixed_folder_index_candidates(records, folder_index, repo_records_map, repos, self_folders, subtree_folders) def search(q: str = "", repos: Iterable[str] | None = None, extensions: Sequence[str] | None = None, folders: Sequence[str] | None = None, min_size: int | float | None = None, max_size: int | float | None = None, page: int = 1, page_size: int = 100, search_folders: bool = True, sort: str = "relevance", exact: bool = False, folder_match_mode: str = "prefix", folder_selfs: Sequence[str] | None = None, folder_subtrees: Sequence[str] | None = None, anchor_id: str | None = None) -> object: global _search_logged_generation started = time.perf_counter() q = q.strip() repos = canonical_repos(repos) order_key = _search_order_key(q, repos, extensions, folders, min_size, max_size, search_folders, sort, exact, folder_match_mode, folder_selfs, folder_subtrees) key = order_key + (page, page_size, anchor_id) cached_page = _search_cache.get(key) cache_hit = bool(cached_page and time.monotonic() - cached_page[0] < SEARCH_CACHE_TTL_SECONDS) result = _cached(_search_cache, key, lambda: _search_uncached(q, repos, extensions, folders, min_size, max_size, page, page_size, search_folders, sort, exact, folder_match_mode, folder_selfs, folder_subtrees, anchor_id), SEARCH_CACHE_TTL_SECONDS, 500) cached_order = _search_order_cache.get(order_key) if cached_order is not None and time.monotonic() - cached_order[0] < SEARCH_ORDER_CACHE_TTL_SECONDS: _search_order_cache[order_key] = (time.monotonic(), cached_order[1]) _search_order_cache.move_to_end(order_key) duration_ms = (time.perf_counter() - started) * 1000 first = _search_logged_generation != _data_generation if first or duration_ms >= 250: _search_logged_generation = _data_generation # Operational timing only; never log queries, paths, anchors or URLs. print("search_performance " + json.dumps({"stage": "search", "first": first, "duration_ms": round(duration_ms, 2), "page_cache_hit": cache_hit})) return result def _search_order_key(q: str, repos: Iterable[str] | None, extensions: Iterable[str] | None, folders: Iterable[str] | None, min_size: int | float | None, max_size: int | float | None, search_folders: bool, sort: str, exact: bool, folder_match_mode: str, folder_selfs: Iterable[str] | None, folder_subtrees: Iterable[str] | None) -> SearchOrderKey: return (_data_generation, q.strip(), tuple(canonical_repos(repos) or ()), tuple(extensions or ()), tuple(folders or ()), min_size, max_size, search_folders, sort, exact, folder_match_mode, tuple(folder_selfs or ()), tuple(folder_subtrees or ())) def _get_search_order(q: str, repos: Sequence[str] | None, extensions: Sequence[str] | None, folders: Sequence[str] | None, min_size: int | float | None, max_size: int | float | None, search_folders: bool, sort: str, exact: bool, folder_match_mode: str, folder_selfs: Sequence[str] | None, folder_subtrees: Sequence[str] | None) -> "array[int]": key = _search_order_key(q, repos, extensions, folders, min_size, max_size, search_folders, sort, exact, folder_match_mode, folder_selfs, folder_subtrees) now = time.monotonic() for old_key, (created, _) in list(_search_order_cache.items()): if now - created >= SEARCH_ORDER_CACHE_TTL_SECONDS: del _search_order_cache[old_key] cached = _search_order_cache.get(key) if cached is not None: _search_order_cache[key] = (now, cached[1]) _search_order_cache.move_to_end(key) return cached[1] indices = _search_order_uncached(q, repos, extensions, folders, min_size, max_size, search_folders, sort, exact, folder_match_mode, folder_selfs, folder_subtrees) # Oversized queries still return all results; only caching is skipped. packed = indices if isinstance(indices, array) else array('I', indices) size = len(packed) * packed.itemsize if size <= SEARCH_ORDER_CACHE_BYTES_MAX: while _search_order_cache and (len(_search_order_cache) >= SEARCH_ORDER_CACHE_MAX or sum(len(v[1]) * v[1].itemsize for v in _search_order_cache.values()) + size > SEARCH_ORDER_CACHE_BYTES_MAX): _search_order_cache.popitem(last=False) _search_order_cache[key] = (now, packed) return packed def _find_search_anchor(indices: "array[int]", anchor_id: str) -> int: owner = id(indices) cached = _search_anchor_cache.get(owner) if cached is not None and cached[0]() is not indices: del _search_anchor_cache[owner] cached = None if cached is not None and anchor_id in cached[1]: cached[1].move_to_end(anchor_id) _search_anchor_cache.move_to_end(owner) return cached[1][anchor_id] anchor_repo, separator, anchor_path = anchor_id.partition('\0') index = -1 if separator: for offset, idx in enumerate(indices): rec = records[idx] repo = str(rec.get('Repo', '')) if repo == anchor_repo: matches = build_record_relative_path(rec) == anchor_path elif '\0' in repo and anchor_id.startswith(f'{repo}\0'): # Preserve raw-key matching for injected repository names. matches = f'{repo}\0{build_record_relative_path(rec)}' == anchor_id else: continue if matches: index = offset break if len(anchor_id) <= SEARCH_ANCHOR_KEY_MAX: lookups: OrderedDict[str, int] = cached[1] if cached is not None else OrderedDict() lookups[anchor_id] = index while len(lookups) > SEARCH_ANCHOR_PER_ORDER_MAX: lookups.popitem(last=False) # Do not keep a complete order alive after its normal cache eviction. _search_anchor_cache[owner] = (weakref.ref(indices), lookups) _search_anchor_cache.move_to_end(owner) while len(_search_anchor_cache) > SEARCH_ANCHOR_ORDER_MAX: _search_anchor_cache.popitem(last=False) return index def _search_uncached(q: str = "", repos: Sequence[str] | None = None, extensions: Sequence[str] | None = None, folders: Sequence[str] | None = None, min_size: int | float | None = None, max_size: int | float | None = None, page: int = 1, page_size: int = 100, search_folders: bool = True, sort: str = "relevance", exact: bool = False, folder_match_mode: str = "prefix", folder_selfs: Sequence[str] | None = None, folder_subtrees: Sequence[str] | None = None, anchor_id: str | None = None) -> JsonObject: indices = _get_search_order(q, repos, extensions, folders, min_size, max_size, search_folders, sort, exact, folder_match_mode, folder_selfs, folder_subtrees) total, results = paginate_indices(indices, page, page_size) response = build_response(results, total, page, page_size) if anchor_id is not None: response['anchor_index'] = _find_search_anchor(indices, anchor_id) return response def _search_order_uncached(q: str = "", repos: Sequence[str] | None = None, extensions: Sequence[str] | None = None, folders: Sequence[str] | None = None, min_size: int | float | None = None, max_size: int | float | None = None, search_folders: bool = True, sort: str = "relevance", exact: bool = False, folder_match_mode: str = "prefix", folder_selfs: Sequence[str] | None = None, folder_subtrees: Sequence[str] | None = None) -> Sequence[int]: q = q.strip() # Every star-only term matches the empty substring in every field. Reuse # browsing's filtering and stable precomputed order, but retain the exact # search path's list return type and original request cache keys. if exact and q and all(not term.strip("*") for term in split_exact_terms(q)): return list(_search_order_uncached("", repos, extensions, folders, min_size, max_size, search_folders, sort, False, folder_match_mode, folder_selfs, folder_subtrees)) if exact and q: terms = split_exact_terms(q) matched: set[int] | None = None scope: list[int] | None = None for term in terms: matcher = compile_exact_matcher(term) if "*" not in term and "?" not in term: candidates = sorted(_term_literal_candidates(term, repos)) else: # Earlier terms are an AND constraint. Rechecking only those # records is equivalent and does not change wildcard semantics. if matched is not None: candidates = matched else: if scope is None: scope = _wildcard_literal_candidates(term, repos, literal_candidates, get_initial_indices) candidates = scope term_matches: set[int] = set() for idx in candidates: rec = cast(IndexedRecord, records[idx]) if (matcher(rec.get("_file_lower", "")) or matcher(rec.get("_repo_lower", "")) or (search_folders and matcher(rec.get("_folder_path_lower", "")))): term_matches.add(idx) matched = term_matches if matched is None else matched.intersection(term_matches) if not matched: break filtered = sorted(matched or ()) # Exact matching must still honor every record-level filter. This block # was dropped when exact terms were split: without it, extension, folder, # size and mixed-folder filters were silently ignored in exact mode. if folder_match_mode == "mixed": filtered = apply_mixed_folder_filters(filtered, folder_selfs, folder_subtrees) filtered = apply_filters(filtered, repos, extensions, None, min_size, max_size) else: filtered = apply_filters(filtered, repos, extensions, folders, min_size, max_size, folder_match_mode) if sort == "name": filtered.sort(key=sort_key_name) elif sort == "size": filtered.sort(key=sort_key_size) return filtered if not q: has_record_filters = extensions or folders or min_size is not None or max_size is not None or folder_match_mode == "mixed" can_use_precomputed = not has_record_filters and (not repos or len(repos) == 1) if can_use_precomputed: if repos and len(repos) == 1: repo = repos[0] if sort == "name": indices = repo_sorted_by_name.get(repo, []) elif sort == "size": indices = repo_sorted_by_size.get(repo, []) else: indices = repo_records_map.get(repo, []) else: if sort == "name": indices = sorted_by_name elif sort == "size": indices = sorted_by_size else: indices = range(len(records)) return indices else: if folder_match_mode == "mixed": indices = mixed_folder_index_candidates(repos, folder_selfs, folder_subtrees) if indices is None: indices = get_initial_indices(repos) filtered = apply_mixed_folder_filters(indices, folder_selfs, folder_subtrees) filtered = apply_filters(filtered, repos, extensions, None, min_size, max_size) else: indices = get_initial_indices(repos) filtered = apply_filters(indices, repos, extensions, folders, min_size, max_size, folder_match_mode) if sort == "name": filtered.sort(key=sort_key_name) elif sort == "size": filtered.sort(key=sort_key_size) return filtered terms = split_exact_terms(q) multi_term = len(terms) > 1 query_tokens = tokenize(q) fuzzy_tokens: set[str] = set() if multi_term: # Whitespace separates independent AND terms. Candidate sets are the # union of the existing jieba/fuzzy postings and a literal substring # scan, so matches that cross a jieba token boundary are retained. posting_cache: dict[str, set[int]] = {} matched_terms: set[int] | None = None for term in terms: # The literal branch is authoritative. jieba/fuzzy candidates only # widen plain words; punctuation-bearing terms must stay literal so # "手。机" never degrades into "手机". if not search_folders: candidates, term_fuzzy = _term_candidates(term, len(query_tokens), posting_cache, False) plain = _term_is_plain(term) else: plain = _term_is_plain(term) if not plain: # Fuzzy candidates would be discarded below and token # metadata is only used by files-only post-filtering. candidates, term_fuzzy = set[int](), set[str]() else: candidates, term_fuzzy = _term_candidates(term, len(query_tokens), posting_cache, True) literal = { idx for idx in _term_literal_candidates(term, repos) if _term_matches_literal(records[idx], term, search_folders) } candidates |= literal if not plain: candidates = literal matched_terms = candidates if matched_terms is None else matched_terms.intersection(candidates) fuzzy_tokens |= term_fuzzy if not matched_terms: break matched_order = sorted(matched_terms or ()) if not search_folders and query_tokens and matched_order: matched_order = [idx for idx in matched_order if matches_file_query(records[idx], query_tokens, fuzzy_tokens)] if folder_match_mode == "mixed": filtered = apply_mixed_folder_filters(matched_order, folder_selfs, folder_subtrees) filtered = apply_filters(filtered, repos, extensions, None, min_size, max_size) else: filtered = apply_filters(matched_order, repos, extensions, folders, min_size, max_size, folder_match_mode) if sort == "name": filtered.sort(key=sort_key_name) return filtered if sort == "size": filtered.sort(key=sort_key_size) return filtered scored = [(idx, score_record(idx, query_tokens, search_folders)) for idx in filtered] if sort == "relevance": scored.sort(key=lambda x: (-x[1], x[0])) return [idx for idx, _ in scored] fuzzy_candidate_limit = 200 if len(query_tokens) == 1 else None posting_cache = {} def query_postings(token: str) -> set[int]: if token not in posting_cache: posting_cache[token] = scoped_word_postings(token, search_folders=search_folders) return posting_cache[token] exact_constraint: set[int] | None = None for tok in query_tokens: if tok not in word_index: continue postings = query_postings(tok) if not postings: continue exact_constraint = set(postings) if exact_constraint is None else exact_constraint.intersection(postings) token_candidates: list[set[int]] = [] for tok in query_tokens: candidates = query_postings(tok) if tok in word_index else set[int]() if not candidates: fuzzy_tokens.add(tok) fuzzy_candidates: set[int] = set() if exact_constraint is not None: for idx in sorted(exact_constraint): rec = records[idx] record_tokens = tokenize(" ".join([cast(str, rec.get("File", "")), *(cast(list[str], rec.get("Folder", []) or []) if search_folders else [])])) if any(is_fuzzy_match(tok, word) for word in record_tokens): fuzzy_candidates.add(idx) if fuzzy_candidate_limit is not None and len(fuzzy_candidates) >= fuzzy_candidate_limit: break else: tok_len = len(tok) for delta in (-2, -1, 0, 1, 2): for vocab_word in vocab_by_len.get(tok_len + delta, []): if is_fuzzy_match(tok, vocab_word): fuzzy_candidates.update(query_postings(vocab_word)) if fuzzy_candidate_limit is not None and len(fuzzy_candidates) >= fuzzy_candidate_limit: break if fuzzy_candidate_limit is not None and len(fuzzy_candidates) >= fuzzy_candidate_limit: break candidates = fuzzy_candidates if not candidates: token_candidates = [] break token_candidates.append(candidates) if token_candidates: token_candidates.sort(key=len) matched = set(token_candidates[0]) for candidates in token_candidates[1:]: matched.intersection_update(candidates) if not matched: break all_matched = list(matched) else: all_matched = [] literal_query = q.lower() if literal_query: literal_matches: list[int] = [] initial_indices = get_initial_indices(repos) candidates = literal_candidates(literal_query, repos) if candidates is not None: initial_indices = sorted(candidates) skip = set(all_matched) for idx in initial_indices: if skip and idx in skip: continue rec = cast(IndexedRecord, records[idx]) file_name = rec.get("_file_lower", "") folder_path = rec.get("_folder_path_lower", "") repo_name = rec.get("_repo_lower", "") if literal_query in file_name or literal_query in repo_name or (search_folders and literal_query in folder_path): literal_matches.append(idx) if literal_matches: all_matched.extend(idx for idx in literal_matches if idx not in skip) if not search_folders and query_tokens and all_matched: all_matched = [idx for idx in all_matched if matches_file_query(records[idx], query_tokens, fuzzy_tokens)] if folder_match_mode == "mixed": filtered = apply_mixed_folder_filters(all_matched, folder_selfs, folder_subtrees) filtered = apply_filters(filtered, repos, extensions, None, min_size, max_size) else: filtered = apply_filters(all_matched, repos, extensions, folders, min_size, max_size, folder_match_mode) if sort == "name": filtered.sort(key=sort_key_name) return filtered if sort == "size": filtered.sort(key=sort_key_size) return filtered scored = [(idx, score_record(idx, query_tokens, search_folders)) for idx in filtered] if sort == "relevance": scored.sort(key=lambda x: (-x[1], x[0])) return [idx for idx, _ in scored] def build_filter_folder_tree(repo: str) -> list[JsonObject]: if repo in folder_tree_data: return folder_tree_data[repo] return cast(list[JsonObject], _build_folder_tree(repo, folder_index, repo_records_map, records)) def get_folder_contents(repo: str, path: str) -> JsonObject: return _get_folder_contents( repo, path, get_browser=lambda: folder_browser_data, get_folder_index=lambda: folder_index, get_repo_indices=lambda: repo_records_map, get_records=lambda: records, enrich_browser_entry=lambda repo, path, entry: enrich_browser_entry(repo, path, entry), build_record_link=lambda record: build_record_link(record), build_record_path_url=lambda record: build_record_path_url(record), ) DOWNLOAD_CONNECTION_WARM_INTERVAL_SECONDS = 30 async def warm_download_connection(app: FastAPI): # Use the download pool, but never queue speculative work behind real transfers. semaphore = app.state.upstream_semaphore if semaphore.locked(): return try: async with semaphore: async with app.state.http_session.head( "https://huggingface.co/robots.txt", allow_redirects=False, timeout=aiohttp.ClientTimeout(total=4, connect=3, sock_read=3), ): pass except (aiohttp.ClientError, asyncio.TimeoutError): # A failed warmup must not affect ping or the later download attempt. pass def schedule_download_connection_warm(app: FastAPI): state = app.state if not getattr(state, "download_warm_enabled", False): return task = state.download_warm_task now = time.monotonic() if task is not None and not task.done(): return if now - state.download_warm_at < DOWNLOAD_CONNECTION_WARM_INTERVAL_SECONDS: return state.download_warm_at = now state.download_warm_task = asyncio.create_task(warm_download_connection(app)) @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: global last_user_request_at load_data() app.state.search_executor = SearchExecutor() app.state.reader_index_build_task = None app.state.reader_index_warm_task = None app.state.http_session = aiohttp.ClientSession( timeout=aiohttp.ClientTimeout(total=300, connect=15), connector=aiohttp.TCPConnector(keepalive_timeout=60, ttl_dns_cache=300), headers={"User-Agent": "VoiceOfML-Search/1.0"}, auto_decompress=True, ) app.state.upstream_semaphore = asyncio.Semaphore(8) app.state.download_warm_enabled = True app.state.download_warm_task = None app.state.download_warm_at = float("-inf") app.state.reader_assets_lock = asyncio.Lock() app.state.reader_assets_task = None initialize_reader_bucket_state(app) initialize_reader_archive_state(app) range_cache: OrderedDict[RangeKey, RangeCacheEntry] = OrderedDict() app.state.reader_range_cache = range_cache app.state.reader_range_cache_bytes = 0 app.state.reader_range_flights = {} app.state.reader_range_flight_owners = set() last_user_request_at = time.monotonic() app.state.reader_index_warm_task = asyncio.create_task(warm_reader_indexes()) try: yield finally: warm_task = cast("asyncio.Task[None] | None", app.state.reader_index_warm_task) if warm_task is not None: warm_task.cancel() await asyncio.gather(warm_task, return_exceptions=True) app.state.reader_index_warm_task = None if app.state.reader_index_build_task is not None: app.state.reader_index_build_task.cancel() await asyncio.gather(app.state.reader_index_build_task, return_exceptions=True) app.state.reader_index_build_task = None await app.state.search_executor.close() del app.state.search_executor if app.state.reader_assets_task is not None: app.state.reader_assets_task.cancel() await asyncio.gather(app.state.reader_assets_task, return_exceptions=True) app.state.reader_assets_task = None app.state.download_warm_enabled = False if app.state.download_warm_task is not None: app.state.download_warm_task.cancel() await asyncio.gather(app.state.download_warm_task, return_exceptions=True) app.state.download_warm_task = None await shutdown_reader_bucket_state(app) await shutdown_reader_archive_state(app) await shutdown_reader_range_flights() app.state.reader_range_cache.clear() app.state.reader_range_cache_bytes = 0 await app.state.http_session.close() app = FastAPI(title="VoiceOfML Search", version="2.0", lifespan=lifespan) app.add_middleware(GZipMiddleware, minimum_size=500) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], expose_headers=["Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Last-Modified", "Server-Timing"], ) @app.middleware("http") async def track_user_activity(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response: global last_user_request_at if request.url.path not in ("/health", "/favicon.ico", "/api/ping"): last_user_request_at = time.monotonic() return await call_next(request) SearchText = Annotated[str, Field(max_length=256)] SearchListItem = Annotated[str, Field(max_length=512)] SearchList = Annotated[list[SearchListItem], Field(max_length=100)] FolderSearchList = Annotated[list[SearchListItem], Field(max_length=10000)] class SearchRequest(BaseModel): q: SearchText = "" repos: Optional[SearchList] = None extensions: Optional[SearchList] = None folders: Optional[FolderSearchList] = None folder_match_mode: Literal["prefix", "exact", "mixed"] = "prefix" folder_selfs: Optional[FolderSearchList] = None folder_subtrees: Optional[FolderSearchList] = None min_size: Optional[int] = Field(default=None, ge=0) max_size: Optional[int] = Field(default=None, ge=0) page: int = Field(default=1, ge=1) page_size: int = Field(default=100, ge=1, le=500) search_folders: bool = True sort: Literal["relevance", "name", "size"] = "relevance" exact: bool = False anchor_id: Optional[str] = Field(default=None, max_length=16384) def normalize_search_list(values: list[str] | None, lowercase: bool = False) -> list[str] | None: if not values: return None return list(dict.fromkeys(value.strip().lower() if lowercase else value.strip() for value in values)) async def build_search_api_response(body: SearchRequest, repos: list[str] | None) -> Response: params = body.model_dump(exclude={"repos"}) for name in ("extensions", "folders", "folder_selfs", "folder_subtrees"): params[name] = normalize_search_list(params[name], lowercase=name == "extensions") compute = functools.partial(search, repos=repos, **params) try: executor = getattr(app.state, "search_executor", None) if executor is None: # Direct endpoint tests without ASGI lifespan own a temporary pool. async with SearchExecutor() as executor: payload, queued_ms, search_ms = await executor.run(compute) else: payload, queued_ms, search_ms = await executor.run(compute) except SearchBusy: return JSONResponse({"error": "搜索繁忙,请稍后重试"}, status_code=503, headers={"Retry-After": "1"}) started = time.perf_counter() assets = await get_reader_assets(wait=False) assets_ms = (time.perf_counter() - started) * 1000 started = time.perf_counter() key = ("search", _data_generation, reader_assets_revision, READER_ASSET_ROUTING_CONTRACT_VERSION, tuple(canonical_repos(repos) or ()), json.dumps(params, sort_keys=True, ensure_ascii=False)) # SearchExecutor retains the callable's result type. The legacy bounded # cache is heterogeneous, but this search path always returns a mapping. response = cached_json_response(key, lambda: add_reader_assets(cast(JsonObject, payload), assets)) response.headers["Server-Timing"] = ( f"queue;dur={queued_ms:.2f}, search;dur={search_ms:.2f}, " f"reader_assets;dur={assets_ms:.2f}, response;dur={(time.perf_counter() - started) * 1000:.2f}") return response @app.get("/api/search") async def api_search_method_not_allowed(): return JSONResponse({"detail": "Method Not Allowed", "allow": ["POST"]}, status_code=405, headers={"Allow": "POST"}) @app.get("/api/search/{repo_name}") async def api_search_repo_method_not_allowed(repo_name: str): return JSONResponse({"detail": "Method Not Allowed", "allow": ["POST"]}, status_code=405, headers={"Allow": "POST"}) @app.post("/api/search") async def api_search(body: SearchRequest): return await build_search_api_response(body, normalize_search_list(body.repos)) @app.post("/api/search/{repo_name}") async def api_search_repo(repo_name: str, body: SearchRequest): full_repo = f"VoiceOfML/{repo_name}" if full_repo not in repo_counts: return JSONResponse({"error": f"仓库 {full_repo} 不存在", "results": [], "total": 0}, status_code=404) return await build_search_api_response(body, [full_repo]) @app.get("/api/repos") def api_repos(): return cached_json_response(("repos", _data_generation), lambda: repo_list, METADATA_CACHE_HEADERS) @app.get("/api/reader-assets") async def api_reader_assets(): assets = await get_reader_assets() cache_control = "public, max-age=300" if assets.get("f") else "no-store" return JSONResponse(assets, headers={"Cache-Control": cache_control}) @app.get("/api/reader-v3-status") async def api_reader_v3_status(): assets = await get_reader_assets() metadata = cast("JsonObject | None", assets.get("v3")) return JSONResponse({"version": 1, "surface": "hf", "active": metadata is not None, **(metadata or {})}, headers={"Cache-Control": "no-store"}) @app.get("/api/extensions") def api_extensions(repo: Optional[str] = Query(default=None)): def build(): if repo: full_repo = f"VoiceOfML/{repo}" ext_count = repo_extension_counts.get(full_repo, {}) else: ext_count = extension_counts sorted_exts = sorted(ext_count.keys()) return [{"name": e, "count": ext_count[e]} for e in sorted_exts] return cached_json_response(("extensions", _data_generation, repo or ""), build, METADATA_CACHE_HEADERS) @app.get("/api/folders/{repo_name}") def api_folders(repo_name: str): full_repo = f"VoiceOfML/{repo_name}" if full_repo not in repo_counts: return JSONResponse({"error": f"仓库 {full_repo} 不存在"}, status_code=404) return cached_json_response(("folders", _data_generation, full_repo), lambda: build_filter_folder_tree(full_repo)) @app.get("/api/folders/{repo_name}/contents") def api_folder_contents(repo_name: str, path: str = Query(default="")): full_repo = f"VoiceOfML/{repo_name}" if full_repo not in repo_counts: return JSONResponse({"error": f"仓库 {full_repo} 不存在"}, status_code=404) return cached_json_response(("folder_contents", _data_generation, full_repo, path), lambda: get_folder_contents(full_repo, path)) @app.get("/api/random") def api_random(repo: Optional[str] = Query(default=None)): if repo: full_repo = f"VoiceOfML/{repo}" repo_indices = repo_records_map.get(full_repo, []) if not repo_indices: return JSONResponse({"error": "无可用记录"}, status_code=404) rec = public_record(records[random.choice(repo_indices)]) else: if not records: return JSONResponse({"error": "无可用记录"}, status_code=404) rec = public_record(random.choice(records)) return JSONResponse(rec) def converted_reader_indices(assets: JsonObject, full_repo: str | None = None) -> dict[int, JsonObject]: global reader_join_cache_key, reader_join_cache ensure_reader_indexes() cache_key = (_data_generation, reader_assets_revision, READER_ASSET_ROUTING_CONTRACT_VERSION) if reader_join_cache_key != cache_key: converted: dict[int, JsonObject] = {} for key, asset in cast(JsonObject, assets.get("f", {})).items(): if not isinstance(asset, dict) or cast(JsonObject, asset).get("s") != 2: continue index = reader_record_key_indices.get(key) if index is not None: converted[index] = cast(JsonObject, asset) by_repo: dict[str, dict[int, JsonObject]] = {} for index, asset in converted.items(): repo = cast(str, records[index].get("Repo", "")) by_repo.setdefault(repo, {})[index] = asset reader_join_cache = {"all": converted, "repos": by_repo} reader_join_cache_key = cache_key if full_repo: return reader_join_cache["repos"].get(full_repo, {}) return reader_join_cache["all"] async def get_reader_pool(repo: str | None = None) -> tuple[Sequence[int], dict[int, JsonObject]]: global reader_pool_cache_key, reader_pool_cache # A cold pool needs both the complete routing indexes and the first # complete asset snapshot. Their shared owners are independent, so overlap # the waits without selecting from a partial pool or weakening cancellation. # With an existing snapshot, do not schedule a refresh while waiting on the # index: keep the previous refresh timing and select from the then-current # published revision, as the warm path already does. if _reader_indexes_ready: assets = await get_reader_assets(wait=not bool(reader_assets_cache.get("f"))) elif reader_assets_cache.get("f"): await ensure_reader_indexes_async() assets = await get_reader_assets(wait=not bool(reader_assets_cache.get("f"))) else: assets = await resolve_cold_reader_dependencies() # A second already-in-flight refresh may have published while the # index was building. Do not join old data under its newer revision. if assets is not reader_assets_cache: assets = reader_assets_cache full_repo = f"VoiceOfML/{repo}" if repo else None original = repo_reader_record_indices.get(full_repo, []) if full_repo else reader_record_indices # Random selection uses the complete last published snapshot while refresh # proceeds; a cold process must still await its first asset generation. converted = converted_reader_indices(assets, full_repo) cache_key = (_data_generation, reader_assets_revision, READER_ASSET_ROUTING_CONTRACT_VERSION) if reader_pool_cache_key != cache_key: reader_pool_cache = {} reader_pool_cache_key = cache_key if full_repo in reader_pool_cache: return reader_pool_cache[full_repo], converted if not original and not converted: # Never retain arbitrary, unknown repository names supplied by callers. return (), converted pool = dict.fromkeys(original) pool.update(dict.fromkeys(converted)) # Packed immutable-by-convention IDs bound memory to the global list plus # non-overlapping per-repository lists and preserve the original order. result = array('I', pool) reader_pool_cache[full_repo] = result return result, converted @app.get("/api/random-reader") async def api_random_reader(repo: Optional[str] = Query(default=None)): started = time.perf_counter() pool, converted = await get_reader_pool(repo) if not pool: return JSONResponse({"error": "无可读文档"}, status_code=404) index = random.choice(pool) rec = public_record(records[index]) asset = converted.get(index) if asset: rec = enrich_reader_record(rec, asset) return JSONResponse(rec, headers={"Server-Timing": f"reader_select;dur={(time.perf_counter() - started) * 1000:.2f}"}) @app.get("/api/random-reader/status") async def api_random_reader_status(repo: Optional[str] = Query(default=None)): pool, _ = await get_reader_pool(repo) count = len(pool) return JSONResponse({"available": count > 0, "count": count}, headers=METADATA_CACHE_HEADERS) @app.get("/api/bootstrap") def api_bootstrap(): return JSONResponse( cached_payload(("bootstrap", _data_generation), build_global_bootstrap), headers=METADATA_CACHE_HEADERS, ) @app.get("/api/ping") async def api_ping(): schedule_download_connection_warm(app) return PlainTextResponse(status_code=204, headers={"Cache-Control": "no-store"}) READER_UPSTREAM_RESPONSE_HEADERS = ( "Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "ETag", "Last-Modified", "Cache-Control", ) READER_COMPRESSIBLE_SUFFIXES = {"txt", "md", "markdown", "html", "htm", "xhtml", "json", "css", "xml"} def reader_body_allows_compression(target_url: str, request: Request | None = None, status: int = 200) -> bool: # Only complete text bodies may use the existing negotiated GZip middleware. # Ranges/conditionals, HEAD, PDFs, images, archives and native media retain # their exact-byte/length policy. Expanded client byte limits still apply. if status != 200 or (request is not None and request.method != "GET"): return False headers: Mapping[str, str] = request.headers if request is not None else {} if any(name in headers for name in ("Range", "If-Range", "If-None-Match", "If-Modified-Since")): return False return unquote(urlparse(target_url).path).rsplit(".", 1)[-1].lower() in READER_COMPRESSIBLE_SUFFIXES READER_ISOLATION_HEADERS = { "Content-Security-Policy": "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'", "X-Content-Type-Options": "nosniff", } READER_DOCUMENT_MAX_BYTES = 512 * 1024 * 1024 # PDFs have their own limit for both complete bodies and range totals. Other # document formats retain their existing limits. READER_PDF_MAX_BYTES = 2 * 1024 * 1024 * 1024 READER_RESOURCE_MAX_ARCHIVE_BYTES = 512 * 1024 * 1024 READER_RESOURCE_MAX_BYTES = 64 * 1024 * 1024 READER_BUCKET_CACHE_TTL_SECONDS = 3600 READER_BUCKET_CACHE_MAX_BYTES = 32 * 1024 * 1024 READER_BUCKET_CACHE_MAX_ITEM_BYTES = 8 * 1024 * 1024 READER_BUCKET_MAX_CONCURRENT_READS = 8 READER_BUCKET_MAX_INFLIGHT = 32 READER_OCR_CACHE_MAX_BYTES = 32 * 1024 * 1024 READER_OCR_CACHE_MAX_ITEMS = 4 READER_OCR_SEARCH_MAX_CONCURRENT = 2 READER_ARCHIVE_MAX_ENTRIES = 20_000 READER_ARCHIVE_MAX_EXPANDED_BYTES = 1536 * 1024 * 1024 READER_ARCHIVE_MAX_COMPRESSION_RATIO = 200 READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES = 8 * 1024 * 1024 READER_ARCHIVE_MAX_METADATA_BYTES = 16 * 1024 * 1024 READER_ARCHIVE_CACHE_TTL_SECONDS = 900 READER_ARCHIVE_CACHE_MAX_BYTES = 32 * 1024 * 1024 READER_ARCHIVE_CACHE_MAX_ENTRIES = 4 READER_ARCHIVE_MAX_CONCURRENT_LOADS = 2 READER_ARCHIVE_MAX_INFLIGHT = 16 READER_ARCHIVE_MAX_WORKERS = 2 READER_ARCHIVE_MEMBER_RE = re.compile(r"^[^/\x00]+(?:/[^/\x00]+)*(?:/)?$") READER_RANGE_CACHE_TTL_SECONDS = 900 READER_RANGE_CACHE_MAX_BYTES = 32 * 1024 * 1024 READER_RANGE_CACHE_MAX_ITEM_BYTES = 2 * 1024 * 1024 READER_RANGE_CACHE_MAX_ENTRIES = 256 READER_RANGE_MAX_FLIGHTS = 32 # Validation moved to backend.reader_archive; app keeps the public names and owns the limits. from backend.reader_archive import (ReaderArchiveInvalidError as ReaderArchiveInvalidError, ReaderArchiveLimitError as ReaderArchiveLimitError, ReaderArchiveLimits as _ReaderArchiveLimits, ReaderDocumentLimitError as ReaderDocumentLimitError, validate_reader_archive as _validate_reader_archive) def validate_reader_archive(archive: bytes) -> None: # Pass this module itself: every limit is read when used, so patch.object(app, ...) still applies. _validate_reader_archive(archive, cast(_ReaderArchiveLimits, sys.modules[__name__])) READER_RESOURCE_TYPES = { "json": "application/json", "xhtml": "application/xhtml+xml", "html": "text/html", "txt": "text/plain", "md": "text/markdown", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "pdf": "application/pdf", "djvu": "image/vnd.djvu", "epub": "application/epub+zip", "css": "text/css", "jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "gif": "image/gif", "bmp": "image/bmp", "webp": "image/webp", "jxl": "image/jxl", "svg": "image/svg+xml", "ttf": "font/ttf", "otf": "font/otf", "woff": "font/woff", "woff2": "font/woff2", "mp3": "audio/mpeg", "wav": "audio/wav", "m4a": "audio/mp4", "flac": "audio/flac", "mpga": "audio/mpeg", "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 = 0 target_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 = 0 target_app.state.reader_ocr_inflight = {} target_app.state.reader_ocr_search_semaphore = asyncio.Semaphore(READER_OCR_SEARCH_MAX_CONCURRENT) async 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 = 0 target_app.state.reader_ocr_cache.clear() target_app.state.reader_ocr_cache_bytes = 0 ocr_tasks = list(getattr(target_app.state, "reader_ocr_inflight", {}).values()) target_app.state.reader_ocr_inflight.clear() for task in ocr_tasks: task.cancel() if ocr_tasks: await 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: str expected_bytes: int 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 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 exc class _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 payload async def get_reader_bucket_resource(path: str, max_bytes: int = READER_RESOURCE_MAX_BYTES) -> bytes: state = app.state cache_key = path if is_reader_bucket_cacheable(path): cached = state.reader_bucket_cache.get(cache_key) if cached: cached_at, payload = cached if time.monotonic() - cached_at < READER_BUCKET_CACHE_TTL_SECONDS: 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) >= 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 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_reader_bucket_read(path: str, max_bytes: int) -> bytes: state = app.state semaphore = state.reader_bucket_semaphore await 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]: return _parse_reader_ocr_book(raw, READER_RESOURCE_MAX_BYTES) async def _load_reader_ocr_book(path: str) -> list[OcrPage]: state = app.state raw = await get_reader_bucket_resource(path) pages, size = await asyncio.to_thread(parse_reader_ocr_book, raw) if size <= READER_OCR_CACHE_MAX_BYTES: previous = state.reader_ocr_cache.pop(path, None) if previous: state.reader_ocr_cache_bytes -= previous[2] state.reader_ocr_cache[path] = (time.monotonic(), pages, size) state.reader_ocr_cache_bytes += size while (len(state.reader_ocr_cache) > READER_OCR_CACHE_MAX_ITEMS or state.reader_ocr_cache_bytes > READER_OCR_CACHE_MAX_BYTES): _, (_, _, evicted_size) = state.reader_ocr_cache.popitem(last=False) state.reader_ocr_cache_bytes -= evicted_size return pages async def get_reader_ocr_book(path: str) -> list[OcrPage]: """Load and parse one OCR book once, even during a cold concurrent burst.""" state = app.state if not hasattr(state, "reader_ocr_cache"): ocr_cache: OrderedDict[str, tuple[float, list[OcrPage], int]] = OrderedDict() state.reader_ocr_cache = ocr_cache state.reader_ocr_cache_bytes = 0 if not hasattr(state, "reader_ocr_inflight"): ocr_inflight: dict[str, asyncio.Task[list[OcrPage]]] = {} state.reader_ocr_inflight = ocr_inflight cached = state.reader_ocr_cache.get(path) if cached: cached_at, pages, size = cached if time.monotonic() - cached_at < READER_BUCKET_CACHE_TTL_SECONDS: state.reader_ocr_cache.move_to_end(path) return pages state.reader_ocr_cache.pop(path) state.reader_ocr_cache_bytes -= size task = state.reader_ocr_inflight.get(path) if task is None: task = asyncio.create_task(_load_reader_ocr_book(path)) state.reader_ocr_inflight[path] = task def settled(done: "asyncio.Task[list[OcrPage]]") -> None: if state.reader_ocr_inflight.get(path) is done: state.reader_ocr_inflight.pop(path, None) if not done.cancelled(): done.exception() task.add_done_callback(settled) return await asyncio.shield(task) @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 = True if 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_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) <= READER_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)} # 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/")) else READER_PDF_MAX_BYTES if suffix == "pdf" else READER_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: target_app.state.reader_archive_cache = OrderedDict() target_app.state.reader_archive_inflight = {} target_app.state.reader_archive_workers = set() target_app.state.reader_archive_load_semaphore = asyncio.Semaphore(READER_ARCHIVE_MAX_CONCURRENT_LOADS) target_app.state.reader_archive_worker_semaphore = asyncio.Semaphore(READER_ARCHIVE_MAX_WORKERS) async def shutdown_reader_archive_state(target_app: FastAPI) -> None: tasks = list(target_app.state.reader_archive_inflight.values()) for task in tasks: task.cancel() if tasks: await asyncio.gather(*tasks, return_exceptions=True) workers = list(target_app.state.reader_archive_workers) if workers: await asyncio.gather(*workers, return_exceptions=True) target_app.state.reader_archive_inflight.clear() target_app.state.reader_archive_cache.clear() async def run_reader_archive_worker(function: Callable[..., _T], *args: object) -> _T: state = app.state semaphore = state.reader_archive_worker_semaphore await semaphore.acquire() task = asyncio.create_task(asyncio.to_thread(function, *args)) state.reader_archive_workers.add(task) def finished(done: "asyncio.Task[_T]") -> None: # Cancelling a caller cannot stop its thread or free that thread's slot. state.reader_archive_workers.discard(done) semaphore.release() if not done.cancelled(): done.exception() task.add_done_callback(finished) return await asyncio.shield(task) # ZIP local-file/empty-archive signatures and the gzip wrapper accepted by # prepare_reader_archive. Anything else is rejected after its first bytes. READER_ARCHIVE_SIGNATURES = (b"PK\x03\x04", b"PK\x05\x06", b"\x1f\x8b") READER_ARCHIVE_SIGNATURE_PREFIX = b"PK\x03\x04" # Large non-ZIP formats served by other routes are refused before any upstream # request; every other source must still start with an archive signature. READER_NON_ARCHIVE_SUFFIXES = frozenset({ "pdf", "mobi", "azw", "azw3", "fb2", "chm", "djvu", "swf", }) def reader_archive_signature_possible(head: bytes) -> bool: return any(signature.startswith(head) or head.startswith(signature) for signature in READER_ARCHIVE_SIGNATURES) def reader_archive_source_allowed(target_url: str) -> bool: suffix = unquote(urlparse(target_url).path).rsplit("/", 1)[-1] suffix = suffix.rsplit(".", 1)[-1].lower() if "." in suffix else "" media_type = READER_RESOURCE_TYPES.get(suffix, "") return (suffix not in READER_NON_ARCHIVE_SUFFIXES and not media_type.startswith(("image/", "audio/", "video/"))) def prepare_reader_archive(raw: bytes | bytearray) -> bytes: # bytes(raw) is a no-op for bytes; only legacy bytearray callers copy. archive = raw if isinstance(raw, bytes) else bytes(raw) if archive.startswith(b"\x1f\x8b"): try: with gzip.GzipFile(fileobj=io.BytesIO(archive)) as stream: archive = stream.read(READER_RESOURCE_MAX_ARCHIVE_BYTES + 1) except (OSError, EOFError, zlib.error) as exc: raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") from exc validate_reader_archive(archive) return archive async def get_reader_archive(target_url: str) -> bytes: state = app.state cache = state.reader_archive_cache cached = cache.get(target_url) if cached: if time.monotonic() - cached[0] < READER_ARCHIVE_CACHE_TTL_SECONDS: cache.move_to_end(target_url) return cached[1] cache.pop(target_url) task = state.reader_archive_inflight.get(target_url) if task is None: if len(state.reader_archive_inflight) >= READER_ARCHIVE_MAX_INFLIGHT: raise HTTPException(503, "阅读资源请求过多") async def load() -> bytes: try: async with state.reader_archive_load_semaphore: async with state.upstream_semaphore: upstream = await open_download_response( state.http_session, target_url, aiohttp.ClientTimeout(total=180, connect=15, sock_read=60), url_validator=validate_reader_redirect_url, ) try: if upstream.status != 200: raise HTTPException(upstream.status, f"上游阅读文件加载失败: HTTP {upstream.status}") declared = (upstream.headers or {}).get("Content-Length") if (declared is not None and declared.strip().isdigit() and int(declared) > READER_RESOURCE_MAX_ARCHIVE_BYTES): raise ReaderArchiveLimitError("阅读文件过大") chunks: list[bytes] = [] size = 0 async for chunk in upstream.content.iter_chunked(64 * 1024): if not chunk: continue if size < len(READER_ARCHIVE_SIGNATURE_PREFIX): head = b"".join(chunks + [chunk])[:len(READER_ARCHIVE_SIGNATURE_PREFIX)] if not reader_archive_signature_possible(head): raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") chunks.append(chunk) size += len(chunk) if size > READER_RESOURCE_MAX_ARCHIVE_BYTES: raise ReaderArchiveLimitError("阅读文件过大") finally: upstream.release() # One contiguous immutable copy; the chunk list is dropped # immediately so validation does not hold two full buffers. raw = b"".join(chunks) chunks.clear() archive = await run_reader_archive_worker(prepare_reader_archive, raw) del raw if len(archive) <= READER_ARCHIVE_CACHE_MAX_BYTES: cache[target_url] = (time.monotonic(), archive) cache.move_to_end(target_url) while (len(cache) > READER_ARCHIVE_CACHE_MAX_ENTRIES or sum(len(item[1]) for item in cache.values()) > READER_ARCHIVE_CACHE_MAX_BYTES): cache.popitem(last=False) return archive finally: state.reader_archive_inflight.pop(target_url, None) task = asyncio.create_task(load()) task.add_done_callback(lambda done: None if done.cancelled() else done.exception()) state.reader_archive_inflight[target_url] = task return await asyncio.shield(task) def read_reader_archive_member(archive: bytes, resource_path: str) -> bytes: with zipfile.ZipFile(io.BytesIO(archive)) as book_zip: names = {name.replace("\\", "/"): name for name in book_zip.namelist()} info = book_zip.getinfo(names[resource_path]) if info.file_size > READER_RESOURCE_MAX_BYTES: raise ReaderArchiveLimitError("阅读资源过大") return book_zip.read(info) @app.get("/api/reader-resource") async def api_reader_resource(book: str = Query(...), path: str = Query(...)): try: target_url = validate_reader_source_url(book) except ValueError as exc: return JSONResponse({"error": str(exc)}, status_code=403) if not reader_archive_source_allowed(target_url): return JSONResponse({"error": "阅读文件不是 ZIP 归档"}, status_code=400) resource_path = path.replace("\\", "/") if (not resource_path or len(resource_path) > 512 or "\x00" in resource_path or any(part in {"", ".", ".."} for part in resource_path.split("/"))): return JSONResponse({"error": "不允许的阅读资源路径"}, status_code=400) try: archive = await get_reader_archive(target_url) except HTTPException as exc: return JSONResponse({"error": exc.detail}, status_code=exc.status_code, headers={"Cache-Control": "no-store"}) except ReaderArchiveLimitError as exc: return JSONResponse({"error": str(exc)}, status_code=413) except ReaderArchiveInvalidError as exc: return JSONResponse({"error": str(exc)}, status_code=400) except Exception as exc: return JSONResponse({"error": str(exc) or "上游阅读文件加载失败"}, status_code=502) try: payload = await run_reader_archive_worker(read_reader_archive_member, archive, resource_path) except KeyError: return JSONResponse({"error": "阅读资源不存在"}, status_code=404) except ReaderArchiveLimitError as exc: return JSONResponse({"error": str(exc)}, status_code=413) except (zipfile.BadZipFile, EOFError, IndexError, OverflowError, RuntimeError, NotImplementedError, OSError, zlib.error): return JSONResponse({"error": "阅读资源损坏"}, status_code=400) suffix = resource_path.rsplit(".", 1)[-1].lower() if "." in resource_path else "" return Response(content=payload, media_type=READER_RESOURCE_TYPES.get(suffix, "application/octet-stream"), headers={**READER_ISOLATION_HEADERS, "Cache-Control": "public, max-age=3600"}) @app.get("/api/reader-resolve") async def api_reader_resolve(id: str = Query(..., min_length=13, max_length=13)): if not READER_SHORT_ID_RE.fullmatch(id): return JSONResponse({"error": "无效阅读 ID"}, status_code=400) # A cold resolution must await conversion metadata; otherwise unsupported # originals (such as PS) become cached as the Reader's document source. # Index building and metadata refresh are independent. Start both together, # but never resolve with partial IDs or an incomplete first asset snapshot. if _reader_indexes_ready: assets = await get_reader_assets(wait=not bool(reader_assets_cache.get("f"))) else: assets = await resolve_cold_reader_dependencies() matches: list[JsonObject] = [] # Exact source IDs always take precedence. A legacy sidebar alias is used # only when no exact source exists and the alias names one canonical file. for index in reader_source_id_indices.get(id, []) or reader_legacy_source_id_indices.get(id, []): record = records[index] matches.append(reader_resolved_record(record, cast(dict[str, JsonObject], assets.get("f", {})).get(build_reader_asset_key(record), {}))) if len({canonical_reader_source_url(cast(str, match["download"])) for match in matches}) > 1: return JSONResponse({"error": "阅读 ID 不唯一"}, status_code=409) matches = matches[:1] if matches: return JSONResponse(matches[0], headers={"Cache-Control": "public, max-age=300" if assets.get("f") else "no-store"}) return JSONResponse({"error": "阅读文件不存在"}, status_code=404) async def resolve_cold_reader_dependencies() -> JsonObject: # The shared build/refresh tasks retain their existing shielded owners; # request-local waiters are collected on failure or cancellation. index_task = asyncio.create_task(ensure_reader_indexes_async()) asset_task = asyncio.create_task(get_reader_assets(wait=not bool(reader_assets_cache.get("f")))) try: await asyncio.gather(index_task, asset_task) finally: for task in (index_task, asset_task): if not task.done(): task.cancel() await asyncio.gather(index_task, asset_task, return_exceptions=True) return asset_task.result() @app.get("/api/reader-ocr-search") async def api_reader_ocr_search( id: str = Query(..., min_length=13, max_length=13), q: str = Query(..., min_length=1, max_length=256), page: int = Query(1, ge=1, le=1000000), page_size: int = Query(50, ge=1, le=100), ): """Search one PDF's immutable OCR text without loading it into app memory.""" resolved = await api_reader_resolve(id) if resolved.status_code != 200: return resolved try: data = json.loads(bytes(resolved.body)) manifest_url = str(data.get("ocr_manifest") or "") parsed = urlparse(manifest_url) parameters = parse_qs(parsed.query) manifest_path = parameters.get("path", [""])[0] if (parsed.path != "/api/reader-bucket-resource" or set(parameters) != {"path"} or not READER_BUCKET_PATH_RE.fullmatch(manifest_path) or not manifest_path.endswith("/ocr-manifest.json")): return JSONResponse({"error": "本书暂无 OCR 索引"}, status_code=404) manifest: object = json.loads(await get_reader_bucket_resource(manifest_path)) book = cast(JsonObject, manifest).get("book_text") if isinstance(manifest, dict) else None book_path = cast(JsonObject, book).get("path") if isinstance(book, dict) else "" if (not isinstance(book_path, str) or not READER_BUCKET_PATH_RE.fullmatch(book_path) or not book_path.endswith("/book-text.json.gz")): return JSONResponse({"error": "OCR 索引损坏"}, status_code=502) pages = await get_reader_ocr_book(book_path) needle = q.casefold() state = app.state if not hasattr(state, "reader_ocr_search_semaphore"): state.reader_ocr_search_semaphore = asyncio.Semaphore(READER_OCR_SEARCH_MAX_CONCURRENT) async with state.reader_ocr_search_semaphore: total, results = await asyncio.to_thread( search_reader_ocr_pages, pages, needle, page, page_size ) return JSONResponse({ "version": 2, "kind": "pdf-book-text-search", "page": page, "page_size": page_size, "total": total, "results": results, }, headers={"Cache-Control": "no-store"}) except (ValueError, TypeError, KeyError, EOFError, gzip.BadGzipFile, zlib.error): return JSONResponse({"error": "OCR 索引损坏"}, status_code=502) except FileNotFoundError: return JSONResponse({"error": "OCR 索引不存在"}, status_code=404, headers={"Cache-Control": "no-store"}) except ReaderBucketBusyError: return JSONResponse({"error": "OCR 索引请求过多,请稍后重试"}, status_code=503, headers=READER_BUSY_HEADERS) except Exception: # Upstream bucket/HF transport failures are gateway errors, not 500s. return JSONResponse({"error": "OCR 索引加载失败"}, status_code=502, headers={"Cache-Control": "no-store"}) @app.api_route("/api/reader-content", methods=["GET", "HEAD"]) async def api_reader_content(request: Request, url: Optional[str] = Query(default=None), id: Optional[str] = Query(default=None)): if id and not url: resolved = await api_reader_resolve(id) if resolved.status_code != 200: return resolved try: url = json.loads(bytes(resolved.body)).get("url") except (AttributeError, TypeError, ValueError): return JSONResponse({"error": "阅读文件解析失败"}, status_code=502) if not url: return JSONResponse({"error": "缺少阅读文件地址"}, status_code=400) try: parsed = urlparse(url) except ValueError as exc: return JSONResponse({"error": str(exc)}, status_code=403) is_bucket_proxy = ( (not parsed.scheme and not parsed.netloc) or (parsed.scheme == "https" and parsed.netloc == "voiceofml-search.hf.space") ) if is_bucket_proxy and parsed.path == "/api/reader-bucket-resource" and not parsed.fragment: parameters = parse_qs(parsed.query) if (set(parameters) != {"path"} or len(parameters["path"]) != 1): return JSONResponse({"error": "不允许的阅读资源路径"}, status_code=400) return await api_reader_bucket_resource(parameters["path"][0], request) bucket_prefix = next((prefix for prefix in ( "/buckets/vomebook/pdf-pages-v2/resolve/", "/buckets/vomebook/reader-assets-v2/resolve/", ) if parsed.path.startswith(prefix)), None) if (parsed.scheme == "https" and parsed.hostname == "huggingface.co" and parsed.netloc.lower() in {"huggingface.co", "huggingface.co:443"} and not parsed.username and not parsed.password and not parsed.query and not parsed.fragment and bucket_prefix is not None): resource_path = unquote(parsed.path[len(bucket_prefix):]) if not READER_BUCKET_PATH_RE.fullmatch(resource_path): return JSONResponse({"error": "不允许的阅读资源路径"}, status_code=400) return await api_reader_bucket_resource(resource_path, request) try: target_url = validate_reader_source_url(url) except ValueError as exc: return JSONResponse({"error": str(exc)}, status_code=403) source_type = READER_RESOURCE_TYPES.get(unquote(urlparse(target_url).path).rsplit(".", 1)[-1].lower(), "") if source_type == "application/pdf": return await stream_reader_document(request, target_url, max_bytes=READER_PDF_MAX_BYTES) if source_type.startswith(("audio/", "video/")): return await stream_reader_document(request, target_url, media_type=source_type) return await stream_reader_document(request, target_url) def 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 headers async def stream_reader_document( request: Request, target_url: str, *, url_validator: Callable[[str], str] = validate_reader_redirect_url, cache_control: str | None = None, max_bytes: int | None = None, media_type: str | None = None, validation_scope: Hashable | None = None, expected_sha256: str | None = None, expected_bytes: int | None = None, ) -> Response: async def open_stream() -> Response: return await _stream_reader_document( request, target_url, url_validator=url_validator, cache_control=cache_control, max_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(): return if not stop_watching.is_set(): await asyncio.sleep(0.1) # StreamingResponse handles disconnects after headers; own the wait for # the upstream slot and headers too, so abandoned books cannot occupy it. transport = asyncio.create_task(open_stream()) watcher = asyncio.create_task(disconnected()) try: await asyncio.wait((transport, watcher), return_when=asyncio.FIRST_COMPLETED) if transport.done(): return transport.result() raise asyncio.CancelledError() finally: stop_watching.set() watcher.cancel() if not transport.done(): transport.cancel() await asyncio.gather(transport, watcher, return_exceptions=True) async def _stream_reader_document( request: Request, target_url: str, *, url_validator: Callable[[str], str] = validate_reader_redirect_url, 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 = READER_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") ) range_key: RangeKey | None = ( (target_url, range_header, max_bytes, media_type) if request.method == "GET" and range_header and not has_conditionals else None ) if range_key: if not hasattr(app.state, "reader_range_cache"): app.state.reader_range_cache = cast("OrderedDict[RangeKey, RangeCacheEntry]", OrderedDict()) app.state.reader_range_cache_bytes = 0 cached = app.state.reader_range_cache.get(range_key) if cached: cached_at, payload, cached_headers = cached if 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 = covered return 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_BYTES and (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=validation_scope)) semaphore = app.state.upstream_semaphore queued_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_type status = upstream.status headers = 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 = 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") 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) 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( range_key and status == 206 and length is not None and 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 + 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 = app.state.reader_range_cache previous = 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_BYTES or 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"]) async def api_reader_cdn(request: Request, url: str = Query(...)): """Resolve a public VoiceOfML asset to its short-lived CDN URL. The browser can then range-read the CDN directly. Reader clients retain /api/reader-content as a fallback for networks that cannot reach the CDN. """ try: target_url = validate_reader_source_url(url) semaphore = app.state.upstream_semaphore await semaphore.acquire() lease = UpstreamLease(semaphore) try: upstream = lease.response = await open_download_response( app.state.http_session, target_url, aiohttp.ClientTimeout(total=30, connect=10, sock_read=15), method="HEAD", url_validator=validate_reader_redirect_url, auto_decompress=False, ) final_url = str(upstream.url) validate_reader_redirect_url(final_url) if upstream.status >= 400: return JSONResponse({"error": f"上游阅读文件加载失败: HTTP {upstream.status}"}, status_code=upstream.status) return Response(status_code=307, headers={ "Location": final_url, "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*", }) finally: lease.close() except Exception as exc: return JSONResponse({"error": str(exc) or "阅读 CDN 解析失败"}, status_code=502) @app.get("/api/reader-source-revision") async def api_reader_source_revision(url: str = Query(...)): """Resolve a DjVu source to an immutable dataset revision without its body.""" try: source = validate_reader_source_url(url) parsed = urlparse(source) decoded = validate_path_safety(parsed.path) match = re.fullmatch(r'/datasets/(VoiceOfML/[A-Za-z0-9._-]+)/(resolve|raw)/(main|[0-9a-f]{40})/(.+\.(?i:djvu))', decoded) if (not match or match.group(1).rsplit('/', 1)[-1] in {'.', '..'} or '//' in decoded or len(source.encode('utf-8')) > 16384 or any(ord(c) < 32 or ord(c) == 127 or 0xd800 <= ord(c) <= 0xdfff or c in '%?#' for c in decoded)): raise ValueError("不是有效的 DjVu 原件地址") _repo, action, requested, _path = match.groups() if action == 'raw' and requested != 'main': raise ValueError("原件版本地址无效") if requested != 'main': return JSONResponse({"url": source, "revision": requested}, headers={"Cache-Control": "no-store"}) # Query the original HF response without following redirects. The commit # header pins the exact snapshot used by the one subsequent body fetch. async with app.state.upstream_semaphore: response = await app.state.http_session.head(source, allow_redirects=False, timeout=aiohttp.ClientTimeout(total=30, connect=10, sock_read=15), headers={"Accept-Encoding":"identity", "Cache-Control":"no-cache"}) try: if response.status not in (200,301,302,303,307,308): raise ValueError(f"原件版本解析失败: HTTP {response.status}") revision = response.headers.get("X-Repo-Commit", "") if not re.fullmatch(r'[0-9a-f]{40}', revision): raise ValueError("原件版本信息缺失") finally: response.release() # Preserve the already-encoded source spelling to avoid changing URL # identity for literal parentheses or other valid filename bytes. pinned = parsed._replace(path=parsed.path.replace(f'/{action}/main/', f'/resolve/{revision}/', 1)).geturl() validate_reader_source_url(pinned) return JSONResponse({"url":pinned,"revision":revision}, headers={"Cache-Control":"no-store"}) except ValueError as exc: return JSONResponse({"error":str(exc)}, status_code=400, headers={"Cache-Control":"no-store"}) except Exception: return JSONResponse({"error":"原件版本解析失败"}, status_code=502, headers={"Cache-Control":"no-store"}) @app.get("/api/download") async def api_download(file: str = Query(...), link: str = Query(...)): try: target_url = validate_voiceofml_source_url(link) except ValueError: return JSONResponse({"error": "只允许 HuggingFace 域名"}, status_code=403) session = app.state.http_session semaphore = app.state.upstream_semaphore await semaphore.acquire() with UpstreamLease(semaphore) as lease: try: upstream = lease.response = await open_download_response( session, target_url, # Large downloads may legitimately take longer than any fixed # total; bound only connection setup and read inactivity. aiohttp.ClientTimeout(total=None, connect=15, sock_read=60), url_validator=validate_voiceofml_redirect_url, ) except Exception as e: print(f"下载代理异常: {e}") return JSONResponse({"error": str(e) or "上游下载失败"}, status_code=502) if upstream.status != 200: return JSONResponse({"error": f"上游下载失败: HTTP {upstream.status}"}, status_code=502) encoded_filename = quote(sanitize_archive_name(file), safe="") return lease.streaming_response( lease.chunks("下载代理异常"), media_type="application/octet-stream", headers={ "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}", "Cache-Control": "no-cache", }, ) @app.get("/api/download/check") async def api_download_check(link: str = Query(...)): target_url = link try: target_url = validate_voiceofml_source_url(target_url) except ValueError as e: return JSONResponse({"error": str(e)}, status_code=403) session = app.state.http_session semaphore = app.state.upstream_semaphore await semaphore.acquire() upstream = None try: upstream = await open_download_response( session, target_url, aiohttp.ClientTimeout(total=30, connect=10, sock_read=10), method="HEAD", url_validator=validate_voiceofml_redirect_url, ) if upstream.status not in (200, 206): return JSONResponse({"error": f"上游下载失败: HTTP {upstream.status}"}, status_code=502) return JSONResponse({"ok": True}) except Exception as e: print(f"下载检查异常: {e}") return JSONResponse({"error": str(e) or "上游下载失败"}, status_code=502) finally: if upstream is not None: upstream.release() semaphore.release() HASHED_ASSET_RE = re.compile(r"\.[0-9a-f]{12}\.(?:js|css|mjs)$") class HashedStaticFiles(StaticFiles): async def get_response(self, path: str, scope: Scope) -> Response: response = await super().get_response(path, scope) if response.status_code == 200 and HASHED_ASSET_RE.search(path): response.headers["Cache-Control"] = "public, max-age=31536000, immutable" elif response.status_code in (200, 304) and path.endswith(".html"): # Unhashed shells reference current hashes; never serve them from # heuristic HTTP freshness after a deploy. response.headers["Cache-Control"] = "no-cache" return response app.mount("/static", HashedStaticFiles(directory="static", html=True), name="static") app.mount("/icons", StaticFiles(directory="static/icons"), name="icons") @app.get("/manifest.json") def serve_manifest(): p = Path("static/manifest.json") if p.exists(): return JSONResponse(json.loads(p.read_text(encoding="utf-8"))) return JSONResponse({"error": "manifest not found"}, status_code=404) @app.get("/sw.js") def serve_sw(): p = Path("static/sw.js") if p.exists(): return PlainTextResponse(p.read_text(encoding="utf-8"), media_type="application/javascript") return PlainTextResponse("", status_code=404) @app.get("/data/initial/global.json") def serve_initial_global(): return JSONResponse(cached_payload(("initial_global", _data_generation), lambda: initial_payload_global or build_initial_payload(None))) @app.get("/data/initial/repos/{repo_name}.json") def serve_initial_repo(repo_name: str): full_repo = f"VoiceOfML/{repo_name}" payload = initial_payload_by_repo.get(full_repo) if not payload: return JSONResponse({"error": f"仓库 {full_repo} 不存在"}, status_code=404) return JSONResponse(cached_payload(("initial_repo", _data_generation, full_repo), lambda: payload)) @app.get("/data/initial/manifest.json") def serve_initial_manifest(): def build(): urls = ["/data/initial/global.json"] for repo in sorted(initial_payload_by_repo): urls.append(f"/data/initial/repos/{quote(repo.split('/')[-1], safe='')}.json") return {"urls": urls} return JSONResponse(cached_payload(("initial_manifest", _data_generation), build)) def read_sidebar_json(path: Path): data = load_sidebar_payload(path) if data is None: return JSONResponse({"error": "sidebar data not found"}, status_code=404) return JSONResponse( cached_payload(("sidebar_file", _data_generation, str(path)), lambda: data), headers=METADATA_CACHE_HEADERS, ) @app.get("/data/sidebar/global.json") def serve_sidebar_global(): return read_sidebar_json(SIDEBAR_DATA_PATH / "global.json") @app.get("/data/sidebar/repos/{repo_name}.json") def serve_sidebar_repo(repo_name: str): full_repo = f"VoiceOfML/{repo_name}" if full_repo not in repo_counts: return JSONResponse({"error": f"仓库 {full_repo} 不存在"}, status_code=404) return read_sidebar_json(SIDEBAR_DATA_PATH / "repos" / f"{quote(repo_name, safe='')}.json") @app.get("/data/sidebar/manifest.json") def serve_sidebar_manifest(): return read_sidebar_json(SIDEBAR_DATA_PATH / "manifest.json") seo_catalog_cache: CatalogResult | None = None @app.get("/robots.txt") def serve_robots(): # The indexable catalog lives on Pages. Do not advertise a conflicting HF sitemap. return PlainTextResponse("User-agent: *\nAllow: /\n", headers={"Cache-Control": "public, max-age=3600"}) @app.get("/catalog") def redirect_catalog(): return RedirectResponse("/catalog/", status_code=308) @app.get("/catalog/") @app.get("/catalog/{catalog_path:path}") def serve_seo_catalog(catalog_path: str = ""): if seo_catalog_cache is None: return PlainTextResponse("Catalog temporarily unavailable", status_code=503, headers={"Cache-Control": "no-store", "X-Robots-Tag": "noindex"}) headers = {"X-Robots-Tag": "noindex, follow"} if catalog_path == "publication.json": return JSONResponse(seo_catalog_cache["manifest"], headers={**headers, "Cache-Control": "no-store"}) key = "catalog/" + catalog_path.rstrip("/") key = key.rstrip("/") + "/index.html" body = seo_catalog_cache["files"].get(key) if body is None: return PlainTextResponse("Catalog page not found", status_code=404, headers=headers) if catalog_path and not catalog_path.endswith("/"): return RedirectResponse("/catalog/" + quote(catalog_path, safe="/") + "/", status_code=308) return HTMLResponse(body, headers={**headers, "Cache-Control": "public, max-age=300"}) @app.get("/") async def serve_root(): html = injected_html_cache.get(None) if html is not None: return HTMLResponse(html) index_path = Path("static/index.html") if index_path.exists(): return HTMLResponse(inject_initial_payload(index_path.read_text(encoding="utf-8"), None)) return PlainTextResponse("Frontend shell unavailable", status_code=503) @app.get("/{rest_of_path:path}") async def serve_spa(rest_of_path: str): normalized = rest_of_path.strip("/") if normalized == "api" or normalized.startswith("api/"): return JSONResponse({"detail": "Not Found"}, status_code=404) index_path = Path("static/index.html") if index_path.exists(): repo_short = normalized.split("/")[0] if normalized else None if repo_short and f"VoiceOfML/{repo_short}" not in repo_counts: return PlainTextResponse("Repository not found", status_code=404) cache_key = f"VoiceOfML/{repo_short}" if repo_short else None html = injected_html_cache.get(cache_key) if html is not None: return HTMLResponse(html) return 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: requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_key[1]) if requested is None: return None start, end = (int(value) for value in requested.groups()) if start > end or end - start + 1 > READER_RANGE_CACHE_MAX_ITEM_BYTES: return None cache = app.state.reader_range_cache now = time.monotonic() for key in reversed(list(cache)): cached_at, payload, headers = cache[key] if now - cached_at >= READER_RANGE_CACHE_TTL_SECONDS: cache.pop(key) app.state.reader_range_cache_bytes -= len(payload) continue if key[0] != range_key[0] or key[2:] != range_key[2:]: continue match = re.fullmatch(r"bytes ([0-9]+)-([0-9]+)/([0-9]+)", headers.get("Content-Range", "")) if match is None: continue cached_start, cached_end, total = (int(value) for value in match.groups()) final_end = min(end, total - 1) if cached_start <= start <= final_end <= cached_end and len(payload) == cached_end - cached_start + 1: cache.move_to_end(key) body = payload[start - cached_start:final_end - cached_start + 1] return body, {**headers, "Content-Range": f"bytes {start}-{final_end}/{total}", "Content-Length": str(len(body))} return None async def shutdown_reader_range_flights() -> None: owners: set[SharedRangeFlight] = getattr(app.state, "reader_range_flight_owners", set()) await asyncio.gather(*(flight.close() for flight in list(owners)), return_exceptions=True) owners.clear() getattr(app.state, "reader_range_flights", {}).clear() 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_flights app.state.reader_range_flight_owners = new_owners flights: dict[RangeFlightKey, SharedRangeFlight] = app.state.reader_range_flights owners: set[SharedRangeFlight] = app.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) >= 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: 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] = flight owners.add(flight) subscription = flight.subscribe() shared_at = time.monotonic() transferred = False try: if not await asyncio.shield(flight.ready): response = flight.take_response() if response is not None: return response return await _stream_reader_document(request, target_url, _share_range=False, **options) headers = dict(flight.headers) if joined: headers["server-timing"] += f', reader_shared;dur={(time.monotonic() - shared_at) * 1000:.2f};desc="joined"' response = OwnedStreamingResponse(subscription.stream(), cleanup=subscription.release, status_code=206, headers=headers) transferred = True return response finally: if not transferred: await subscription.release()