vomebook commited on
Commit
eeb144a
·
1 Parent(s): 3cfe96e

Organize backend and search implementations by feature layers

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. backend/app.py +26 -26
  2. backend/cache_core.py +7 -30
  3. backend/data_formats.py +17 -110
  4. backend/download/application/__init__.py +1 -0
  5. backend/download/application/warming.py +42 -0
  6. backend/download/http/routes.py +1 -1
  7. backend/download_warm.py +9 -42
  8. backend/folder_contents.py +12 -84
  9. backend/folder_tree.py +9 -69
  10. backend/proxy_streams.py +11 -287
  11. backend/reader/archive/domain/content.py +1 -1
  12. backend/reader/archive/domain/validation.py +156 -0
  13. backend/reader/catalog/application/indexes.py +2 -2
  14. backend/reader/catalog/domain/__init__.py +1 -0
  15. backend/reader/catalog/domain/assets.py +154 -0
  16. backend/reader/catalog/domain/index.py +54 -0
  17. backend/reader/catalog/infrastructure/__init__.py +1 -0
  18. backend/reader/catalog/infrastructure/v3.py +161 -0
  19. backend/reader/document/application/ranges.py +1 -1
  20. backend/reader/document/domain/policy.py +1 -1
  21. backend/reader/document/domain/range_cache.py +67 -0
  22. backend/reader/document/http/transport.py +2 -2
  23. backend/reader/query/application/ocr.py +1 -1
  24. backend/reader/query/domain/ocr.py +165 -0
  25. backend/reader_archive.py +12 -156
  26. backend/reader_assets.py +11 -152
  27. backend/reader_index.py +10 -54
  28. backend/reader_ocr.py +13 -165
  29. backend/reader_range_cache.py +12 -67
  30. backend/reader_v3_catalog.py +18 -161
  31. backend/record_metadata.py +23 -185
  32. backend/runtime/application/lifecycle.py +2 -2
  33. backend/search/application/bootstrap.py +31 -0
  34. backend/search/corpus/application/preparation.py +2 -2
  35. backend/search/corpus/domain/folder_contents.py +84 -0
  36. backend/search/corpus/domain/folder_tree.py +69 -0
  37. backend/search/corpus/domain/formats.py +110 -0
  38. backend/search/corpus/domain/records.py +185 -0
  39. backend/search/corpus/domain/words.py +65 -0
  40. backend/search/corpus/infrastructure/__init__.py +1 -0
  41. backend/search/corpus/infrastructure/indexes.py +205 -0
  42. backend/search/corpus/infrastructure/selection.py +290 -0
  43. backend/search/domain/browse.py +47 -0
  44. backend/search/domain/candidates.py +72 -0
  45. backend/search/domain/filters.py +134 -0
  46. backend/search/domain/matching.py +179 -0
  47. backend/search/domain/ordering.py +2 -2
  48. backend/search/domain/term_candidates.py +129 -0
  49. backend/search/http/body_limit.py +64 -0
  50. backend/search/http/responses.py +1 -1
backend/app.py CHANGED
@@ -31,7 +31,7 @@ from fastapi.middleware.cors import CORSMiddleware
31
  from fastapi.middleware.gzip import GZipMiddleware
32
  from starlette.types import Scope
33
  from contextlib import asynccontextmanager
34
- from backend.cache_core import cached as _bounded_cache
35
  from backend.catalog.application.metadata import (
36
  CatalogMetadata, RepoSummary as RepoSummary, load_sidebar_payload as load_sidebar_payload,
37
  )
@@ -45,18 +45,18 @@ from backend.download.http.routes import (
45
  DownloadDependencies, DownloadState, download as _download, download_check as _download_check,
46
  download_with_disconnect as _download_with_disconnect,
47
  )
48
- from backend.download_warm import (warm_download_connection as _warm_download_connection,
49
  schedule_download_connection_warm as _schedule_download_connection_warm)
50
- from backend.folder_tree import build_folder_tree as _build_folder_tree
51
- from backend.folder_contents import get_folder_contents as _get_folder_contents
52
- from backend.search_bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_results
53
- from backend.search_candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidates
54
- from backend.search_browse import browse_order as _browse_order
55
- from backend.search_term_candidates import term_candidates as _search_term_candidates
56
- from backend.search_projection import public_record as _public_record, trim_results as _trim_results
57
- from backend.reader_identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE,
58
  canonical_reader_source_url as canonical_reader_source_url, reader_short_id as reader_short_id)
59
- from backend.reader_index import ReaderIndexBuild, advance_build, new_build
60
  from backend.reader.catalog.application.indexes import (
61
  IndexDependencies, IndexPublication, IndexRuntime, IndexState, ReaderIndexes,
62
  )
@@ -74,21 +74,21 @@ from backend.reader.query.http.routes import (
74
  QueryStream, reader_resolve as _query_resolve, reader_content as _query_content,
75
  reader_ocr_search as _query_ocr_search,
76
  )
77
- from backend.reader_ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text,
78
  parse_reader_ocr_book as _parse_reader_ocr_book, search_reader_ocr_pages as search_reader_ocr_pages)
79
- from backend.search_filters import (apply_filters as _apply_filters,
80
  apply_mixed_folder_filters as _apply_mixed_folder_filters,
81
  mixed_folder_index_candidates as _mixed_folder_index_candidates, score_record as _score_record)
82
- from backend.search_words import (build_vocab_by_len as _build_vocab_by_len, build_word_index as _build_word_index,
83
  matches_file_query as _matches_file_query, matches_file_token as _matches_file_token,
84
  records_digest as _records_digest, tokenize as _tokenize)
85
- from backend.search_matching import (compile_exact_matcher as compile_exact_matcher,
86
  split_exact_terms as split_exact_terms, edit_distance as edit_distance,
87
  could_be_fuzzy as could_be_fuzzy, is_fuzzy_match as is_fuzzy_match)
88
- from backend.proxy_streams import (
89
  OwnedStreamingResponse as OwnedStreamingResponse, SharedRangeFlight as SharedRangeFlight, UpstreamLease,
90
  )
91
- from backend.reader_range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,
92
  requested_range_bounds as _requested_range_bounds)
93
  from backend.reader.document.domain.policy import (
94
  RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry, RangeFlightKey as RangeFlightKey,
@@ -106,7 +106,7 @@ from backend.reader.document.application.ranges import (
106
  from backend.runtime.application.lifecycle import (
107
  LifecycleDependencies, LifecycleState, lifespan as _application_lifespan,
108
  )
109
- from backend.search_execution import SearchBusy as SearchBusy, SearchExecutor, check_search_cancelled
110
  from backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnect
111
  from backend.search.application.cached import (
112
  CacheDependencies, search_cached as _search_cached, order_key as _order_key,
@@ -131,24 +131,24 @@ from backend.search.corpus.application.preparation import (
131
  from backend.search.corpus.domain.metadata import (
132
  MetadataMaps, populate_metadata, name_order, size_order, pack_postings,
133
  )
134
- from backend.search_transport import SearchBodyLimitMiddleware
135
- from backend.search_indexes import (
136
  NGRAM_MAGIC as NGRAM_MAGIC, WORD_INDEX_MAGIC as WORD_INDEX_MAGIC,
137
  WORD_INDEX_TOKENIZER as WORD_INDEX_TOKENIZER, Posting, PostingIndex,
138
  decode_postings as decode_postings, decode_varint as decode_varint,
139
  load_ngram_index, load_word_index, resolve_postings,
140
  )
141
- from backend.reader_assets import (
142
  READER_ASSET_FILENAMES as READER_ASSET_FILENAMES, READER_BUCKET_PATH_RE, decode_reader_assets,
143
  )
144
- from backend.reader_v3_catalog import decode_in_thread, load_reading_catalog, merge_sidecar as merge_v3_sidecar
145
- from backend.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell
146
- from backend.data_formats import (
147
  decode_browser_entry as decode_browser_entry, decode_folder_browser_data as decode_folder_browser_data,
148
  decode_folder_tree_data as decode_folder_tree_data, decode_search_payload as decode_search_payload,
149
  decode_tree_node as decode_tree_node,
150
  )
151
- from backend.record_metadata import (
152
  READER_ASSET_MODES as READER_ASSET_MODES,
153
  add_reader_assets, build_browser_file_name as build_browser_file_name, build_reader_asset_key,
154
  build_record_link, build_record_path_url, build_record_relative_path,
@@ -156,7 +156,7 @@ from backend.record_metadata import (
156
  reader_asset_url as reader_asset_url, reader_extension_for_asset as reader_extension_for_asset,
157
  reader_resolved_record,
158
  )
159
- from backend.upstream_http import (
160
  ALLOWED_DOWNLOAD_HOSTS as ALLOWED_DOWNLOAD_HOSTS,
161
  ALLOWED_DOWNLOAD_HOST_SUFFIXES as ALLOWED_DOWNLOAD_HOST_SUFFIXES, MAX_REDIRECTS as MAX_REDIRECTS,
162
  READER_ASSET_PATH_RE as READER_ASSET_PATH_RE, VOICEOFML_READER_SOURCE_RE as VOICEOFML_READER_SOURCE_RE,
 
31
  from fastapi.middleware.gzip import GZipMiddleware
32
  from starlette.types import Scope
33
  from contextlib import asynccontextmanager
34
+ from backend.shared.cache.core import cached as _bounded_cache
35
  from backend.catalog.application.metadata import (
36
  CatalogMetadata, RepoSummary as RepoSummary, load_sidebar_payload as load_sidebar_payload,
37
  )
 
45
  DownloadDependencies, DownloadState, download as _download, download_check as _download_check,
46
  download_with_disconnect as _download_with_disconnect,
47
  )
48
+ from backend.download.application.warming import (warm_download_connection as _warm_download_connection,
49
  schedule_download_connection_warm as _schedule_download_connection_warm)
50
+ from backend.search.corpus.domain.folder_tree import build_folder_tree as _build_folder_tree
51
+ from backend.search.corpus.domain.folder_contents import get_folder_contents as _get_folder_contents
52
+ from backend.search.application.bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_results
53
+ from backend.search.domain.candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidates
54
+ from backend.search.domain.browse import browse_order as _browse_order
55
+ from backend.search.domain.term_candidates import term_candidates as _search_term_candidates
56
+ from backend.search.domain.projection import public_record as _public_record, trim_results as _trim_results
57
+ from backend.reader.query.domain.identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE,
58
  canonical_reader_source_url as canonical_reader_source_url, reader_short_id as reader_short_id)
59
+ from backend.reader.catalog.domain.index import ReaderIndexBuild, advance_build, new_build
60
  from backend.reader.catalog.application.indexes import (
61
  IndexDependencies, IndexPublication, IndexRuntime, IndexState, ReaderIndexes,
62
  )
 
74
  QueryStream, reader_resolve as _query_resolve, reader_content as _query_content,
75
  reader_ocr_search as _query_ocr_search,
76
  )
77
+ from backend.reader.query.domain.ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text,
78
  parse_reader_ocr_book as _parse_reader_ocr_book, search_reader_ocr_pages as search_reader_ocr_pages)
79
+ from backend.search.domain.filters import (apply_filters as _apply_filters,
80
  apply_mixed_folder_filters as _apply_mixed_folder_filters,
81
  mixed_folder_index_candidates as _mixed_folder_index_candidates, score_record as _score_record)
82
+ from backend.search.corpus.domain.words import (build_vocab_by_len as _build_vocab_by_len, build_word_index as _build_word_index,
83
  matches_file_query as _matches_file_query, matches_file_token as _matches_file_token,
84
  records_digest as _records_digest, tokenize as _tokenize)
85
+ from backend.search.domain.matching import (compile_exact_matcher as compile_exact_matcher,
86
  split_exact_terms as split_exact_terms, edit_distance as edit_distance,
87
  could_be_fuzzy as could_be_fuzzy, is_fuzzy_match as is_fuzzy_match)
88
+ from backend.shared.transport.streams import (
89
  OwnedStreamingResponse as OwnedStreamingResponse, SharedRangeFlight as SharedRangeFlight, UpstreamLease,
90
  )
91
+ from backend.reader.document.domain.range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,
92
  requested_range_bounds as _requested_range_bounds)
93
  from backend.reader.document.domain.policy import (
94
  RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry, RangeFlightKey as RangeFlightKey,
 
106
  from backend.runtime.application.lifecycle import (
107
  LifecycleDependencies, LifecycleState, lifespan as _application_lifespan,
108
  )
109
+ from backend.search.infrastructure.executor import SearchBusy as SearchBusy, SearchExecutor, check_search_cancelled
110
  from backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnect
111
  from backend.search.application.cached import (
112
  CacheDependencies, search_cached as _search_cached, order_key as _order_key,
 
131
  from backend.search.corpus.domain.metadata import (
132
  MetadataMaps, populate_metadata, name_order, size_order, pack_postings,
133
  )
134
+ from backend.search.http.body_limit import SearchBodyLimitMiddleware
135
+ from backend.search.corpus.infrastructure.indexes import (
136
  NGRAM_MAGIC as NGRAM_MAGIC, WORD_INDEX_MAGIC as WORD_INDEX_MAGIC,
137
  WORD_INDEX_TOKENIZER as WORD_INDEX_TOKENIZER, Posting, PostingIndex,
138
  decode_postings as decode_postings, decode_varint as decode_varint,
139
  load_ngram_index, load_word_index, resolve_postings,
140
  )
141
+ from backend.reader.catalog.domain.assets import (
142
  READER_ASSET_FILENAMES as READER_ASSET_FILENAMES, READER_BUCKET_PATH_RE, decode_reader_assets,
143
  )
144
+ from backend.reader.catalog.infrastructure.v3 import decode_in_thread, load_reading_catalog, merge_sidecar as merge_v3_sidecar
145
+ from backend.site.application.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell
146
+ from backend.search.corpus.domain.formats import (
147
  decode_browser_entry as decode_browser_entry, decode_folder_browser_data as decode_folder_browser_data,
148
  decode_folder_tree_data as decode_folder_tree_data, decode_search_payload as decode_search_payload,
149
  decode_tree_node as decode_tree_node,
150
  )
151
+ from backend.search.corpus.domain.records import (
152
  READER_ASSET_MODES as READER_ASSET_MODES,
153
  add_reader_assets, build_browser_file_name as build_browser_file_name, build_reader_asset_key,
154
  build_record_link, build_record_path_url, build_record_relative_path,
 
156
  reader_asset_url as reader_asset_url, reader_extension_for_asset as reader_extension_for_asset,
157
  reader_resolved_record,
158
  )
159
+ from backend.shared.transport.upstream import (
160
  ALLOWED_DOWNLOAD_HOSTS as ALLOWED_DOWNLOAD_HOSTS,
161
  ALLOWED_DOWNLOAD_HOST_SUFFIXES as ALLOWED_DOWNLOAD_HOST_SUFFIXES, MAX_REDIRECTS as MAX_REDIRECTS,
162
  READER_ASSET_PATH_RE as READER_ASSET_PATH_RE, VOICEOFML_READER_SOURCE_RE as VOICEOFML_READER_SOURCE_RE,
backend/cache_core.py CHANGED
@@ -1,31 +1,8 @@
1
- """Bounded insertion-ordered response cache shared by API and search."""
2
- from collections.abc import Callable, Hashable
3
- import json
4
- import time
5
-
6
-
7
- def cached(store: dict[Hashable, tuple[float, object] | tuple[float, object, int]], key: Hashable,
8
- builder: Callable[[], object], ttl: float, limit: int, *,
9
- max_entry_bytes: int, max_total_bytes: int) -> object:
10
- now = time.monotonic()
11
- cached = store.get(key)
12
- if cached and now - cached[0] < ttl:
13
- store[key] = store.pop(key)
14
- return cached[1]
15
- value = builder()
16
- store.pop(key, None)
17
- for old_key, entry in list(store.items()):
18
- if now - entry[0] >= ttl:
19
- del store[old_key]
20
- size = (len(value) if isinstance(value, bytes) else len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))) + len(str(key).encode("utf-8"))
21
- if size > max_entry_bytes:
22
- return value
23
- total = sum(entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8")) for entry in store.values())
24
- while store and (len(store) >= limit or total + size > max_total_bytes):
25
- oldest_key = next(iter(store))
26
- entry = store.pop(oldest_key)
27
- total -= entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8"))
28
- if size <= max_total_bytes:
29
- store[key] = (now, value, size)
30
- return value
31
 
 
 
1
+ """Compatibility import for backend.shared.cache.core."""
2
+ import sys
3
+ from backend.shared.cache import core as _implementation
4
+ from backend.shared.cache.core import (
5
+ cached as cached,
6
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ sys.modules[__name__] = _implementation
backend/data_formats.py CHANGED
@@ -1,110 +1,17 @@
1
- """Decode the current compact corpus and directory formats without runtime state."""
2
-
3
- from typing import TypedDict, cast
4
-
5
-
6
- class CompactCorpus(TypedDict, total=False):
7
- rp: list[str]
8
- fd: list[list[str]]
9
- rc: list[object]
10
-
11
-
12
- class CompactTreeNode(TypedDict, total=False):
13
- n: str
14
- c: int
15
- df: bool
16
- ch: list["CompactTreeNode"]
17
-
18
-
19
- class CompactFolder(TypedDict, total=False):
20
- n: str
21
- c: int
22
-
23
-
24
- class CompactFile(TypedDict, total=False):
25
- n: str
26
- e: str
27
- t: bool
28
- s: int | str
29
-
30
-
31
- class CompactBrowserEntry(TypedDict, total=False):
32
- d: list[CompactFolder]
33
- f: list[CompactFile]
34
-
35
-
36
- def decode_search_payload(data: object) -> list[dict[str, object]]:
37
- if not isinstance(data, dict):
38
- return []
39
- compact = cast(CompactCorpus, data)
40
- repos = compact.get("rp", []) or []
41
- folders = compact.get("fd", []) or []
42
- records: list[dict[str, object]] = []
43
- for raw_item in compact.get("rc", []) or []:
44
- if not isinstance(raw_item, list):
45
- continue
46
- item = cast(list[object], raw_item)
47
- if len(item) < 6:
48
- continue
49
- repo = repos[item[0]] if isinstance(item[0], int) and 0 <= item[0] < len(repos) else ""
50
- folder = folders[item[3]] if isinstance(item[3], int) and 0 <= item[3] < len(folders) else []
51
- records.append({
52
- "Repo": repo,
53
- "File": item[1],
54
- "Extension": item[2],
55
- "Folder": folder,
56
- "Size": item[4],
57
- "HasTxt": bool(item[5]),
58
- })
59
- return records
60
-
61
-
62
- def decode_tree_node(node: CompactTreeNode, parent_path: str = "", is_root: bool = False) -> dict[str, object]:
63
- name = node.get("n", "")
64
- path = "" if is_root else (f"{parent_path}/{name}" if parent_path else name)
65
- children = [decode_tree_node(child, path, False) for child in node.get("ch", [])]
66
- decoded: dict[str, object] = {
67
- "name": name,
68
- "path": path,
69
- "count": node.get("c", 0),
70
- "hasDirectFiles": node.get("df", False),
71
- "hasChildren": len(children) > 0,
72
- "showSelfToggle": bool(path and node.get("df", False) and len(children) > 0),
73
- "children": children,
74
- }
75
- if is_root:
76
- decoded["isRoot"] = True
77
- return decoded
78
-
79
-
80
- def decode_folder_tree_data(data: dict[str, list[CompactTreeNode]] | None) -> dict[str, list[dict[str, object]]]:
81
- return {repo: [decode_tree_node(node, "", True) for node in nodes]
82
- for repo, nodes in (data or {}).items()}
83
-
84
-
85
- def decode_browser_entry(entry: CompactBrowserEntry, current_path: str = "") -> dict[str, object]:
86
- return {
87
- "folders": [
88
- {
89
- "name": item.get("n", ""),
90
- "path": f"{current_path}/{item.get('n', '')}" if current_path else item.get("n", ""),
91
- "count": item.get("c", 0),
92
- }
93
- for item in entry.get("d", [])
94
- ],
95
- "files": [
96
- {
97
- "name": item.get("n", ""),
98
- "ext": item.get("e", ""),
99
- "hasTxt": item.get("t", False),
100
- "size": item.get("s", ""),
101
- }
102
- for item in entry.get("f", [])
103
- ],
104
- "current_path": current_path,
105
- }
106
-
107
-
108
- def decode_folder_browser_data(data: dict[str, dict[str, CompactBrowserEntry]] | None) -> dict[str, dict[str, dict[str, object]]]:
109
- return {repo: {path: decode_browser_entry(entry, path) for path, entry in (browser or {}).items()}
110
- for repo, browser in (data or {}).items()}
 
1
+ """Compatibility import for backend.search.corpus.domain.formats."""
2
+ import sys
3
+ from backend.search.corpus.domain import formats as _implementation
4
+ from backend.search.corpus.domain.formats import (
5
+ CompactBrowserEntry as CompactBrowserEntry,
6
+ CompactCorpus as CompactCorpus,
7
+ CompactFile as CompactFile,
8
+ CompactFolder as CompactFolder,
9
+ CompactTreeNode as CompactTreeNode,
10
+ decode_browser_entry as decode_browser_entry,
11
+ decode_folder_browser_data as decode_folder_browser_data,
12
+ decode_folder_tree_data as decode_folder_tree_data,
13
+ decode_search_payload as decode_search_payload,
14
+ decode_tree_node as decode_tree_node,
15
+ )
16
+
17
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/download/application/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """download application package."""
backend/download/application/warming.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded, owned speculative connection warmup for the download pool."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ from collections.abc import Callable, Coroutine
6
+ from typing import Any
7
+ from fastapi import FastAPI
8
+ import aiohttp
9
+
10
+
11
+ async def warm_download_connection(app: FastAPI):
12
+ # Use the download pool, but never queue speculative work behind real transfers.
13
+ semaphore = app.state.upstream_semaphore
14
+ if semaphore.locked():
15
+ return
16
+ try:
17
+ async with semaphore:
18
+ async with app.state.http_session.head(
19
+ "https://huggingface.co/robots.txt",
20
+ allow_redirects=False,
21
+ timeout=aiohttp.ClientTimeout(total=4, connect=3, sock_read=3),
22
+ ):
23
+ pass
24
+ except (aiohttp.ClientError, asyncio.TimeoutError):
25
+ # A failed warmup must not affect ping or the later download attempt.
26
+ pass
27
+
28
+
29
+ def schedule_download_connection_warm(app: FastAPI, *, now: Callable[[], float],
30
+ interval: Callable[[], int],
31
+ warm: Callable[[FastAPI], Coroutine[Any, Any, None]]) -> None:
32
+ state = app.state
33
+ if not getattr(state, "download_warm_enabled", False):
34
+ return
35
+ task = state.download_warm_task
36
+ current_time = now()
37
+ if task is not None and not task.done():
38
+ return
39
+ if current_time - state.download_warm_at < interval():
40
+ return
41
+ state.download_warm_at = current_time
42
+ state.download_warm_task = asyncio.create_task(warm(app))
backend/download/http/routes.py CHANGED
@@ -10,7 +10,7 @@ import aiohttp
10
  from fastapi import Request
11
  from fastapi.responses import JSONResponse, Response
12
 
13
- from backend.proxy_streams import OwnedStreamingResponse, UpstreamLease
14
 
15
 
16
  class DownloadState(Protocol):
 
10
  from fastapi import Request
11
  from fastapi.responses import JSONResponse, Response
12
 
13
+ from backend.shared.transport.streams import OwnedStreamingResponse, UpstreamLease
14
 
15
 
16
  class DownloadState(Protocol):
backend/download_warm.py CHANGED
@@ -1,42 +1,9 @@
1
- """Bounded, owned speculative connection warmup for the download pool."""
2
- from __future__ import annotations
3
-
4
- import asyncio
5
- from collections.abc import Callable, Coroutine
6
- from typing import Any
7
- from fastapi import FastAPI
8
- import aiohttp
9
-
10
-
11
- async def warm_download_connection(app: FastAPI):
12
- # Use the download pool, but never queue speculative work behind real transfers.
13
- semaphore = app.state.upstream_semaphore
14
- if semaphore.locked():
15
- return
16
- try:
17
- async with semaphore:
18
- async with app.state.http_session.head(
19
- "https://huggingface.co/robots.txt",
20
- allow_redirects=False,
21
- timeout=aiohttp.ClientTimeout(total=4, connect=3, sock_read=3),
22
- ):
23
- pass
24
- except (aiohttp.ClientError, asyncio.TimeoutError):
25
- # A failed warmup must not affect ping or the later download attempt.
26
- pass
27
-
28
-
29
- def schedule_download_connection_warm(app: FastAPI, *, now: Callable[[], float],
30
- interval: Callable[[], int],
31
- warm: Callable[[FastAPI], Coroutine[Any, Any, None]]) -> None:
32
- state = app.state
33
- if not getattr(state, "download_warm_enabled", False):
34
- return
35
- task = state.download_warm_task
36
- current_time = now()
37
- if task is not None and not task.done():
38
- return
39
- if current_time - state.download_warm_at < interval():
40
- return
41
- state.download_warm_at = current_time
42
- state.download_warm_task = asyncio.create_task(warm(app))
 
1
+ """Compatibility import for backend.download.application.warming."""
2
+ import sys
3
+ from backend.download.application import warming as _implementation
4
+ from backend.download.application.warming import (
5
+ schedule_download_connection_warm as schedule_download_connection_warm,
6
+ warm_download_connection as warm_download_connection,
7
+ )
8
+
9
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/folder_contents.py CHANGED
@@ -1,84 +1,12 @@
1
- """Directory browser lookup against a caller-owned search index snapshot."""
2
- from __future__ import annotations
3
-
4
- from collections.abc import Callable, Mapping, Sequence
5
- from typing import cast
6
-
7
- SearchRecord = dict[str, object]
8
- BrowserEntries = Mapping[str, Mapping[str, SearchRecord]]
9
- FolderIndex = Mapping[str, Mapping[str, Sequence[int]]]
10
- RepoIndices = Mapping[str, Sequence[int]]
11
-
12
-
13
- def get_folder_contents(repo: str, path: str, *,
14
- get_browser: Callable[[], BrowserEntries],
15
- get_folder_index: Callable[[], FolderIndex],
16
- get_repo_indices: Callable[[], RepoIndices],
17
- get_records: Callable[[], Sequence[SearchRecord]],
18
- enrich_browser_entry: Callable[[str, str, SearchRecord], SearchRecord],
19
- build_record_link: Callable[[SearchRecord], str],
20
- build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord:
21
- """Prefer precomputed entries, otherwise count and project the indexed subtree."""
22
- if repo in get_browser():
23
- repo_browser = get_browser().get(repo, {}) or {}
24
- if path in repo_browser:
25
- return enrich_browser_entry(repo, path, repo_browser[path])
26
- if path == "" and "" in repo_browser:
27
- return enrich_browser_entry(repo, path, repo_browser[""])
28
- return _from_index(repo, path, get_folder_index, get_repo_indices, get_records,
29
- build_record_link, build_record_path_url)
30
-
31
-
32
- def _from_index(repo: str, path: str, get_folder_index: Callable[[], FolderIndex],
33
- get_repo_indices: Callable[[], RepoIndices], get_records: Callable[[], Sequence[SearchRecord]],
34
- build_record_link: Callable[[SearchRecord], str],
35
- build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord:
36
- path_parts = [p for p in path.strip("/").split("/") if p]
37
- path_depth = len(path_parts)
38
- repo_folders = get_folder_index().get(repo)
39
- candidate_indices = (repo_folders.get("/".join(path_parts), [])
40
- if repo_folders is not None else get_repo_indices().get(repo, []))
41
-
42
- def is_under(rec_folders: list[str], prefix: list[str]) -> bool:
43
- return rec_folders[:len(prefix)] == prefix
44
- matching = [get_records()[i] for i in candidate_indices
45
- if is_under(cast(list[str], get_records()[i].get("Folder", []) or []), path_parts)]
46
- result_folders = _subfolder_results(matching, path_parts, path_depth)
47
- direct_files = _direct_file_results(matching, path_depth, build_record_link, build_record_path_url)
48
- return {"folders": result_folders, "files": direct_files, "current_path": path}
49
-
50
-
51
- def _subfolder_results(matching: Sequence[SearchRecord], path_parts: list[str],
52
- path_depth: int) -> list[SearchRecord]:
53
- subfolder_names: set[str] = set()
54
- subfolder_counts: dict[str, int] = {}
55
- for rec in matching:
56
- folders = cast(list[str], rec.get("Folder", []) or [])
57
- if len(folders) > path_depth:
58
- name = folders[path_depth]
59
- subfolder_names.add(name)
60
- subfolder_counts[name] = subfolder_counts.get(name, 0) + 1
61
- result_folders: list[SearchRecord] = []
62
- for fname in sorted(subfolder_names):
63
- full_path = "/".join(path_parts + [fname]) if path_parts else fname
64
- result_folders.append({"name": fname, "path": full_path, "count": subfolder_counts.get(fname, 0)})
65
- return result_folders
66
-
67
-
68
- def _direct_file_results(matching: Sequence[SearchRecord], path_depth: int,
69
- build_record_link: Callable[[SearchRecord], str],
70
- build_record_path_url: Callable[[SearchRecord], str]) -> list[SearchRecord]:
71
- direct_files: list[SearchRecord] = []
72
- for rec in matching:
73
- folders = cast(list[str], rec.get("Folder", []) or [])
74
- if len(folders) == path_depth:
75
- direct_files.append({
76
- "name": rec.get("File", ""),
77
- "ext": rec.get("Extension", ""),
78
- "link": rec.get("Link") or build_record_link(rec),
79
- "path": rec.get("Path") or build_record_path_url(rec),
80
- "hasTxt": rec.get("HasTxt", False),
81
- "size": rec.get("Size", ""),
82
- })
83
- direct_files.sort(key=lambda f: cast(str, f["name"]))
84
- return direct_files
 
1
+ """Compatibility import for backend.search.corpus.domain.folder_contents."""
2
+ import sys
3
+ from backend.search.corpus.domain import folder_contents as _implementation
4
+ from backend.search.corpus.domain.folder_contents import (
5
+ BrowserEntries as BrowserEntries,
6
+ FolderIndex as FolderIndex,
7
+ RepoIndices as RepoIndices,
8
+ SearchRecord as SearchRecord,
9
+ get_folder_contents as get_folder_contents,
10
+ )
11
+
12
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/folder_tree.py CHANGED
@@ -1,69 +1,9 @@
1
- """Build search filter trees from a caller-owned index snapshot."""
2
- from __future__ import annotations
3
-
4
- from collections.abc import Mapping, Sequence
5
- from typing import NotRequired, TypedDict, cast
6
-
7
-
8
- class FolderTreeNode(TypedDict):
9
- name: str
10
- path: str
11
- children: list[FolderTreeNode]
12
- count: int
13
- hasDirectFiles: bool
14
- hasChildren: bool
15
- showSelfToggle: bool
16
- isRoot: NotRequired[bool]
17
-
18
-
19
- def build_folder_tree(repo: str, folder_index: Mapping[str, Mapping[str, Sequence[int]]],
20
- repo_records_map: Mapping[str, Sequence[int]],
21
- records: Sequence[dict[str, object]]) -> list[FolderTreeNode]:
22
- """Preserve corpus counts, stable child order and direct-file toggles."""
23
- if repo not in folder_index:
24
- return []
25
- repo_name_short = repo.split("/")[-1]
26
- tree_root: FolderTreeNode = {
27
- "name": repo_name_short,
28
- "path": "",
29
- "children": [],
30
- "count": 0,
31
- "hasDirectFiles": False,
32
- "hasChildren": False,
33
- "showSelfToggle": False,
34
- "isRoot": True,
35
- }
36
- node_map: dict[str, FolderTreeNode] = {"": tree_root}
37
- for path, idx_list in folder_index[repo].items():
38
- if path == "":
39
- tree_root["count"] = len(idx_list)
40
- continue
41
- parts = path.split("/")
42
- for depth in range(1, len(parts) + 1):
43
- key = "/".join(parts[:depth])
44
- if key not in node_map:
45
- parent_key = "/".join(parts[:depth - 1]) if depth > 1 else ""
46
- parent = node_map[parent_key]
47
- node: FolderTreeNode = {
48
- "name": parts[depth - 1],
49
- "path": key,
50
- "children": [],
51
- "count": 0,
52
- "hasDirectFiles": False,
53
- "hasChildren": False,
54
- "showSelfToggle": False,
55
- }
56
- node_map[key] = node
57
- parent["children"].append(node)
58
- node_map[path]["count"] = len(idx_list)
59
- direct_file_dirs: set[str] = set()
60
- for idx in repo_records_map.get(repo, []):
61
- rec = records[idx]
62
- folders = cast(list[str], rec.get("Folder", []) or [])
63
- direct_file_dirs.add("/".join(folders))
64
- for path_key, node in node_map.items():
65
- node["hasDirectFiles"] = path_key in direct_file_dirs
66
- node["children"].sort(key=lambda child: child["name"])
67
- node["hasChildren"] = len(node["children"]) > 0
68
- node["showSelfToggle"] = bool(path_key and node["hasDirectFiles"] and node["hasChildren"])
69
- return [tree_root]
 
1
+ """Compatibility import for backend.search.corpus.domain.folder_tree."""
2
+ import sys
3
+ from backend.search.corpus.domain import folder_tree as _implementation
4
+ from backend.search.corpus.domain.folder_tree import (
5
+ FolderTreeNode as FolderTreeNode,
6
+ build_folder_tree as build_folder_tree,
7
+ )
8
+
9
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/proxy_streams.py CHANGED
@@ -1,287 +1,11 @@
1
- """Own upstream responses across the route-to-ASGI streaming handoff."""
2
- import asyncio
3
- import inspect
4
- from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
5
- from types import TracebackType
6
- import aiohttp
7
- from fastapi.responses import StreamingResponse
8
- from starlette.background import BackgroundTask
9
- from starlette.responses import ContentStream, Response
10
- from starlette.types import Receive, Scope, Send
11
-
12
-
13
- class OwnedStreamingResponse(StreamingResponse):
14
- def __init__(self, content: ContentStream, *, cleanup: Callable[[], Awaitable[None] | None],
15
- status_code: int = 200, headers: Mapping[str, str] | None = None,
16
- media_type: str | None = None, background: BackgroundTask | None = None) -> None:
17
- super().__init__(content, status_code=status_code, headers=headers, media_type=media_type, background=background)
18
- self.cleanup = cleanup
19
-
20
- async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
21
- try:
22
- await super().__call__(scope, receive, send)
23
- finally:
24
- # A disconnect may happen before the generator's first iteration.
25
- try:
26
- result = self.cleanup()
27
- if inspect.isawaitable(result):
28
- await result
29
- finally:
30
- close = getattr(self.body_iterator, "aclose", None)
31
- if close is not None:
32
- await close()
33
-
34
-
35
- class UpstreamLease:
36
- """Own an upstream response and an optional, already-acquired pool slot."""
37
-
38
- def __init__(self, semaphore: asyncio.Semaphore | None = None) -> None:
39
- self.response: aiohttp.ClientResponse | None = None
40
- self.semaphore = semaphore
41
- self.closed = False
42
- self.transferred = False
43
-
44
- def close(self) -> None:
45
- if self.closed:
46
- return
47
- try:
48
- if self.response is not None:
49
- self.response.release()
50
- self.response = None
51
- self.closed = True
52
- finally:
53
- if self.semaphore is not None:
54
- self.semaphore.release()
55
- self.semaphore = None
56
-
57
- def __enter__(self) -> "UpstreamLease":
58
- return self
59
-
60
- def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None,
61
- traceback: TracebackType | None) -> None:
62
- if not self.transferred:
63
- self.close()
64
-
65
- async def chunks(self, error_label: str) -> AsyncIterator[bytes]:
66
- try:
67
- response = self.response
68
- if response is None:
69
- raise RuntimeError("upstream response unavailable")
70
- async for chunk in response.content.iter_chunked(65536):
71
- yield chunk
72
- except Exception as exc:
73
- print(f"{error_label}: {exc}")
74
- raise
75
- finally:
76
- self.close()
77
-
78
- def streaming_response(self, content: ContentStream, *, status_code: int = 200,
79
- headers: Mapping[str, str] | None = None, media_type: str | None = None,
80
- background: BackgroundTask | None = None) -> OwnedStreamingResponse:
81
- response = OwnedStreamingResponse(content, cleanup=self.close, status_code=status_code,
82
- headers=headers, media_type=media_type, background=background)
83
- self.transferred = True
84
- return response
85
-
86
-
87
- class SharedRangeFlight:
88
- """Stream one bounded response to independently owned subscribers."""
89
-
90
- def __init__(self, create: Callable[[], Awaitable[Response]], limit: int,
91
- finished: Callable[["SharedRangeFlight"], None]) -> None:
92
- self.create = create
93
- self.limit = limit
94
- self.finished = finished
95
- self.ready: asyncio.Future[bool] = asyncio.get_running_loop().create_future()
96
- self.ready.add_done_callback(lambda future: None if future.cancelled() else future.exception())
97
- self.changed = asyncio.Event()
98
- self.started = asyncio.Event()
99
- self.task: asyncio.Task[None] | None = None
100
- self.response: Response | None = None
101
- self.headers: dict[str, str] = {}
102
- self.chunks: list[bytes | memoryview] = []
103
- self.size = 0
104
- self.subscribers = 0
105
- self.shared = False
106
- self.done = False
107
- self.error: BaseException | None = None
108
- self.close_error: BaseException | None = None
109
- self._response_cleaned = False
110
- self._iterator_closed = False
111
-
112
- def subscribe(self) -> "RangeSubscription":
113
- self.subscribers += 1
114
- if self.task is None:
115
- self.task = asyncio.create_task(self._run())
116
- self.task.add_done_callback(self._settled)
117
- return RangeSubscription(self)
118
-
119
- def _settled(self, task: asyncio.Task[None]) -> None:
120
- error = asyncio.CancelledError() if task.cancelled() else task.exception()
121
- if error is not None and self.error is None:
122
- self.error = error
123
- if not self.done:
124
- self.done = True
125
- if not self.ready.done():
126
- self.ready.set_exception(self.error or RuntimeError("range flight stopped"))
127
- self.changed.set()
128
- if not self.subscribers:
129
- self.finished(self)
130
-
131
- async def _release_response(self) -> None:
132
- response = self.response
133
- if response is None:
134
- return
135
- errors: list[BaseException] = []
136
- cleanup = getattr(response, "cleanup", None)
137
- try:
138
- if not self._response_cleaned:
139
- if cleanup:
140
- result = cleanup()
141
- if inspect.isawaitable(result):
142
- await result
143
- self._response_cleaned = True
144
- except BaseException as exc:
145
- errors.append(exc)
146
- iterator = getattr(response, "body_iterator", None)
147
- try:
148
- if not self._iterator_closed:
149
- if iterator is not None:
150
- await iterator.aclose()
151
- self._iterator_closed = True
152
- except BaseException as exc:
153
- errors.append(exc)
154
- self.close_error = (errors[0] if len(errors) == 1 else
155
- BaseExceptionGroup("Reader range response close failures", errors) if errors else None)
156
- if self.close_error is not None:
157
- raise self.close_error
158
- self.response = None
159
-
160
- async def _run(self) -> None:
161
- try:
162
- self.response = await self.create()
163
- try:
164
- length = int(self.response.headers.get("content-length", ""))
165
- except (TypeError, ValueError):
166
- length = -1
167
- if self.response.status_code != 206 or not 0 <= length <= self.limit:
168
- self.ready.set_result(False)
169
- return
170
- self.shared = True
171
- self.headers = dict(self.response.headers)
172
- self.ready.set_result(True)
173
- # A transport may suppress cancellation and still return headers.
174
- # If all waiters left, no one can start this producer; release it.
175
- if not self.subscribers:
176
- return
177
- await self.started.wait()
178
- iterator = getattr(self.response, "body_iterator", None)
179
- if iterator is None:
180
- body = self.response.body
181
- if len(body) > length:
182
- raise ValueError("shared range body exceeds declared length")
183
- self.chunks.append(body)
184
- self.size = len(body)
185
- self.changed.set()
186
- else:
187
- async for chunk in iterator:
188
- if self.size + len(chunk) > length:
189
- raise ValueError("shared range body exceeds declared length")
190
- self.chunks.append(chunk)
191
- self.size += len(chunk)
192
- self.changed.set()
193
- if self.size < length:
194
- raise ValueError("shared range body shorter than declared length")
195
- except BaseException as error:
196
- self.error = error
197
- if not self.ready.done():
198
- self.ready.set_exception(error)
199
- finally:
200
- try:
201
- if self.shared or self.error or not self.subscribers:
202
- await self._release_response()
203
- finally:
204
- self.done = True
205
- self.changed.set()
206
- if not self.subscribers:
207
- self.finished(self)
208
-
209
- def take_response(self) -> Response | None:
210
- response, self.response = self.response, None
211
- return response
212
-
213
- def unsubscribe(self) -> None:
214
- self.subscribers -= 1
215
- if self.subscribers:
216
- return
217
- if not self.done:
218
- if self.task is not None:
219
- self.task.cancel()
220
- self.finished(self)
221
- elif self.response is not None:
222
- # An unclaimed declined response still owns its upstream lease.
223
- self.task = asyncio.create_task(self._close_declined())
224
- self.task.add_done_callback(self._settled)
225
- else:
226
- self.finished(self)
227
-
228
- async def _close_declined(self) -> None:
229
- try:
230
- await self._release_response()
231
- finally:
232
- self.finished(self)
233
-
234
- async def close(self) -> None:
235
- previous_error = self.close_error
236
- if self.task and not self.task.done():
237
- self.task.cancel()
238
- if self.task:
239
- await asyncio.gather(self.task, return_exceptions=True)
240
- if self.close_error is not None and self.close_error is not previous_error:
241
- raise self.close_error
242
- await self._release_response()
243
- self.finished(self)
244
-
245
-
246
- class RangeSubscription:
247
- def __init__(self, flight: SharedRangeFlight) -> None:
248
- self.flight: SharedRangeFlight | None = flight
249
- self.closed = False
250
-
251
- def close(self) -> None:
252
- if not self.closed:
253
- self.closed = True
254
- if self.flight is not None:
255
- self.flight.unsubscribe()
256
-
257
- async def release(self) -> None:
258
- flight = self.flight
259
- if flight is None:
260
- return
261
- self.close()
262
- if not flight.subscribers and flight.task:
263
- await asyncio.gather(flight.task, return_exceptions=True)
264
- self.flight = None
265
-
266
- async def stream(self) -> AsyncIterator[bytes | memoryview]:
267
- cursor = 0
268
- flight = self.flight
269
- if flight is None:
270
- return
271
- flight.started.set()
272
- try:
273
- while not self.closed:
274
- while cursor < len(flight.chunks):
275
- chunk = flight.chunks[cursor]
276
- cursor += 1
277
- yield chunk
278
- if flight.done:
279
- if flight.error:
280
- raise flight.error
281
- return
282
- flight.changed.clear()
283
- if cursor < len(flight.chunks) or flight.done:
284
- continue
285
- await flight.changed.wait()
286
- finally:
287
- await self.release()
 
1
+ """Compatibility import for backend.shared.transport.streams."""
2
+ import sys
3
+ from backend.shared.transport import streams as _implementation
4
+ from backend.shared.transport.streams import (
5
+ OwnedStreamingResponse as OwnedStreamingResponse,
6
+ RangeSubscription as RangeSubscription,
7
+ SharedRangeFlight as SharedRangeFlight,
8
+ UpstreamLease as UpstreamLease,
9
+ )
10
+
11
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/reader/archive/domain/content.py CHANGED
@@ -6,7 +6,7 @@ from urllib.parse import unquote, urlparse
6
  import zipfile
7
  import zlib
8
 
9
- from backend.reader_archive import (
10
  ReaderArchiveInvalidError as ReaderArchiveInvalidError,
11
  ReaderArchiveLimitError as ReaderArchiveLimitError,
12
  ReaderArchiveLimits as ReaderArchiveLimits,
 
6
  import zipfile
7
  import zlib
8
 
9
+ from backend.reader.archive.domain.validation import (
10
  ReaderArchiveInvalidError as ReaderArchiveInvalidError,
11
  ReaderArchiveLimitError as ReaderArchiveLimitError,
12
  ReaderArchiveLimits as ReaderArchiveLimits,
backend/reader/archive/domain/validation.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded ZIP validation for reader archives with caller-owned limits."""
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ import re
6
+ import zipfile
7
+ from typing import Protocol, cast
8
+
9
+
10
+ class ReaderArchiveLimits(Protocol):
11
+ """Limits are read on every use so callers may replace them at any time."""
12
+
13
+ @property
14
+ def READER_RESOURCE_MAX_ARCHIVE_BYTES(self) -> int: ...
15
+ @property
16
+ def READER_ARCHIVE_MAX_ENTRIES(self) -> int: ...
17
+ @property
18
+ def READER_ARCHIVE_MAX_EXPANDED_BYTES(self) -> int: ...
19
+ @property
20
+ def READER_ARCHIVE_MAX_COMPRESSION_RATIO(self) -> int: ...
21
+ @property
22
+ def READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES(self) -> int: ...
23
+ @property
24
+ def READER_ARCHIVE_MAX_METADATA_BYTES(self) -> int: ...
25
+ @property
26
+ def READER_ARCHIVE_MEMBER_RE(self) -> re.Pattern[str]: ...
27
+
28
+
29
+ class ReaderArchiveLimitError(ValueError):
30
+ pass
31
+
32
+
33
+ class ReaderArchiveInvalidError(ValueError):
34
+ pass
35
+
36
+
37
+ class ReaderDocumentLimitError(ValueError):
38
+ pass
39
+
40
+
41
+ def _plain_int(value: object) -> bool:
42
+ return isinstance(value, int) and not isinstance(value, bool)
43
+
44
+
45
+ def _is_bytes(value: object) -> bool:
46
+ return isinstance(value, bytes)
47
+
48
+
49
+ def _is_str(value: object) -> bool:
50
+ return isinstance(value, str)
51
+
52
+
53
+ def validate_reader_archive(archive: bytes, limits: ReaderArchiveLimits) -> None:
54
+ if len(archive) > limits.READER_RESOURCE_MAX_ARCHIVE_BYTES:
55
+ raise ReaderArchiveLimitError("阅读文件过大")
56
+ try:
57
+ # Use the stdlib's EOCD/ZIP64 parser before ZipFile allocates its directory.
58
+ # These bounded EOCD fields are stdlib internals missing from typeshed.
59
+ zip_internal = cast(object, zipfile)
60
+ end_record = getattr(zip_internal, "_EndRecData")(io.BytesIO(archive))
61
+ if not end_record:
62
+ raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP")
63
+ central_directory_size = end_record[getattr(zip_internal, "_ECD_SIZE")]
64
+ directory_offset = end_record[getattr(zip_internal, "_ECD_OFFSET")]
65
+ entry_count = end_record[getattr(zip_internal, "_ECD_ENTRIES_TOTAL")]
66
+ if (end_record[getattr(zip_internal, "_ECD_DISK_NUMBER")] != 0
67
+ or end_record[getattr(zip_internal, "_ECD_DISK_START")] != 0
68
+ or end_record[getattr(zip_internal, "_ECD_ENTRIES_THIS_DISK")] != entry_count
69
+ or len(end_record[getattr(zip_internal, "_ECD_COMMENT")]) != end_record[getattr(zip_internal, "_ECD_COMMENT_SIZE")]
70
+ or (end_record[getattr(zip_internal, "_ECD_SIGNATURE")] != getattr(zip_internal, "stringEndArchive64")
71
+ and (central_directory_size == 0xffffffff or directory_offset == 0xffffffff))):
72
+ raise ReaderArchiveInvalidError("阅读文件元数据无效")
73
+ if central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES:
74
+ raise ReaderArchiveLimitError("阅读文件元数据过大")
75
+ if entry_count > limits.READER_ARCHIVE_MAX_ENTRIES:
76
+ raise ReaderArchiveLimitError("阅读文件条目过多")
77
+ if directory_offset + central_directory_size > len(archive):
78
+ raise ReaderArchiveInvalidError("阅读文件元数据无效")
79
+ with zipfile.ZipFile(io.BytesIO(archive)) as book_zip:
80
+ infos = book_zip.infolist()
81
+ if len(infos) > limits.READER_ARCHIVE_MAX_ENTRIES:
82
+ raise ReaderArchiveLimitError("阅读文件条目过多")
83
+
84
+ if len(infos) != entry_count:
85
+ raise ReaderArchiveInvalidError("阅读文件条目数无效")
86
+ central_directory_offset = book_zip.start_dir
87
+ archive_comment = book_zip.comment
88
+ if (
89
+ not _plain_int(central_directory_size)
90
+ or central_directory_size < 0
91
+ or central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES
92
+ or not _plain_int(central_directory_offset)
93
+ or central_directory_offset < 0
94
+ or central_directory_offset > len(archive)
95
+ or central_directory_size > len(archive) - central_directory_offset
96
+ or not _is_bytes(archive_comment)
97
+ ):
98
+ raise ReaderArchiveInvalidError("阅读文件元数据无效")
99
+
100
+ expanded = 0
101
+ compressed = 0
102
+ metadata_bytes = len(archive_comment)
103
+ for info in infos:
104
+ filename = info.orig_filename
105
+ extra = info.extra
106
+ comment = info.comment
107
+ if not _is_str(filename) or not _is_bytes(extra) or not _is_bytes(comment):
108
+ raise ReaderArchiveInvalidError("阅读文件元数据无效")
109
+ name = filename.replace("\\", "/")
110
+ name_parts = name.split("/")
111
+ if (not name or name.startswith("/") or "\x00" in name
112
+ or any(part in {".", ".."} for part in name_parts)
113
+ or any(not part for part in name_parts[:-1])
114
+ or not limits.READER_ARCHIVE_MEMBER_RE.fullmatch(name)):
115
+ raise ReaderArchiveInvalidError("阅读文件包含不安全路径")
116
+ try:
117
+ filename_bytes = len(filename.encode("utf-8", "surrogatepass"))
118
+ except (UnicodeError, AttributeError) as exc:
119
+ raise ReaderArchiveInvalidError("阅读文件元数据无效") from exc
120
+ metadata_bytes += 46 + filename_bytes + len(extra) + len(comment)
121
+ if metadata_bytes > limits.READER_ARCHIVE_MAX_METADATA_BYTES:
122
+ raise ReaderArchiveLimitError("阅读文件元数据过大")
123
+
124
+ file_size = info.file_size
125
+ compressed_size = info.compress_size
126
+ header_offset = info.header_offset
127
+ if (
128
+ not _plain_int(file_size)
129
+ or file_size < 0
130
+ or not _plain_int(compressed_size)
131
+ or compressed_size < 0
132
+ or compressed_size > len(archive)
133
+ or not _plain_int(header_offset)
134
+ or header_offset < 0
135
+ or header_offset >= len(archive)
136
+ or header_offset >= central_directory_offset
137
+ ):
138
+ raise ReaderArchiveInvalidError("阅读文件条目无效")
139
+ expanded += file_size
140
+ compressed += compressed_size
141
+ if expanded > limits.READER_ARCHIVE_MAX_EXPANDED_BYTES:
142
+ raise ReaderArchiveLimitError("阅读文件展开后过大")
143
+ if file_size and (compressed_size == 0 or file_size > compressed_size * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO):
144
+ raise ReaderArchiveLimitError("阅读文件压缩比过高")
145
+
146
+ if compressed == 0:
147
+ if expanded:
148
+ raise ReaderArchiveLimitError("阅读文件压缩比过高")
149
+ elif expanded > compressed * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO:
150
+ raise ReaderArchiveLimitError("阅读文件压缩比过高")
151
+ if compressed > len(archive):
152
+ raise ReaderArchiveInvalidError("阅读文件条目无效")
153
+ except (ReaderArchiveLimitError, ReaderArchiveInvalidError):
154
+ raise
155
+ except Exception as exc:
156
+ raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") from exc
backend/reader/catalog/application/indexes.py CHANGED
@@ -7,8 +7,8 @@ from contextlib import AbstractContextManager
7
  from dataclasses import dataclass
8
  from typing import Protocol
9
 
10
- from backend.reader_index import ReaderIndexBuild
11
- from backend.search_execution import SearchBusy, SearchExecutor
12
 
13
  Record = dict[str, object]
14
 
 
7
  from dataclasses import dataclass
8
  from typing import Protocol
9
 
10
+ from backend.reader.catalog.domain.index import ReaderIndexBuild
11
+ from backend.search.infrastructure.executor import SearchBusy, SearchExecutor
12
 
13
  Record = dict[str, object]
14
 
backend/reader/catalog/domain/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """reader catalog domain package."""
backend/reader/catalog/domain/assets.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure validation and decoding for the Reader-Assets sidecar."""
2
+
3
+ import gzip
4
+ import io
5
+ import json
6
+ import posixpath
7
+ import re
8
+ from typing import cast
9
+
10
+ from backend.shared.transport.upstream import READER_ASSET_PATH_RE as READER_ASSET_PATH_RE # re-exported for app/tests
11
+
12
+
13
+ READER_ASSET_FILENAMES = {
14
+ "p": {"document.pdf", "linearized.pdf", "page-manifest.json"},
15
+ "e": {"document.epub", "book.epub", "document.mobi", "document.azw", "document.azw3", "document.fb2", "chapter-manifest.json"},
16
+ "d": {"document.docx"},
17
+ "h": {"document.html"},
18
+ "t": {"document.txt", "document.vcf", "document.ini"},
19
+ "k": {"document.md"},
20
+ "i": {"document.webp", "document.jpg", "document.jpeg", "document.png", "document.gif", "document.bmp", "page-manifest.json"},
21
+ "a": {"audio.mp3", "audio.wav", "audio.m4a", "audio.flac", "audio.mpga"},
22
+ "v": {"video.mp4", "video.mov"},
23
+ "f": {"document.swf"},
24
+ }
25
+ READER_BUCKET_PATH_RE = re.compile(
26
+ r"^(?:documents/(?:text|web|spreadsheet|office|pdf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:document\.(?:txt|md|html|docx|pdf|vcf|ini))|"
27
+ r"chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\.json|epub-search-index\.json\.gz|chapters/chapter-[0-9]{4}\.xhtml|resources/(?!\.{1,2}(?:/|$))[^/]+(?:/(?!\.{1,2}(?:/|$))[^/]+)*)|"
28
+ r"media/(?:audio|video|swf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:audio\.[a-z0-9]+|video\.[a-z0-9]+|document\.swf)|"
29
+ r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp|gif)/[0-9a-f]{64}/(?:document\.webp|page-manifest\.json|pages/page-[0-9]{6}\.webp)|"
30
+ r"native/ebook/chm/[0-9a-f]{64}/document\.epub|"
31
+ r"derived/[a-zA-Z0-9._-]+/[a-z0-9]{32}/(?:document\.pdf|page-manifest\.json|pages/page-[0-9]{6}\.webp|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))|"
32
+ r"objects/(?P<djvu_prefix>[0-9a-f]{2})/(?P=djvu_prefix)[0-9a-f]{62}/[0-9a-f]{16}/document\.djvu|"
33
+ r"objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:reading-manifest\.json|page-map\.json\.gz|text-layer-manifest\.json|text-review-manifest\.json|text/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz|search-[0-9]{6}-[0-9]{6}\.json\.gz|partition-[0-9]{6}-[0-9]{6}-manifest\.json)|preview/(?:page-[0-9]{6}\.(?:png|webp|jpeg|svg|jxl)|partition-[0-9]{6}-[0-9]{6}-manifest\.json))|"
34
+ r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl|png)|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|document\.pdf))$"
35
+ )
36
+ READER_EBOOK_BUCKET = "vomebook/reader-assets-v2"
37
+ READER_ALLOWED_BUCKETS = {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}
38
+
39
+
40
+ def decode_reader_assets(
41
+ raw: bytes,
42
+ max_compressed_bytes: int = 5 * 1024 * 1024,
43
+ max_decompressed_bytes: int = 50 * 1024 * 1024,
44
+ ) -> dict[str, object]:
45
+ if len(raw) > max_compressed_bytes:
46
+ raise ValueError("reader assets sidecar is too large")
47
+ with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:
48
+ decoded = stream.read(max_decompressed_bytes + 1)
49
+ if len(decoded) > max_decompressed_bytes:
50
+ raise ValueError("reader assets sidecar expands beyond limit")
51
+ payload: object = json.loads(decoded)
52
+ payload_map = cast(dict[str, object], payload) if isinstance(payload, dict) else None
53
+ files = payload_map.get("f") if payload_map is not None and payload_map.get("v") == 1 else None
54
+ if not isinstance(files, dict):
55
+ raise ValueError("invalid reader assets sidecar")
56
+ file_map = cast(dict[object, object], files)
57
+ clean: dict[str, dict[str, object]] = {}
58
+ for key, raw_entry in file_map.items():
59
+ if not isinstance(key, str) or not isinstance(raw_entry, dict):
60
+ continue
61
+ entry = cast(dict[str, object], raw_entry)
62
+ if entry.get("s") not in (2, 3, 4):
63
+ continue
64
+ if entry.get("s") == 2:
65
+ path = entry.get("p")
66
+ mode = entry.get("m")
67
+ if not isinstance(path, str) or not isinstance(mode, str) or mode not in READER_ASSET_FILENAMES:
68
+ continue
69
+ if entry.get("b") not in READER_ALLOWED_BUCKETS:
70
+ continue
71
+ path_pattern = READER_BUCKET_PATH_RE
72
+ image_page_path = bool(re.fullmatch(r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp)/[0-9a-f]{64}/pages/page-[0-9]{6}\.webp", path))
73
+ valid_filename = (posixpath.basename(path) in READER_ASSET_FILENAMES[mode]
74
+ or (mode == "i" and image_page_path)
75
+ or (mode == "p" and entry.get("b") == "vomebook/pdf-pages-v2"
76
+ and path.endswith("/reading-manifest.json")))
77
+ if (
78
+ not path_pattern.fullmatch(path)
79
+ or not valid_filename
80
+ ):
81
+ continue
82
+ chapter_manifest = entry.get("c")
83
+ fallback = entry.get("f")
84
+ ocr_manifest = entry.get("o")
85
+ chapter_bucket = entry.get("cb")
86
+ bucket = entry.get("b")
87
+ document_path, document_bucket = entry.get("pd"), entry.get("pdb")
88
+ if (document_path is not None or document_bucket is not None) and (
89
+ mode != "p" or not path.endswith("/page-manifest.json")
90
+ or not isinstance(document_bucket, str)
91
+ or document_bucket not in READER_ALLOWED_BUCKETS
92
+ or not isinstance(document_path, str)
93
+ or not READER_BUCKET_PATH_RE.fullmatch(document_path)
94
+ or not document_path.endswith("/document.pdf")
95
+ ):
96
+ continue
97
+ if chapter_manifest is not None and (
98
+ mode not in {"e", "p"}
99
+ or not isinstance(chapter_manifest, str)
100
+ or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest)
101
+ or not chapter_manifest.endswith("/chapter-manifest.json")
102
+ ):
103
+ continue
104
+ if chapter_manifest is not None and chapter_bucket is None:
105
+ continue
106
+ if chapter_bucket is not None and (
107
+ chapter_bucket != READER_EBOOK_BUCKET or not isinstance(chapter_manifest, str)
108
+ or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest)
109
+ or not (chapter_manifest.startswith("ebook-chapters/")
110
+ or (chapter_bucket == "vomebook/reader-assets-v2"
111
+ and chapter_manifest.startswith("chapters/ebook/")))
112
+ ):
113
+ continue
114
+ fallback_is_chm = (bucket == READER_EBOOK_BUCKET and isinstance(fallback, str)
115
+ and READER_BUCKET_PATH_RE.fullmatch(fallback)
116
+ and fallback.endswith("/document.epub"))
117
+ if fallback is not None and not fallback_is_chm:
118
+ continue
119
+ if ocr_manifest is not None and (
120
+ not isinstance(ocr_manifest, str)
121
+ or not READER_BUCKET_PATH_RE.fullmatch(ocr_manifest)
122
+ or not ocr_manifest.endswith("/ocr-manifest.json")
123
+ ):
124
+ continue
125
+ if entry.get("b") is not None and entry.get("b") not in READER_ALLOWED_BUCKETS:
126
+ continue
127
+ if entry.get("ob") is not None and entry.get("ob") != "vomebook/pdf-pages-v2":
128
+ continue
129
+ if bucket == "vomebook/pdf-pages-v2":
130
+ if mode == "p" and (not path.endswith(("/page-manifest.json", "/reading-manifest.json", "/document.pdf"))
131
+ or not READER_BUCKET_PATH_RE.fullmatch(path)):
132
+ continue
133
+ clean[key] = {
134
+ "s": 2,
135
+ "m": mode,
136
+ "p": path,
137
+ **({"b": bucket} if bucket else {}),
138
+ **({"pd": document_path, "pdb": document_bucket} if document_path else {}),
139
+ **({"c": chapter_manifest} if chapter_manifest else {}),
140
+ **({"cb": chapter_bucket} if chapter_bucket else {}),
141
+ **({"f": fallback} if fallback else {}),
142
+ **({"o": ocr_manifest} if ocr_manifest else {}),
143
+ **({"ob": "vomebook/pdf-pages-v2"} if entry.get("ob") else {}),
144
+ **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {}),
145
+ }
146
+ else:
147
+ ocr_manifest = entry.get("o")
148
+ if (isinstance(ocr_manifest, str) and READER_BUCKET_PATH_RE.fullmatch(ocr_manifest)
149
+ and ocr_manifest.endswith("/ocr-manifest.json")):
150
+ clean[key] = {"s": 3, "m": "p", "o": ocr_manifest, "b": "vomebook/pdf-pages-v2",
151
+ **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {})}
152
+ else:
153
+ clean[key] = {"s": 4}
154
+ return {"v": 1, "f": clean}
backend/reader/catalog/domain/index.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Incremental Reader index construction without publishing partial results."""
2
+
3
+ from collections.abc import Callable
4
+ from typing import TypedDict, cast
5
+
6
+
7
+ class ReaderIndexBuild(TypedDict):
8
+ generation: int
9
+ records: list[dict[str, object]]
10
+ next: int
11
+ indices: list[int]
12
+ repos: dict[str, list[int]]
13
+ keys: dict[str, int]
14
+ ids: dict[str, list[int]]
15
+ legacy_ids: dict[str, list[int]]
16
+
17
+
18
+ def new_build(generation: int, records: list[dict[str, object]]) -> ReaderIndexBuild:
19
+ return {"generation": generation, "records": records, "next": 0,
20
+ "indices": [], "repos": {}, "keys": {}, "ids": {}, "legacy_ids": {}}
21
+
22
+
23
+ def advance_build(build: ReaderIndexBuild, limit: int, deadline: float, *,
24
+ now: Callable[[], float], source_id: Callable[[str], str],
25
+ asset_key: Callable[[dict[str, object]], str],
26
+ record_link: Callable[[dict[str, object]], str],
27
+ dataset_url: Callable[[str, str], str],
28
+ reader_extensions: frozenset[str]) -> bool:
29
+ """Advance at most one batch; callers own generation checks and publication."""
30
+ end = min(len(build["records"]), build["next"] + limit)
31
+ while build["next"] < end:
32
+ idx = build["next"]
33
+ rec = build["records"][idx]
34
+ repo = rec.get("Repo", "")
35
+ build["keys"][asset_key(rec)] = idx
36
+ current_url = cast(str, rec.get("Link") or record_link(rec))
37
+ build["ids"].setdefault(source_id(current_url), []).append(idx)
38
+ # Old links omitted a repeated filename extension; index the historical
39
+ # alias without changing the canonical identity or resolving collisions.
40
+ name, ext, folders = rec.get("File", ""), rec.get("Extension", ""), rec.get("Folder", [])
41
+ if (isinstance(repo, str) and repo.startswith("VoiceOfML/") and isinstance(name, str)
42
+ and isinstance(ext, str) and ext and name.lower().endswith("." + ext.lower())
43
+ and isinstance(folders, list) and all(isinstance(part, str) for part in cast(list[object], folders))):
44
+ legacy_path = "/".join([*cast(list[str], folders), name])
45
+ legacy_url = dataset_url(repo, legacy_path)
46
+ if legacy_url != (rec.get("Link") or record_link(rec)):
47
+ build["legacy_ids"].setdefault(source_id(legacy_url), []).append(idx)
48
+ if rec.get("_ext_lower", "") in reader_extensions:
49
+ build["indices"].append(idx)
50
+ build["repos"].setdefault(cast(str, repo), []).append(idx)
51
+ build["next"] += 1
52
+ if now() >= deadline:
53
+ break
54
+ return build["next"] >= len(build["records"])
backend/reader/catalog/infrastructure/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """reader catalog infrastructure package."""
backend/reader/catalog/infrastructure/v3.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pinned v3 catalog projection, using only canonical bucket metadata URLs."""
2
+ import asyncio
3
+ import hashlib
4
+ import json
5
+ import re
6
+ from typing import Callable, Literal, ParamSpec, TypeVar, cast, overload
7
+
8
+ import aiohttp
9
+
10
+ from backend.shared.transport.upstream import open_download_response, validate_fixed_source_redirect_url
11
+
12
+ BUCKET = "vomebook/reader-assets-v2"
13
+ BASE = f"https://huggingface.co/buckets/{BUCKET}/resolve/"
14
+ POINTER = "reader-index/v3/current.json"
15
+ MAX_BYTES = 8 * 1024 * 1024
16
+
17
+
18
+ def sha(value: object) -> re.Match[str] | bool | None:
19
+ return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value)
20
+
21
+
22
+ def catalog_path(generation: object) -> str:
23
+ if not sha(generation):
24
+ raise ValueError("invalid v3 catalog generation")
25
+ return f"reader-index/v3/generations/{generation}/catalog.json"
26
+
27
+
28
+ def decode_catalog(pointer: dict[str, object], raw: bytes) -> dict[str, object]:
29
+ from backend.reader.catalog.domain.assets import READER_BUCKET_PATH_RE
30
+ if pointer.get("version") != 1 or pointer.get("kind") != "reader-reading-pointer":
31
+ raise ValueError("invalid v3 pointer")
32
+ generation = pointer.get("generation")
33
+ ref = cast(dict[str, object], pointer.get("catalog", {}))
34
+ if (ref.get("bucket") != BUCKET or ref.get("path") != catalog_path(generation)
35
+ or ref.get("role") != "runtime" or type(ref.get("bytes")) is not int
36
+ or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES or not sha(ref.get("sha256"))
37
+ or len(raw) != ref["bytes"] or hashlib.sha256(raw).hexdigest() != ref["sha256"]):
38
+ raise ValueError("v3 catalog resource mismatch")
39
+ catalog = cast(dict[str, object], json.loads(raw))
40
+ body = {k: v for k, v in catalog.items() if k != "generation"}
41
+ digest = hashlib.sha256(json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
42
+ allow_nan=False).encode()).hexdigest()
43
+ if (catalog.get("version") != 3 or catalog.get("kind") != "reader-reading-catalog"
44
+ or catalog.get("generation") != generation or digest != generation
45
+ or not isinstance(catalog.get("files"), dict)):
46
+ raise ValueError("invalid v3 catalog identity")
47
+ overrides: dict[str, dict[str, object]] = {}
48
+ for key, raw_entry in cast(dict[object, object], catalog["files"]).items():
49
+ if not isinstance(key, str) or not key or not isinstance(raw_entry, dict):
50
+ raise ValueError("invalid v3 source key")
51
+ entry = cast(dict[str, object], raw_entry)
52
+ resource = cast(dict[str, object], entry.get("resource", {}))
53
+ source = entry.get("source_sha256")
54
+ path = resource.get("path", "")
55
+ if (not isinstance(source, str) or not sha(source) or not sha(entry.get("reading_generation"))
56
+ or resource.get("bucket") != "vomebook/pdf-pages-v2" or resource.get("role") != "runtime"
57
+ or not isinstance(path, str) or not READER_BUCKET_PATH_RE.fullmatch(path)
58
+ or not path.startswith(f"objects/{source[:2]}/{source}/")
59
+ or not path.endswith("/reading-manifest.json") or not sha(resource.get("sha256"))
60
+ or type(resource.get("bytes")) is not int or cast(int, resource["bytes"]) < 1):
61
+ raise ValueError("invalid v3 reading reference")
62
+ overrides[key] = {"s": 2, "m": "p", "p": path, "b": resource["bucket"]}
63
+ return {"generation": generation, "catalog_sha256": ref["sha256"],
64
+ "files": overrides, "catalog": ref,
65
+ **({"base_sidecar_ref": catalog["base_sidecar"]} if catalog.get("base_sidecar") else {})}
66
+
67
+
68
+ def validate_base_ref(ref: object) -> dict[str, object]:
69
+ if not isinstance(ref, dict):
70
+ raise ValueError("invalid unified base sidecar")
71
+ ref = cast(dict[str, object], ref)
72
+ if (ref.get("bucket") != BUCKET or ref.get("role") != "runtime"
73
+ or not sha(ref.get("sha256")) or ref.get("path") !=
74
+ f"reader-index/snapshots/{ref['sha256']}/reader_assets.json.gz"
75
+ or type(ref.get("bytes")) is not int or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES):
76
+ raise ValueError("invalid unified base sidecar")
77
+ return ref
78
+
79
+
80
+ _DecodeParams = ParamSpec("_DecodeParams")
81
+ _DecodeResult = TypeVar("_DecodeResult")
82
+
83
+
84
+ async def decode_in_thread(func: Callable[_DecodeParams, _DecodeResult],
85
+ *args: _DecodeParams.args, **kwargs: _DecodeParams.kwargs) -> _DecodeResult:
86
+ # Keep the refresh owner alive until its worker exits even after cancellation.
87
+ # Otherwise a subsequent refresh could start another large decode while the
88
+ # abandoned worker still holds its inputs and intermediate objects.
89
+ task = asyncio.create_task(asyncio.to_thread(func, *args, **kwargs))
90
+ try:
91
+ return await asyncio.shield(task)
92
+ except asyncio.CancelledError:
93
+ while not task.done():
94
+ try:
95
+ await asyncio.shield(task)
96
+ except asyncio.CancelledError:
97
+ continue
98
+ except Exception:
99
+ break
100
+ if not task.cancelled():
101
+ task.exception() # Retrieve a worker failure without replacing cancellation.
102
+ raise
103
+
104
+
105
+ async def load_reading_catalog(session: object) -> dict[str, object] | None:
106
+ @overload
107
+ async def fetch(path: str, *, missing: Literal[True]) -> bytes | None: ...
108
+
109
+ @overload
110
+ async def fetch(path: str, *, missing: Literal[False] = False) -> bytes: ...
111
+
112
+ async def fetch(path: str, *, missing: bool = False) -> bytes | None:
113
+ source_url = BASE + path
114
+ # Validate every redirect hop against the fixed URL or signed storage;
115
+ # metadata is mutable, so its signed targets are never reused.
116
+ response = await open_download_response(
117
+ session, source_url, aiohttp.ClientTimeout(total=20, connect=8, sock_read=10),
118
+ request_headers={"Cache-Control": "no-cache"},
119
+ url_validator=lambda url: validate_fixed_source_redirect_url(url, source_url),
120
+ cache_redirects=False,
121
+ )
122
+ try:
123
+ if missing and response.status == 404:
124
+ return None
125
+ if response.status != 200:
126
+ raise RuntimeError(f"v3 metadata HTTP {response.status}")
127
+ raw = bytearray()
128
+ async for chunk in response.content.iter_chunked(64 * 1024):
129
+ raw.extend(chunk)
130
+ if len(raw) > MAX_BYTES:
131
+ raise ValueError("v3 metadata exceeds limit")
132
+ return bytes(raw)
133
+ finally:
134
+ response.release()
135
+ raw = await fetch(POINTER, missing=True)
136
+ if raw is None:
137
+ return None
138
+ pointer = cast(dict[str, object], json.loads(raw))
139
+ # Validate the exact fixed catalog path before starting another request.
140
+ path = catalog_path(pointer.get("generation"))
141
+ if cast(dict[str, object], pointer.get("catalog", {})).get("path") != path:
142
+ raise ValueError("v3 pointer path mismatch")
143
+ catalog = await fetch(path)
144
+ result = await decode_in_thread(decode_catalog, pointer, catalog)
145
+ if result.get("base_sidecar_ref"):
146
+ ref = validate_base_ref(result["base_sidecar_ref"])
147
+ packed = await fetch(cast(str, ref["path"]))
148
+ if len(packed) != ref["bytes"] or hashlib.sha256(packed).hexdigest() != ref["sha256"]:
149
+ raise ValueError("unified base sidecar checksum mismatch")
150
+ from backend.reader.catalog.domain.assets import decode_reader_assets
151
+ result["base_sidecar"] = await decode_in_thread(decode_reader_assets, packed)
152
+ return result
153
+
154
+
155
+ def merge_sidecar(base: dict[str, object], catalog: dict[str, object] | None) -> dict[str, object]:
156
+ if not catalog:
157
+ return base
158
+ base = cast(dict[str, object], catalog.get("base_sidecar", base))
159
+ return {**base, "f": {**cast(dict[str, object], base["f"]), **cast(dict[str, object], catalog["files"])},
160
+ "v3": {"generation": catalog["generation"], "catalog_sha256": catalog["catalog_sha256"],
161
+ "files": len(cast(dict[str, object], catalog["files"]))}}
backend/reader/document/application/ranges.py CHANGED
@@ -7,7 +7,7 @@ from typing import Protocol, cast
7
  from fastapi import Request
8
  from fastapi.responses import Response
9
 
10
- from backend.proxy_streams import OwnedStreamingResponse, SharedRangeFlight
11
  from backend.reader.document.domain.policy import RangeFlightKey, RangeKey, ReaderStreamOptions
12
 
13
 
 
7
  from fastapi import Request
8
  from fastapi.responses import Response
9
 
10
+ from backend.shared.transport.streams import OwnedStreamingResponse, SharedRangeFlight
11
  from backend.reader.document.domain.policy import RangeFlightKey, RangeKey, ReaderStreamOptions
12
 
13
 
backend/reader/document/domain/policy.py CHANGED
@@ -2,7 +2,7 @@
2
  from collections.abc import Callable, Hashable, Mapping
3
  from typing import TypedDict
4
 
5
- from backend.reader_range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry
6
 
7
  RangeFlightKey = tuple[RangeKey, Hashable, str | None]
8
 
 
2
  from collections.abc import Callable, Hashable, Mapping
3
  from typing import TypedDict
4
 
5
+ from backend.reader.document.domain.range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry
6
 
7
  RangeFlightKey = tuple[RangeKey, Hashable, str | None]
8
 
backend/reader/document/domain/range_cache.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Safe exact-byte subrange reuse for the Reader proxy's bounded cache."""
2
+ from __future__ import annotations
3
+
4
+ from collections import OrderedDict
5
+ from collections.abc import Callable
6
+ from typing import Protocol
7
+ import re
8
+
9
+ RangeKey = tuple[str, str, int | None, str | None]
10
+ RangeCacheEntry = tuple[float, bytes, dict[str, str]]
11
+
12
+
13
+ class RangeCacheState(Protocol):
14
+ reader_range_cache: OrderedDict[RangeKey, RangeCacheEntry]
15
+ reader_range_cache_bytes: int
16
+
17
+
18
+ def requested_range_bounds(header: str | None, total: int) -> tuple[int, int] | None:
19
+ """Resolve an ordinary single byte range; unknown/unsatisfiable forms return None."""
20
+ if header is None or total <= 0:
21
+ return None
22
+ match = re.fullmatch(r"bytes=([0-9]{0,20})-([0-9]{0,20})", header)
23
+ if match is None:
24
+ return None
25
+ first, last = match.groups()
26
+ if not first:
27
+ if not last or int(last) == 0:
28
+ return None
29
+ return max(0, total - int(last)), total - 1
30
+ start = int(first)
31
+ end = min(int(last), total - 1) if last else total - 1
32
+ if start > end:
33
+ return None
34
+ return start, end
35
+
36
+
37
+ def cached_subrange(range_key: RangeKey, get_state: Callable[[], RangeCacheState],
38
+ get_limit: Callable[[], int], get_ttl: Callable[[], int],
39
+ now: Callable[[], float]) -> tuple[bytes, dict[str, str]] | None:
40
+ """Serve a verified contained range, evicting stale entries in LRU order."""
41
+ requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_key[1])
42
+ if requested is None:
43
+ return None
44
+ start, end = (int(value) for value in requested.groups())
45
+ if start > end or end - start + 1 > get_limit():
46
+ return None
47
+ cache = get_state().reader_range_cache
48
+ current_time = now()
49
+ for key in reversed(list(cache)):
50
+ cached_at, payload, headers = cache[key]
51
+ if current_time - cached_at >= get_ttl():
52
+ cache.pop(key)
53
+ get_state().reader_range_cache_bytes -= len(payload)
54
+ continue
55
+ if key[0] != range_key[0] or key[2:] != range_key[2:]:
56
+ continue
57
+ match = re.fullmatch(r"bytes ([0-9]+)-([0-9]+)/([0-9]+)", headers.get("Content-Range", ""))
58
+ if match is None:
59
+ continue
60
+ cached_start, cached_end, total = (int(value) for value in match.groups())
61
+ final_end = min(end, total - 1)
62
+ if cached_start <= start <= final_end <= cached_end and len(payload) == cached_end - cached_start + 1:
63
+ cache.move_to_end(key)
64
+ body = payload[start - cached_start:final_end - cached_start + 1]
65
+ return body, {**headers, "Content-Range": f"bytes {start}-{final_end}/{total}",
66
+ "Content-Length": str(len(body))}
67
+ return None
backend/reader/document/http/transport.py CHANGED
@@ -13,8 +13,8 @@ import aiohttp
13
  from fastapi import Request
14
  from fastapi.responses import JSONResponse, Response
15
 
16
- from backend.proxy_streams import OwnedStreamingResponse, UpstreamLease
17
- from backend.reader_range_cache import RangeCacheState
18
  from backend.reader.document.domain.policy import RangeKey, RangeCacheEntry, ReaderStreamOptions
19
 
20
 
 
13
  from fastapi import Request
14
  from fastapi.responses import JSONResponse, Response
15
 
16
+ from backend.shared.transport.streams import OwnedStreamingResponse, UpstreamLease
17
+ from backend.reader.document.domain.range_cache import RangeCacheState
18
  from backend.reader.document.domain.policy import RangeKey, RangeCacheEntry, ReaderStreamOptions
19
 
20
 
backend/reader/query/application/ocr.py CHANGED
@@ -5,7 +5,7 @@ from collections.abc import Awaitable, Callable
5
  from typing import Protocol, cast
6
  from urllib.parse import ParseResult, parse_qs
7
 
8
- from backend.reader_ocr import OcrPage, OcrSearchHit
9
 
10
  JsonObject = dict[str, object]
11
  OcrSearch = Callable[[list[OcrPage], str, int, int], tuple[int, list[OcrSearchHit]]]
 
5
  from typing import Protocol, cast
6
  from urllib.parse import ParseResult, parse_qs
7
 
8
+ from backend.reader.query.domain.ocr import OcrPage, OcrSearchHit
9
 
10
  JsonObject = dict[str, object]
11
  OcrSearch = Callable[[list[OcrPage], str, int, int], tuple[int, list[OcrSearchHit]]]
backend/reader/query/domain/ocr.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded PDF text-index validation and original-offset search."""
2
+ from __future__ import annotations
3
+
4
+ from array import array
5
+ import gzip
6
+ import io
7
+ import json
8
+ import re
9
+ from typing import NotRequired, TypedDict, cast
10
+
11
+
12
+ class OcrSpan(TypedDict):
13
+ start: int
14
+ end: int
15
+ box: list[int | float]
16
+
17
+
18
+ class OcrPage(TypedDict):
19
+ page: int
20
+ text: str
21
+ folded: str
22
+ fold_map: NotRequired[array[int] | None]
23
+ layout: dict[str, object]
24
+ spans: list[OcrSpan]
25
+
26
+
27
+ class OcrSearchHit(TypedDict):
28
+ page: int
29
+ start: int
30
+ length: int
31
+ snippet: str
32
+ snippet_start: int
33
+ boxes: list[list[int | float]]
34
+
35
+
36
+ def fold_reader_ocr_text(text: str) -> tuple[str, array[int] | None]:
37
+ """Map casefold-expanded code points back to the source text."""
38
+ folded = text.casefold()
39
+ if len(folded) == len(text):
40
+ return folded, None
41
+ pieces: list[str] = []
42
+ fold_map: array[int] = array('I')
43
+ for index, character in enumerate(text):
44
+ piece = character.casefold()
45
+ pieces.append(piece)
46
+ fold_map.extend([index] * len(piece))
47
+ return "".join(pieces), fold_map
48
+
49
+
50
+ def parse_reader_ocr_book(raw: bytes, max_bytes: int) -> tuple[list[OcrPage], int]:
51
+ """Decode and validate one v2 book index without exceeding its byte limit."""
52
+ with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:
53
+ decoded = stream.read(max_bytes + 1)
54
+ if len(decoded) > max_bytes:
55
+ raise ValueError("PDF OCR text index is too large")
56
+ payload: object = json.loads(decoded)
57
+ if not isinstance(payload, dict):
58
+ raise ValueError("invalid PDF OCR text index")
59
+ document = cast(dict[str, object], payload)
60
+ raw_pages = document.get("pages")
61
+ if not isinstance(raw_pages, list):
62
+ raise ValueError("invalid PDF OCR text index")
63
+ pages = cast(list[object], raw_pages)
64
+ if (len(pages) > 200000
65
+ or document.get("version") != 2 or document.get("kind") != "pdf-book-text"
66
+ or document.get("complete") is not True
67
+ or document.get("offset_unit") != "unicode-codepoint"
68
+ or document.get("page_count") != len(pages)
69
+ or not re.fullmatch(r"[0-9a-f]{64}", str(document.get("source_sha256", "")))):
70
+ raise ValueError("invalid PDF OCR text index")
71
+ output: list[OcrPage] = []
72
+ total_bytes = 0
73
+ previous = 0
74
+ for raw_page in pages:
75
+ if not isinstance(raw_page, dict):
76
+ raise ValueError("invalid PDF OCR text page")
77
+ item = cast(dict[str, object], raw_page)
78
+ number, text = item.get("page"), item.get("text")
79
+ if (not isinstance(number, int) or number < 1 or number <= previous
80
+ or not isinstance(text, str)):
81
+ raise ValueError("invalid PDF OCR text page")
82
+ total_bytes += len(text.encode("utf-8"))
83
+ if total_bytes > max_bytes:
84
+ raise ValueError("PDF OCR text index is too large")
85
+ layout, spans = item.get("layout"), item.get("text_spans")
86
+ if (not isinstance(layout, dict) or cast(dict[str, object], layout).get("offset_unit") != "unicode-codepoint"
87
+ or not isinstance(spans, list)):
88
+ raise ValueError("invalid PDF text layout mapping")
89
+ previous_span_end = 0
90
+ for raw_span in cast(list[object], spans):
91
+ if not isinstance(raw_span, dict):
92
+ raise ValueError("invalid PDF text span")
93
+ span = cast(dict[str, object], raw_span)
94
+ start, end, box = span.get("start"), span.get("end"), span.get("box")
95
+ if (not isinstance(start, int) or not isinstance(end, int) or start < previous_span_end
96
+ or end <= start or end > len(text) or not isinstance(box, list)):
97
+ raise ValueError("invalid PDF text span")
98
+ values = cast(list[object], box)
99
+ if len(values) != 4 or any(not isinstance(value, (int, float)) or value < 0 or value > 1
100
+ for value in values):
101
+ raise ValueError("invalid PDF text span")
102
+ previous_span_end = end
103
+ folded, fold_map = fold_reader_ocr_text(text)
104
+ if fold_map is not None:
105
+ total_bytes += len(fold_map) * fold_map.itemsize
106
+ output.append({"page": number, "text": text, "folded": folded, "fold_map": fold_map,
107
+ "layout": cast(dict[str, object], layout), "spans": cast(list[OcrSpan], spans)})
108
+ previous = number
109
+ return output, total_bytes
110
+
111
+
112
+ def search_reader_ocr_pages(
113
+ pages: list[OcrPage], needle: str, page: int, page_size: int
114
+ ) -> tuple[int, list[OcrSearchHit]]:
115
+ """Count all non-overlapping matches; return one page in original offsets."""
116
+ offset = (page - 1) * page_size
117
+ end_offset = offset + page_size
118
+ folded_length = len(needle)
119
+ total = 0
120
+ results: list[OcrSearchHit] = []
121
+ if not folded_length:
122
+ return total, results
123
+ # Once the requested page is full, only the remaining count is needed.
124
+ # Exact built-ins keep custom string methods and unusual callers on the
125
+ # existing per-match path, including their errors and side effects.
126
+ count_safe = type(needle) is str and type(page) is int and type(page_size) is int and page_size > 0
127
+ for item in pages:
128
+ text, folded = item["text"], item["folded"]
129
+ if "fold_map" in item:
130
+ fold_map = item["fold_map"]
131
+ elif len(folded) == len(text):
132
+ fold_map = None
133
+ else:
134
+ folded, fold_map = fold_reader_ocr_text(text)
135
+ if count_safe and len(results) == page_size and type(folded) is str:
136
+ total += folded.count(needle)
137
+ continue
138
+ start = 0
139
+ while True:
140
+ found = folded.find(needle, start)
141
+ if found < 0:
142
+ break
143
+ match_index = total
144
+ total += 1
145
+ if offset <= match_index < end_offset:
146
+ if fold_map is None:
147
+ original_start, original_end = found, found + folded_length
148
+ else:
149
+ original_start = fold_map[found]
150
+ original_end = fold_map[found + folded_length - 1] + 1
151
+ snippet_start = max(0, original_start - 72)
152
+ snippet_end = min(len(text), original_end + 88)
153
+ boxes = [span["box"] for span in item["spans"]
154
+ if span["end"] > original_start and span["start"] < original_end]
155
+ results.append({
156
+ "page": item["page"], "start": original_start,
157
+ "length": original_end - original_start,
158
+ "snippet": text[snippet_start:snippet_end],
159
+ "snippet_start": original_start - snippet_start, "boxes": boxes,
160
+ })
161
+ if count_safe and len(results) == page_size and type(folded) is str:
162
+ total += folded.count(needle, found + folded_length)
163
+ break
164
+ start = found + folded_length
165
+ return total, results
backend/reader_archive.py CHANGED
@@ -1,156 +1,12 @@
1
- """Bounded ZIP validation for reader archives with caller-owned limits."""
2
- from __future__ import annotations
3
-
4
- import io
5
- import re
6
- import zipfile
7
- from typing import Protocol, cast
8
-
9
-
10
- class ReaderArchiveLimits(Protocol):
11
- """Limits are read on every use so callers may replace them at any time."""
12
-
13
- @property
14
- def READER_RESOURCE_MAX_ARCHIVE_BYTES(self) -> int: ...
15
- @property
16
- def READER_ARCHIVE_MAX_ENTRIES(self) -> int: ...
17
- @property
18
- def READER_ARCHIVE_MAX_EXPANDED_BYTES(self) -> int: ...
19
- @property
20
- def READER_ARCHIVE_MAX_COMPRESSION_RATIO(self) -> int: ...
21
- @property
22
- def READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES(self) -> int: ...
23
- @property
24
- def READER_ARCHIVE_MAX_METADATA_BYTES(self) -> int: ...
25
- @property
26
- def READER_ARCHIVE_MEMBER_RE(self) -> re.Pattern[str]: ...
27
-
28
-
29
- class ReaderArchiveLimitError(ValueError):
30
- pass
31
-
32
-
33
- class ReaderArchiveInvalidError(ValueError):
34
- pass
35
-
36
-
37
- class ReaderDocumentLimitError(ValueError):
38
- pass
39
-
40
-
41
- def _plain_int(value: object) -> bool:
42
- return isinstance(value, int) and not isinstance(value, bool)
43
-
44
-
45
- def _is_bytes(value: object) -> bool:
46
- return isinstance(value, bytes)
47
-
48
-
49
- def _is_str(value: object) -> bool:
50
- return isinstance(value, str)
51
-
52
-
53
- def validate_reader_archive(archive: bytes, limits: ReaderArchiveLimits) -> None:
54
- if len(archive) > limits.READER_RESOURCE_MAX_ARCHIVE_BYTES:
55
- raise ReaderArchiveLimitError("阅读文件过大")
56
- try:
57
- # Use the stdlib's EOCD/ZIP64 parser before ZipFile allocates its directory.
58
- # These bounded EOCD fields are stdlib internals missing from typeshed.
59
- zip_internal = cast(object, zipfile)
60
- end_record = getattr(zip_internal, "_EndRecData")(io.BytesIO(archive))
61
- if not end_record:
62
- raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP")
63
- central_directory_size = end_record[getattr(zip_internal, "_ECD_SIZE")]
64
- directory_offset = end_record[getattr(zip_internal, "_ECD_OFFSET")]
65
- entry_count = end_record[getattr(zip_internal, "_ECD_ENTRIES_TOTAL")]
66
- if (end_record[getattr(zip_internal, "_ECD_DISK_NUMBER")] != 0
67
- or end_record[getattr(zip_internal, "_ECD_DISK_START")] != 0
68
- or end_record[getattr(zip_internal, "_ECD_ENTRIES_THIS_DISK")] != entry_count
69
- or len(end_record[getattr(zip_internal, "_ECD_COMMENT")]) != end_record[getattr(zip_internal, "_ECD_COMMENT_SIZE")]
70
- or (end_record[getattr(zip_internal, "_ECD_SIGNATURE")] != getattr(zip_internal, "stringEndArchive64")
71
- and (central_directory_size == 0xffffffff or directory_offset == 0xffffffff))):
72
- raise ReaderArchiveInvalidError("阅读文件元数据无效")
73
- if central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES:
74
- raise ReaderArchiveLimitError("阅读文件元数据过大")
75
- if entry_count > limits.READER_ARCHIVE_MAX_ENTRIES:
76
- raise ReaderArchiveLimitError("阅读文件条目过多")
77
- if directory_offset + central_directory_size > len(archive):
78
- raise ReaderArchiveInvalidError("阅读文件元数据无效")
79
- with zipfile.ZipFile(io.BytesIO(archive)) as book_zip:
80
- infos = book_zip.infolist()
81
- if len(infos) > limits.READER_ARCHIVE_MAX_ENTRIES:
82
- raise ReaderArchiveLimitError("阅读文件条目过多")
83
-
84
- if len(infos) != entry_count:
85
- raise ReaderArchiveInvalidError("阅读文件条目数无效")
86
- central_directory_offset = book_zip.start_dir
87
- archive_comment = book_zip.comment
88
- if (
89
- not _plain_int(central_directory_size)
90
- or central_directory_size < 0
91
- or central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES
92
- or not _plain_int(central_directory_offset)
93
- or central_directory_offset < 0
94
- or central_directory_offset > len(archive)
95
- or central_directory_size > len(archive) - central_directory_offset
96
- or not _is_bytes(archive_comment)
97
- ):
98
- raise ReaderArchiveInvalidError("阅读文件元数据无效")
99
-
100
- expanded = 0
101
- compressed = 0
102
- metadata_bytes = len(archive_comment)
103
- for info in infos:
104
- filename = info.orig_filename
105
- extra = info.extra
106
- comment = info.comment
107
- if not _is_str(filename) or not _is_bytes(extra) or not _is_bytes(comment):
108
- raise ReaderArchiveInvalidError("阅读文件元数据无效")
109
- name = filename.replace("\\", "/")
110
- name_parts = name.split("/")
111
- if (not name or name.startswith("/") or "\x00" in name
112
- or any(part in {".", ".."} for part in name_parts)
113
- or any(not part for part in name_parts[:-1])
114
- or not limits.READER_ARCHIVE_MEMBER_RE.fullmatch(name)):
115
- raise ReaderArchiveInvalidError("阅读文件包含不安全路径")
116
- try:
117
- filename_bytes = len(filename.encode("utf-8", "surrogatepass"))
118
- except (UnicodeError, AttributeError) as exc:
119
- raise ReaderArchiveInvalidError("阅读文件元数据无效") from exc
120
- metadata_bytes += 46 + filename_bytes + len(extra) + len(comment)
121
- if metadata_bytes > limits.READER_ARCHIVE_MAX_METADATA_BYTES:
122
- raise ReaderArchiveLimitError("阅读文件元数据过大")
123
-
124
- file_size = info.file_size
125
- compressed_size = info.compress_size
126
- header_offset = info.header_offset
127
- if (
128
- not _plain_int(file_size)
129
- or file_size < 0
130
- or not _plain_int(compressed_size)
131
- or compressed_size < 0
132
- or compressed_size > len(archive)
133
- or not _plain_int(header_offset)
134
- or header_offset < 0
135
- or header_offset >= len(archive)
136
- or header_offset >= central_directory_offset
137
- ):
138
- raise ReaderArchiveInvalidError("阅读文件条目无效")
139
- expanded += file_size
140
- compressed += compressed_size
141
- if expanded > limits.READER_ARCHIVE_MAX_EXPANDED_BYTES:
142
- raise ReaderArchiveLimitError("阅读文件展开后过大")
143
- if file_size and (compressed_size == 0 or file_size > compressed_size * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO):
144
- raise ReaderArchiveLimitError("阅读文件压缩比过高")
145
-
146
- if compressed == 0:
147
- if expanded:
148
- raise ReaderArchiveLimitError("阅读文件压缩比过高")
149
- elif expanded > compressed * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO:
150
- raise ReaderArchiveLimitError("阅读文件压缩比过高")
151
- if compressed > len(archive):
152
- raise ReaderArchiveInvalidError("阅读文件条目无效")
153
- except (ReaderArchiveLimitError, ReaderArchiveInvalidError):
154
- raise
155
- except Exception as exc:
156
- raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") from exc
 
1
+ """Compatibility import for backend.reader.archive.domain.validation."""
2
+ import sys
3
+ from backend.reader.archive.domain import validation as _implementation
4
+ from backend.reader.archive.domain.validation import (
5
+ ReaderArchiveInvalidError as ReaderArchiveInvalidError,
6
+ ReaderArchiveLimitError as ReaderArchiveLimitError,
7
+ ReaderArchiveLimits as ReaderArchiveLimits,
8
+ ReaderDocumentLimitError as ReaderDocumentLimitError,
9
+ validate_reader_archive as validate_reader_archive,
10
+ )
11
+
12
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/reader_assets.py CHANGED
@@ -1,154 +1,13 @@
1
- """Pure validation and decoding for the Reader-Assets sidecar."""
2
-
3
- import gzip
4
- import io
5
- import json
6
- import posixpath
7
- import re
8
- from typing import cast
9
-
10
- from backend.upstream_http import READER_ASSET_PATH_RE as READER_ASSET_PATH_RE # re-exported for app/tests
11
-
12
-
13
- READER_ASSET_FILENAMES = {
14
- "p": {"document.pdf", "linearized.pdf", "page-manifest.json"},
15
- "e": {"document.epub", "book.epub", "document.mobi", "document.azw", "document.azw3", "document.fb2", "chapter-manifest.json"},
16
- "d": {"document.docx"},
17
- "h": {"document.html"},
18
- "t": {"document.txt", "document.vcf", "document.ini"},
19
- "k": {"document.md"},
20
- "i": {"document.webp", "document.jpg", "document.jpeg", "document.png", "document.gif", "document.bmp", "page-manifest.json"},
21
- "a": {"audio.mp3", "audio.wav", "audio.m4a", "audio.flac", "audio.mpga"},
22
- "v": {"video.mp4", "video.mov"},
23
- "f": {"document.swf"},
24
- }
25
- READER_BUCKET_PATH_RE = re.compile(
26
- r"^(?:documents/(?:text|web|spreadsheet|office|pdf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:document\.(?:txt|md|html|docx|pdf|vcf|ini))|"
27
- r"chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\.json|epub-search-index\.json\.gz|chapters/chapter-[0-9]{4}\.xhtml|resources/(?!\.{1,2}(?:/|$))[^/]+(?:/(?!\.{1,2}(?:/|$))[^/]+)*)|"
28
- r"media/(?:audio|video|swf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:audio\.[a-z0-9]+|video\.[a-z0-9]+|document\.swf)|"
29
- r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp|gif)/[0-9a-f]{64}/(?:document\.webp|page-manifest\.json|pages/page-[0-9]{6}\.webp)|"
30
- r"native/ebook/chm/[0-9a-f]{64}/document\.epub|"
31
- r"derived/[a-zA-Z0-9._-]+/[a-z0-9]{32}/(?:document\.pdf|page-manifest\.json|pages/page-[0-9]{6}\.webp|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))|"
32
- r"objects/(?P<djvu_prefix>[0-9a-f]{2})/(?P=djvu_prefix)[0-9a-f]{62}/[0-9a-f]{16}/document\.djvu|"
33
- r"objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:reading-manifest\.json|page-map\.json\.gz|text-layer-manifest\.json|text-review-manifest\.json|text/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz|search-[0-9]{6}-[0-9]{6}\.json\.gz|partition-[0-9]{6}-[0-9]{6}-manifest\.json)|preview/(?:page-[0-9]{6}\.(?:png|webp|jpeg|svg|jxl)|partition-[0-9]{6}-[0-9]{6}-manifest\.json))|"
34
- r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl|png)|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|document\.pdf))$"
35
  )
36
- READER_EBOOK_BUCKET = "vomebook/reader-assets-v2"
37
- READER_ALLOWED_BUCKETS = {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}
38
-
39
 
40
- def decode_reader_assets(
41
- raw: bytes,
42
- max_compressed_bytes: int = 5 * 1024 * 1024,
43
- max_decompressed_bytes: int = 50 * 1024 * 1024,
44
- ) -> dict[str, object]:
45
- if len(raw) > max_compressed_bytes:
46
- raise ValueError("reader assets sidecar is too large")
47
- with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:
48
- decoded = stream.read(max_decompressed_bytes + 1)
49
- if len(decoded) > max_decompressed_bytes:
50
- raise ValueError("reader assets sidecar expands beyond limit")
51
- payload: object = json.loads(decoded)
52
- payload_map = cast(dict[str, object], payload) if isinstance(payload, dict) else None
53
- files = payload_map.get("f") if payload_map is not None and payload_map.get("v") == 1 else None
54
- if not isinstance(files, dict):
55
- raise ValueError("invalid reader assets sidecar")
56
- file_map = cast(dict[object, object], files)
57
- clean: dict[str, dict[str, object]] = {}
58
- for key, raw_entry in file_map.items():
59
- if not isinstance(key, str) or not isinstance(raw_entry, dict):
60
- continue
61
- entry = cast(dict[str, object], raw_entry)
62
- if entry.get("s") not in (2, 3, 4):
63
- continue
64
- if entry.get("s") == 2:
65
- path = entry.get("p")
66
- mode = entry.get("m")
67
- if not isinstance(path, str) or not isinstance(mode, str) or mode not in READER_ASSET_FILENAMES:
68
- continue
69
- if entry.get("b") not in READER_ALLOWED_BUCKETS:
70
- continue
71
- path_pattern = READER_BUCKET_PATH_RE
72
- image_page_path = bool(re.fullmatch(r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp)/[0-9a-f]{64}/pages/page-[0-9]{6}\.webp", path))
73
- valid_filename = (posixpath.basename(path) in READER_ASSET_FILENAMES[mode]
74
- or (mode == "i" and image_page_path)
75
- or (mode == "p" and entry.get("b") == "vomebook/pdf-pages-v2"
76
- and path.endswith("/reading-manifest.json")))
77
- if (
78
- not path_pattern.fullmatch(path)
79
- or not valid_filename
80
- ):
81
- continue
82
- chapter_manifest = entry.get("c")
83
- fallback = entry.get("f")
84
- ocr_manifest = entry.get("o")
85
- chapter_bucket = entry.get("cb")
86
- bucket = entry.get("b")
87
- document_path, document_bucket = entry.get("pd"), entry.get("pdb")
88
- if (document_path is not None or document_bucket is not None) and (
89
- mode != "p" or not path.endswith("/page-manifest.json")
90
- or not isinstance(document_bucket, str)
91
- or document_bucket not in READER_ALLOWED_BUCKETS
92
- or not isinstance(document_path, str)
93
- or not READER_BUCKET_PATH_RE.fullmatch(document_path)
94
- or not document_path.endswith("/document.pdf")
95
- ):
96
- continue
97
- if chapter_manifest is not None and (
98
- mode not in {"e", "p"}
99
- or not isinstance(chapter_manifest, str)
100
- or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest)
101
- or not chapter_manifest.endswith("/chapter-manifest.json")
102
- ):
103
- continue
104
- if chapter_manifest is not None and chapter_bucket is None:
105
- continue
106
- if chapter_bucket is not None and (
107
- chapter_bucket != READER_EBOOK_BUCKET or not isinstance(chapter_manifest, str)
108
- or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest)
109
- or not (chapter_manifest.startswith("ebook-chapters/")
110
- or (chapter_bucket == "vomebook/reader-assets-v2"
111
- and chapter_manifest.startswith("chapters/ebook/")))
112
- ):
113
- continue
114
- fallback_is_chm = (bucket == READER_EBOOK_BUCKET and isinstance(fallback, str)
115
- and READER_BUCKET_PATH_RE.fullmatch(fallback)
116
- and fallback.endswith("/document.epub"))
117
- if fallback is not None and not fallback_is_chm:
118
- continue
119
- if ocr_manifest is not None and (
120
- not isinstance(ocr_manifest, str)
121
- or not READER_BUCKET_PATH_RE.fullmatch(ocr_manifest)
122
- or not ocr_manifest.endswith("/ocr-manifest.json")
123
- ):
124
- continue
125
- if entry.get("b") is not None and entry.get("b") not in READER_ALLOWED_BUCKETS:
126
- continue
127
- if entry.get("ob") is not None and entry.get("ob") != "vomebook/pdf-pages-v2":
128
- continue
129
- if bucket == "vomebook/pdf-pages-v2":
130
- if mode == "p" and (not path.endswith(("/page-manifest.json", "/reading-manifest.json", "/document.pdf"))
131
- or not READER_BUCKET_PATH_RE.fullmatch(path)):
132
- continue
133
- clean[key] = {
134
- "s": 2,
135
- "m": mode,
136
- "p": path,
137
- **({"b": bucket} if bucket else {}),
138
- **({"pd": document_path, "pdb": document_bucket} if document_path else {}),
139
- **({"c": chapter_manifest} if chapter_manifest else {}),
140
- **({"cb": chapter_bucket} if chapter_bucket else {}),
141
- **({"f": fallback} if fallback else {}),
142
- **({"o": ocr_manifest} if ocr_manifest else {}),
143
- **({"ob": "vomebook/pdf-pages-v2"} if entry.get("ob") else {}),
144
- **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {}),
145
- }
146
- else:
147
- ocr_manifest = entry.get("o")
148
- if (isinstance(ocr_manifest, str) and READER_BUCKET_PATH_RE.fullmatch(ocr_manifest)
149
- and ocr_manifest.endswith("/ocr-manifest.json")):
150
- clean[key] = {"s": 3, "m": "p", "o": ocr_manifest, "b": "vomebook/pdf-pages-v2",
151
- **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {})}
152
- else:
153
- clean[key] = {"s": 4}
154
- return {"v": 1, "f": clean}
 
1
+ """Compatibility import for backend.reader.catalog.domain.assets."""
2
+ import sys
3
+ from backend.reader.catalog.domain import assets as _implementation
4
+ from backend.reader.catalog.domain.assets import (
5
+ READER_ALLOWED_BUCKETS as READER_ALLOWED_BUCKETS,
6
+ READER_ASSET_FILENAMES as READER_ASSET_FILENAMES,
7
+ READER_ASSET_PATH_RE as READER_ASSET_PATH_RE,
8
+ READER_BUCKET_PATH_RE as READER_BUCKET_PATH_RE,
9
+ READER_EBOOK_BUCKET as READER_EBOOK_BUCKET,
10
+ decode_reader_assets as decode_reader_assets,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  )
 
 
 
12
 
13
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/reader_index.py CHANGED
@@ -1,54 +1,10 @@
1
- """Incremental Reader index construction without publishing partial results."""
2
-
3
- from collections.abc import Callable
4
- from typing import TypedDict, cast
5
-
6
-
7
- class ReaderIndexBuild(TypedDict):
8
- generation: int
9
- records: list[dict[str, object]]
10
- next: int
11
- indices: list[int]
12
- repos: dict[str, list[int]]
13
- keys: dict[str, int]
14
- ids: dict[str, list[int]]
15
- legacy_ids: dict[str, list[int]]
16
-
17
-
18
- def new_build(generation: int, records: list[dict[str, object]]) -> ReaderIndexBuild:
19
- return {"generation": generation, "records": records, "next": 0,
20
- "indices": [], "repos": {}, "keys": {}, "ids": {}, "legacy_ids": {}}
21
-
22
-
23
- def advance_build(build: ReaderIndexBuild, limit: int, deadline: float, *,
24
- now: Callable[[], float], source_id: Callable[[str], str],
25
- asset_key: Callable[[dict[str, object]], str],
26
- record_link: Callable[[dict[str, object]], str],
27
- dataset_url: Callable[[str, str], str],
28
- reader_extensions: frozenset[str]) -> bool:
29
- """Advance at most one batch; callers own generation checks and publication."""
30
- end = min(len(build["records"]), build["next"] + limit)
31
- while build["next"] < end:
32
- idx = build["next"]
33
- rec = build["records"][idx]
34
- repo = rec.get("Repo", "")
35
- build["keys"][asset_key(rec)] = idx
36
- current_url = cast(str, rec.get("Link") or record_link(rec))
37
- build["ids"].setdefault(source_id(current_url), []).append(idx)
38
- # Old links omitted a repeated filename extension; index the historical
39
- # alias without changing the canonical identity or resolving collisions.
40
- name, ext, folders = rec.get("File", ""), rec.get("Extension", ""), rec.get("Folder", [])
41
- if (isinstance(repo, str) and repo.startswith("VoiceOfML/") and isinstance(name, str)
42
- and isinstance(ext, str) and ext and name.lower().endswith("." + ext.lower())
43
- and isinstance(folders, list) and all(isinstance(part, str) for part in cast(list[object], folders))):
44
- legacy_path = "/".join([*cast(list[str], folders), name])
45
- legacy_url = dataset_url(repo, legacy_path)
46
- if legacy_url != (rec.get("Link") or record_link(rec)):
47
- build["legacy_ids"].setdefault(source_id(legacy_url), []).append(idx)
48
- if rec.get("_ext_lower", "") in reader_extensions:
49
- build["indices"].append(idx)
50
- build["repos"].setdefault(cast(str, repo), []).append(idx)
51
- build["next"] += 1
52
- if now() >= deadline:
53
- break
54
- return build["next"] >= len(build["records"])
 
1
+ """Compatibility import for backend.reader.catalog.domain.index."""
2
+ import sys
3
+ from backend.reader.catalog.domain import index as _implementation
4
+ from backend.reader.catalog.domain.index import (
5
+ ReaderIndexBuild as ReaderIndexBuild,
6
+ advance_build as advance_build,
7
+ new_build as new_build,
8
+ )
9
+
10
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/reader_ocr.py CHANGED
@@ -1,165 +1,13 @@
1
- """Bounded PDF text-index validation and original-offset search."""
2
- from __future__ import annotations
3
-
4
- from array import array
5
- import gzip
6
- import io
7
- import json
8
- import re
9
- from typing import NotRequired, TypedDict, cast
10
-
11
-
12
- class OcrSpan(TypedDict):
13
- start: int
14
- end: int
15
- box: list[int | float]
16
-
17
-
18
- class OcrPage(TypedDict):
19
- page: int
20
- text: str
21
- folded: str
22
- fold_map: NotRequired[array[int] | None]
23
- layout: dict[str, object]
24
- spans: list[OcrSpan]
25
-
26
-
27
- class OcrSearchHit(TypedDict):
28
- page: int
29
- start: int
30
- length: int
31
- snippet: str
32
- snippet_start: int
33
- boxes: list[list[int | float]]
34
-
35
-
36
- def fold_reader_ocr_text(text: str) -> tuple[str, array[int] | None]:
37
- """Map casefold-expanded code points back to the source text."""
38
- folded = text.casefold()
39
- if len(folded) == len(text):
40
- return folded, None
41
- pieces: list[str] = []
42
- fold_map: array[int] = array('I')
43
- for index, character in enumerate(text):
44
- piece = character.casefold()
45
- pieces.append(piece)
46
- fold_map.extend([index] * len(piece))
47
- return "".join(pieces), fold_map
48
-
49
-
50
- def parse_reader_ocr_book(raw: bytes, max_bytes: int) -> tuple[list[OcrPage], int]:
51
- """Decode and validate one v2 book index without exceeding its byte limit."""
52
- with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:
53
- decoded = stream.read(max_bytes + 1)
54
- if len(decoded) > max_bytes:
55
- raise ValueError("PDF OCR text index is too large")
56
- payload: object = json.loads(decoded)
57
- if not isinstance(payload, dict):
58
- raise ValueError("invalid PDF OCR text index")
59
- document = cast(dict[str, object], payload)
60
- raw_pages = document.get("pages")
61
- if not isinstance(raw_pages, list):
62
- raise ValueError("invalid PDF OCR text index")
63
- pages = cast(list[object], raw_pages)
64
- if (len(pages) > 200000
65
- or document.get("version") != 2 or document.get("kind") != "pdf-book-text"
66
- or document.get("complete") is not True
67
- or document.get("offset_unit") != "unicode-codepoint"
68
- or document.get("page_count") != len(pages)
69
- or not re.fullmatch(r"[0-9a-f]{64}", str(document.get("source_sha256", "")))):
70
- raise ValueError("invalid PDF OCR text index")
71
- output: list[OcrPage] = []
72
- total_bytes = 0
73
- previous = 0
74
- for raw_page in pages:
75
- if not isinstance(raw_page, dict):
76
- raise ValueError("invalid PDF OCR text page")
77
- item = cast(dict[str, object], raw_page)
78
- number, text = item.get("page"), item.get("text")
79
- if (not isinstance(number, int) or number < 1 or number <= previous
80
- or not isinstance(text, str)):
81
- raise ValueError("invalid PDF OCR text page")
82
- total_bytes += len(text.encode("utf-8"))
83
- if total_bytes > max_bytes:
84
- raise ValueError("PDF OCR text index is too large")
85
- layout, spans = item.get("layout"), item.get("text_spans")
86
- if (not isinstance(layout, dict) or cast(dict[str, object], layout).get("offset_unit") != "unicode-codepoint"
87
- or not isinstance(spans, list)):
88
- raise ValueError("invalid PDF text layout mapping")
89
- previous_span_end = 0
90
- for raw_span in cast(list[object], spans):
91
- if not isinstance(raw_span, dict):
92
- raise ValueError("invalid PDF text span")
93
- span = cast(dict[str, object], raw_span)
94
- start, end, box = span.get("start"), span.get("end"), span.get("box")
95
- if (not isinstance(start, int) or not isinstance(end, int) or start < previous_span_end
96
- or end <= start or end > len(text) or not isinstance(box, list)):
97
- raise ValueError("invalid PDF text span")
98
- values = cast(list[object], box)
99
- if len(values) != 4 or any(not isinstance(value, (int, float)) or value < 0 or value > 1
100
- for value in values):
101
- raise ValueError("invalid PDF text span")
102
- previous_span_end = end
103
- folded, fold_map = fold_reader_ocr_text(text)
104
- if fold_map is not None:
105
- total_bytes += len(fold_map) * fold_map.itemsize
106
- output.append({"page": number, "text": text, "folded": folded, "fold_map": fold_map,
107
- "layout": cast(dict[str, object], layout), "spans": cast(list[OcrSpan], spans)})
108
- previous = number
109
- return output, total_bytes
110
-
111
-
112
- def search_reader_ocr_pages(
113
- pages: list[OcrPage], needle: str, page: int, page_size: int
114
- ) -> tuple[int, list[OcrSearchHit]]:
115
- """Count all non-overlapping matches; return one page in original offsets."""
116
- offset = (page - 1) * page_size
117
- end_offset = offset + page_size
118
- folded_length = len(needle)
119
- total = 0
120
- results: list[OcrSearchHit] = []
121
- if not folded_length:
122
- return total, results
123
- # Once the requested page is full, only the remaining count is needed.
124
- # Exact built-ins keep custom string methods and unusual callers on the
125
- # existing per-match path, including their errors and side effects.
126
- count_safe = type(needle) is str and type(page) is int and type(page_size) is int and page_size > 0
127
- for item in pages:
128
- text, folded = item["text"], item["folded"]
129
- if "fold_map" in item:
130
- fold_map = item["fold_map"]
131
- elif len(folded) == len(text):
132
- fold_map = None
133
- else:
134
- folded, fold_map = fold_reader_ocr_text(text)
135
- if count_safe and len(results) == page_size and type(folded) is str:
136
- total += folded.count(needle)
137
- continue
138
- start = 0
139
- while True:
140
- found = folded.find(needle, start)
141
- if found < 0:
142
- break
143
- match_index = total
144
- total += 1
145
- if offset <= match_index < end_offset:
146
- if fold_map is None:
147
- original_start, original_end = found, found + folded_length
148
- else:
149
- original_start = fold_map[found]
150
- original_end = fold_map[found + folded_length - 1] + 1
151
- snippet_start = max(0, original_start - 72)
152
- snippet_end = min(len(text), original_end + 88)
153
- boxes = [span["box"] for span in item["spans"]
154
- if span["end"] > original_start and span["start"] < original_end]
155
- results.append({
156
- "page": item["page"], "start": original_start,
157
- "length": original_end - original_start,
158
- "snippet": text[snippet_start:snippet_end],
159
- "snippet_start": original_start - snippet_start, "boxes": boxes,
160
- })
161
- if count_safe and len(results) == page_size and type(folded) is str:
162
- total += folded.count(needle, found + folded_length)
163
- break
164
- start = found + folded_length
165
- return total, results
 
1
+ """Compatibility import for backend.reader.query.domain.ocr."""
2
+ import sys
3
+ from backend.reader.query.domain import ocr as _implementation
4
+ from backend.reader.query.domain.ocr import (
5
+ OcrPage as OcrPage,
6
+ OcrSearchHit as OcrSearchHit,
7
+ OcrSpan as OcrSpan,
8
+ fold_reader_ocr_text as fold_reader_ocr_text,
9
+ parse_reader_ocr_book as parse_reader_ocr_book,
10
+ search_reader_ocr_pages as search_reader_ocr_pages,
11
+ )
12
+
13
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/reader_range_cache.py CHANGED
@@ -1,67 +1,12 @@
1
- """Safe exact-byte subrange reuse for the Reader proxy's bounded cache."""
2
- from __future__ import annotations
3
-
4
- from collections import OrderedDict
5
- from collections.abc import Callable
6
- from typing import Protocol
7
- import re
8
-
9
- RangeKey = tuple[str, str, int | None, str | None]
10
- RangeCacheEntry = tuple[float, bytes, dict[str, str]]
11
-
12
-
13
- class RangeCacheState(Protocol):
14
- reader_range_cache: OrderedDict[RangeKey, RangeCacheEntry]
15
- reader_range_cache_bytes: int
16
-
17
-
18
- def requested_range_bounds(header: str | None, total: int) -> tuple[int, int] | None:
19
- """Resolve an ordinary single byte range; unknown/unsatisfiable forms return None."""
20
- if header is None or total <= 0:
21
- return None
22
- match = re.fullmatch(r"bytes=([0-9]{0,20})-([0-9]{0,20})", header)
23
- if match is None:
24
- return None
25
- first, last = match.groups()
26
- if not first:
27
- if not last or int(last) == 0:
28
- return None
29
- return max(0, total - int(last)), total - 1
30
- start = int(first)
31
- end = min(int(last), total - 1) if last else total - 1
32
- if start > end:
33
- return None
34
- return start, end
35
-
36
-
37
- def cached_subrange(range_key: RangeKey, get_state: Callable[[], RangeCacheState],
38
- get_limit: Callable[[], int], get_ttl: Callable[[], int],
39
- now: Callable[[], float]) -> tuple[bytes, dict[str, str]] | None:
40
- """Serve a verified contained range, evicting stale entries in LRU order."""
41
- requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_key[1])
42
- if requested is None:
43
- return None
44
- start, end = (int(value) for value in requested.groups())
45
- if start > end or end - start + 1 > get_limit():
46
- return None
47
- cache = get_state().reader_range_cache
48
- current_time = now()
49
- for key in reversed(list(cache)):
50
- cached_at, payload, headers = cache[key]
51
- if current_time - cached_at >= get_ttl():
52
- cache.pop(key)
53
- get_state().reader_range_cache_bytes -= len(payload)
54
- continue
55
- if key[0] != range_key[0] or key[2:] != range_key[2:]:
56
- continue
57
- match = re.fullmatch(r"bytes ([0-9]+)-([0-9]+)/([0-9]+)", headers.get("Content-Range", ""))
58
- if match is None:
59
- continue
60
- cached_start, cached_end, total = (int(value) for value in match.groups())
61
- final_end = min(end, total - 1)
62
- if cached_start <= start <= final_end <= cached_end and len(payload) == cached_end - cached_start + 1:
63
- cache.move_to_end(key)
64
- body = payload[start - cached_start:final_end - cached_start + 1]
65
- return body, {**headers, "Content-Range": f"bytes {start}-{final_end}/{total}",
66
- "Content-Length": str(len(body))}
67
- return None
 
1
+ """Compatibility import for backend.reader.document.domain.range_cache."""
2
+ import sys
3
+ from backend.reader.document.domain import range_cache as _implementation
4
+ from backend.reader.document.domain.range_cache import (
5
+ RangeCacheEntry as RangeCacheEntry,
6
+ RangeCacheState as RangeCacheState,
7
+ RangeKey as RangeKey,
8
+ cached_subrange as cached_subrange,
9
+ requested_range_bounds as requested_range_bounds,
10
+ )
11
+
12
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/reader_v3_catalog.py CHANGED
@@ -1,161 +1,18 @@
1
- """Pinned v3 catalog projection, using only canonical bucket metadata URLs."""
2
- import asyncio
3
- import hashlib
4
- import json
5
- import re
6
- from typing import Callable, Literal, ParamSpec, TypeVar, cast, overload
7
-
8
- import aiohttp
9
-
10
- from backend.upstream_http import open_download_response, validate_fixed_source_redirect_url
11
-
12
- BUCKET = "vomebook/reader-assets-v2"
13
- BASE = f"https://huggingface.co/buckets/{BUCKET}/resolve/"
14
- POINTER = "reader-index/v3/current.json"
15
- MAX_BYTES = 8 * 1024 * 1024
16
-
17
-
18
- def sha(value: object) -> re.Match[str] | bool | None:
19
- return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value)
20
-
21
-
22
- def catalog_path(generation: object) -> str:
23
- if not sha(generation):
24
- raise ValueError("invalid v3 catalog generation")
25
- return f"reader-index/v3/generations/{generation}/catalog.json"
26
-
27
-
28
- def decode_catalog(pointer: dict[str, object], raw: bytes) -> dict[str, object]:
29
- from backend.reader_assets import READER_BUCKET_PATH_RE
30
- if pointer.get("version") != 1 or pointer.get("kind") != "reader-reading-pointer":
31
- raise ValueError("invalid v3 pointer")
32
- generation = pointer.get("generation")
33
- ref = cast(dict[str, object], pointer.get("catalog", {}))
34
- if (ref.get("bucket") != BUCKET or ref.get("path") != catalog_path(generation)
35
- or ref.get("role") != "runtime" or type(ref.get("bytes")) is not int
36
- or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES or not sha(ref.get("sha256"))
37
- or len(raw) != ref["bytes"] or hashlib.sha256(raw).hexdigest() != ref["sha256"]):
38
- raise ValueError("v3 catalog resource mismatch")
39
- catalog = cast(dict[str, object], json.loads(raw))
40
- body = {k: v for k, v in catalog.items() if k != "generation"}
41
- digest = hashlib.sha256(json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
42
- allow_nan=False).encode()).hexdigest()
43
- if (catalog.get("version") != 3 or catalog.get("kind") != "reader-reading-catalog"
44
- or catalog.get("generation") != generation or digest != generation
45
- or not isinstance(catalog.get("files"), dict)):
46
- raise ValueError("invalid v3 catalog identity")
47
- overrides: dict[str, dict[str, object]] = {}
48
- for key, raw_entry in cast(dict[object, object], catalog["files"]).items():
49
- if not isinstance(key, str) or not key or not isinstance(raw_entry, dict):
50
- raise ValueError("invalid v3 source key")
51
- entry = cast(dict[str, object], raw_entry)
52
- resource = cast(dict[str, object], entry.get("resource", {}))
53
- source = entry.get("source_sha256")
54
- path = resource.get("path", "")
55
- if (not isinstance(source, str) or not sha(source) or not sha(entry.get("reading_generation"))
56
- or resource.get("bucket") != "vomebook/pdf-pages-v2" or resource.get("role") != "runtime"
57
- or not isinstance(path, str) or not READER_BUCKET_PATH_RE.fullmatch(path)
58
- or not path.startswith(f"objects/{source[:2]}/{source}/")
59
- or not path.endswith("/reading-manifest.json") or not sha(resource.get("sha256"))
60
- or type(resource.get("bytes")) is not int or cast(int, resource["bytes"]) < 1):
61
- raise ValueError("invalid v3 reading reference")
62
- overrides[key] = {"s": 2, "m": "p", "p": path, "b": resource["bucket"]}
63
- return {"generation": generation, "catalog_sha256": ref["sha256"],
64
- "files": overrides, "catalog": ref,
65
- **({"base_sidecar_ref": catalog["base_sidecar"]} if catalog.get("base_sidecar") else {})}
66
-
67
-
68
- def validate_base_ref(ref: object) -> dict[str, object]:
69
- if not isinstance(ref, dict):
70
- raise ValueError("invalid unified base sidecar")
71
- ref = cast(dict[str, object], ref)
72
- if (ref.get("bucket") != BUCKET or ref.get("role") != "runtime"
73
- or not sha(ref.get("sha256")) or ref.get("path") !=
74
- f"reader-index/snapshots/{ref['sha256']}/reader_assets.json.gz"
75
- or type(ref.get("bytes")) is not int or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES):
76
- raise ValueError("invalid unified base sidecar")
77
- return ref
78
-
79
-
80
- _DecodeParams = ParamSpec("_DecodeParams")
81
- _DecodeResult = TypeVar("_DecodeResult")
82
-
83
-
84
- async def decode_in_thread(func: Callable[_DecodeParams, _DecodeResult],
85
- *args: _DecodeParams.args, **kwargs: _DecodeParams.kwargs) -> _DecodeResult:
86
- # Keep the refresh owner alive until its worker exits even after cancellation.
87
- # Otherwise a subsequent refresh could start another large decode while the
88
- # abandoned worker still holds its inputs and intermediate objects.
89
- task = asyncio.create_task(asyncio.to_thread(func, *args, **kwargs))
90
- try:
91
- return await asyncio.shield(task)
92
- except asyncio.CancelledError:
93
- while not task.done():
94
- try:
95
- await asyncio.shield(task)
96
- except asyncio.CancelledError:
97
- continue
98
- except Exception:
99
- break
100
- if not task.cancelled():
101
- task.exception() # Retrieve a worker failure without replacing cancellation.
102
- raise
103
-
104
-
105
- async def load_reading_catalog(session: object) -> dict[str, object] | None:
106
- @overload
107
- async def fetch(path: str, *, missing: Literal[True]) -> bytes | None: ...
108
-
109
- @overload
110
- async def fetch(path: str, *, missing: Literal[False] = False) -> bytes: ...
111
-
112
- async def fetch(path: str, *, missing: bool = False) -> bytes | None:
113
- source_url = BASE + path
114
- # Validate every redirect hop against the fixed URL or signed storage;
115
- # metadata is mutable, so its signed targets are never reused.
116
- response = await open_download_response(
117
- session, source_url, aiohttp.ClientTimeout(total=20, connect=8, sock_read=10),
118
- request_headers={"Cache-Control": "no-cache"},
119
- url_validator=lambda url: validate_fixed_source_redirect_url(url, source_url),
120
- cache_redirects=False,
121
- )
122
- try:
123
- if missing and response.status == 404:
124
- return None
125
- if response.status != 200:
126
- raise RuntimeError(f"v3 metadata HTTP {response.status}")
127
- raw = bytearray()
128
- async for chunk in response.content.iter_chunked(64 * 1024):
129
- raw.extend(chunk)
130
- if len(raw) > MAX_BYTES:
131
- raise ValueError("v3 metadata exceeds limit")
132
- return bytes(raw)
133
- finally:
134
- response.release()
135
- raw = await fetch(POINTER, missing=True)
136
- if raw is None:
137
- return None
138
- pointer = cast(dict[str, object], json.loads(raw))
139
- # Validate the exact fixed catalog path before starting another request.
140
- path = catalog_path(pointer.get("generation"))
141
- if cast(dict[str, object], pointer.get("catalog", {})).get("path") != path:
142
- raise ValueError("v3 pointer path mismatch")
143
- catalog = await fetch(path)
144
- result = await decode_in_thread(decode_catalog, pointer, catalog)
145
- if result.get("base_sidecar_ref"):
146
- ref = validate_base_ref(result["base_sidecar_ref"])
147
- packed = await fetch(cast(str, ref["path"]))
148
- if len(packed) != ref["bytes"] or hashlib.sha256(packed).hexdigest() != ref["sha256"]:
149
- raise ValueError("unified base sidecar checksum mismatch")
150
- from backend.reader_assets import decode_reader_assets
151
- result["base_sidecar"] = await decode_in_thread(decode_reader_assets, packed)
152
- return result
153
-
154
-
155
- def merge_sidecar(base: dict[str, object], catalog: dict[str, object] | None) -> dict[str, object]:
156
- if not catalog:
157
- return base
158
- base = cast(dict[str, object], catalog.get("base_sidecar", base))
159
- return {**base, "f": {**cast(dict[str, object], base["f"]), **cast(dict[str, object], catalog["files"])},
160
- "v3": {"generation": catalog["generation"], "catalog_sha256": catalog["catalog_sha256"],
161
- "files": len(cast(dict[str, object], catalog["files"]))}}
 
1
+ """Compatibility import for backend.reader.catalog.infrastructure.v3."""
2
+ import sys
3
+ from backend.reader.catalog.infrastructure import v3 as _implementation
4
+ from backend.reader.catalog.infrastructure.v3 import (
5
+ BASE as BASE,
6
+ BUCKET as BUCKET,
7
+ MAX_BYTES as MAX_BYTES,
8
+ POINTER as POINTER,
9
+ catalog_path as catalog_path,
10
+ decode_catalog as decode_catalog,
11
+ decode_in_thread as decode_in_thread,
12
+ load_reading_catalog as load_reading_catalog,
13
+ merge_sidecar as merge_sidecar,
14
+ sha as sha,
15
+ validate_base_ref as validate_base_ref,
16
+ )
17
+
18
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/record_metadata.py CHANGED
@@ -1,185 +1,23 @@
1
- """Pure record paths and reader projections shared by search and reader APIs."""
2
- import posixpath
3
- import re
4
- from typing import cast
5
- from urllib.parse import quote
6
-
7
-
8
- READER_ASSET_MODES = {
9
- "p": "pdf", "e": "epub", "d": "docx", "h": "html",
10
- "t": "txt", "k": "md", "i": "webp", "a": "audio", "v": "video", "f": "swf",
11
- }
12
- READER_NATIVE_FOLIATE_EXTENSIONS = frozenset({"epub", "mobi", "azw", "azw3", "fb2"})
13
-
14
-
15
- def build_record_relative_path(rec: dict[str, object]) -> str:
16
- file_name = cast(str, rec.get("File", ""))
17
- extension = cast(str, rec.get("Extension", ""))
18
- full_name = f"{file_name}.{extension}" if extension else file_name
19
- folders = cast(list[str], rec.get("Folder", []) or [])
20
- return posixpath.join(*folders, full_name) if folders else full_name
21
-
22
-
23
- def build_reader_asset_key(rec: dict[str, object]) -> str:
24
- return f"{rec.get('Repo', '')}\0{build_record_relative_path(rec)}"
25
-
26
-
27
- def dataset_file_url(repo: str, relative_path: str, action: str = "resolve") -> str:
28
- return f"https://huggingface.co/datasets/{repo}/{action}/main/{quote(relative_path, safe='/')}"
29
-
30
-
31
- def dataset_file_urls(repo: str, relative_path: str) -> tuple[str, str]:
32
- """Produce source and browser URLs using the same encoded path."""
33
- encoded = quote(relative_path, safe="/")
34
- prefix = f"https://huggingface.co/datasets/{repo}"
35
- return f"{prefix}/resolve/main/{encoded}", f"{prefix}/blob/main/{encoded}"
36
-
37
-
38
- def build_record_link(rec: dict[str, object]) -> str:
39
- return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec))
40
-
41
-
42
- def build_record_path_url(rec: dict[str, object]) -> str:
43
- return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec), "blob")
44
-
45
-
46
- def build_browser_file_name(file_item: dict[str, object]) -> str:
47
- name = str(file_item.get("name", "") or "file")
48
- ext = str(file_item.get("ext", "") or "")
49
- # Browser metadata stores the source record's stem and last extension in
50
- # separate fields; a repeated suffix in the stem is still significant.
51
- if not ext:
52
- return name
53
- return f"{name}.{ext}"
54
-
55
-
56
- def enrich_browser_entry(repo: str, path: str, entry: dict[str, object]) -> dict[str, object]:
57
- decoded = dict(entry or {})
58
- decoded["current_path"] = decoded.get("current_path", path)
59
- folders: list[dict[str, object]] = []
60
- for folder in cast(list[dict[str, object]], decoded.get("folders", []) or []):
61
- item = dict(folder)
62
- if "path" not in item:
63
- name = item.get("name", "")
64
- item["path"] = f"{path}/{name}" if path else name
65
- folders.append(item)
66
- files: list[dict[str, object]] = []
67
- for file_item in cast(list[dict[str, object]], decoded.get("files", []) or []):
68
- item = dict(file_item)
69
- full_name = build_browser_file_name(item)
70
- rel_path = f"{path}/{full_name}" if path else full_name
71
- if not item.get("link") and not item.get("path"):
72
- item["link"], item["path"] = dataset_file_urls(repo, rel_path)
73
- else:
74
- item["link"] = item.get("link") or dataset_file_url(repo, rel_path)
75
- item["path"] = item.get("path") or dataset_file_url(repo, rel_path, "blob")
76
- files.append(item)
77
- decoded["folders"] = folders
78
- decoded["files"] = files
79
- return decoded
80
-
81
-
82
- def reader_asset_url(asset: dict[str, object]) -> str:
83
- path = quote(str(asset.get("p") or ""), safe="/")
84
- return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + path
85
-
86
-
87
- def reader_extension_for_asset(asset: dict[str, object], original_extension: str = "") -> str:
88
- asset_path = str(asset.get("p") or "")
89
- if asset.get('c'):
90
- return 'epub-chapters'
91
- if asset_path.endswith(("page-manifest.json", "reading-manifest.json")):
92
- return "image-pages" if asset.get("m") == "i" else "pdf-pages"
93
- if asset.get("m") == "e":
94
- match = re.search(r"/(?:document|book)\.(epub|mobi|azw|azw3|fb2)$", asset_path, re.IGNORECASE)
95
- if match:
96
- return match.group(1).lower()
97
- extension = str(original_extension or "").lower().lstrip(".")
98
- return extension if extension in READER_NATIVE_FOLIATE_EXTENSIONS else "epub"
99
- mode = asset.get("m")
100
- return READER_ASSET_MODES.get(mode, "") if isinstance(mode, str) else ""
101
-
102
-
103
- def _reader_bucket_url(path: str) -> str:
104
- return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + quote(path, safe="/")
105
-
106
-
107
- def reader_asset_fields(asset: dict[str, object], original_extension: str) -> dict[str, str]:
108
- ocr_path = str(asset.get("o") or "")
109
- ocr_bucket = asset.get("b") == "vomebook/pdf-pages-v2" or asset.get("ob") == "vomebook/pdf-pages-v2"
110
- fields: dict[str, str] = {}
111
- if ocr_path.endswith("/ocr-manifest.json") and ocr_bucket:
112
- fields["ocr_manifest"] = _reader_bucket_url(ocr_path)
113
- fields["ocr_mode"] = str(asset.get("om") or "")
114
- if asset.get("s") == 3:
115
- return fields
116
- if asset.get("s") != 2 or asset.get("m") not in READER_ASSET_MODES or not asset.get("p"):
117
- return fields
118
- if str(original_extension).lower().lstrip('.') == 'djvu':
119
- # Existing OCR remains independent. Native DjVu reading starts at the
120
- # dataset source, never an older image stream, manifest or derivative.
121
- return fields
122
- if (asset.get('m') == 'p' and not asset.get('c') and str(asset['p']).endswith('/page-manifest.json')
123
- and str(original_extension).lower().lstrip('.') != 'djvu'):
124
- # Legacy page indexes no longer own PDF/converted-PDF reading. Keep
125
- # independent OCR metadata and prefer the validated PDF companion.
126
- if asset.get('pd') and asset.get('pdb') in {'vomebook/reader-assets-v2', 'vomebook/pdf-pages-v2'}:
127
- fields.update(url=_reader_bucket_url(cast(str, asset['pd'])), extension='pdf')
128
- return fields
129
- fields.update({"url": reader_asset_url(asset), "extension": reader_extension_for_asset(asset, original_extension)})
130
- if asset.get("pd") and asset.get("pdb") in {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}:
131
- fields["pdf_document"] = _reader_bucket_url(cast(str, asset["pd"]))
132
- if asset.get("c"):
133
- if asset.get("cb") == "vomebook/reader-assets-v2":
134
- fields["chapter_manifest"] = _reader_bucket_url(cast(str, asset["c"]))
135
- elif asset.get("cb") == "vomebook/pdf-pages-v2":
136
- fields["chapter_manifest"] = "/api/reader-bucket-resource?path=" + quote(cast(str, asset["c"]), safe="/")
137
- return fields
138
-
139
-
140
- def enrich_reader_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]:
141
- result = dict(record)
142
- fields = reader_asset_fields(asset, cast(str, record.get("Extension", "")))
143
- direct_modes = {
144
- "pdf": ("pdf", "pdf"), "djvu": ("djvu", "pdf"), "vcf": ("vcf", "text"), "ini": ("ini", "text"),
145
- "tif": ("image", "image"), "tiff": ("image", "image"),
146
- }
147
- direct_extension = str(record.get("Extension") or "").lower().lstrip(".")
148
- if 'url' not in fields and direct_extension in direct_modes:
149
- # A PDF without a converted/page asset remains directly readable from
150
- # its immutable source dataset after the derived asset store changes.
151
- fields.update(url=cast(str, record.get("Link") or build_record_link(record)),
152
- extension=direct_modes[direct_extension][0])
153
- if fields:
154
- for source, target in (("url", "ReaderLink"), ("extension", "ReaderExtension"),
155
- ("chapter_manifest", "ReaderChapterManifest"),
156
- ("ocr_manifest", "ReaderOcrManifest"), ("ocr_mode", "ReaderOcrMode"),
157
- ("pdf_document", "ReaderPdfDocument")):
158
- if source in fields:
159
- result[target] = fields[source]
160
- result["DownloadLink"] = record.get("Link") or build_record_link(record)
161
- return result
162
-
163
-
164
- def add_reader_assets(payload: dict[str, object], assets: dict[str, object]) -> dict[str, object]:
165
- files = cast(dict[str, dict[str, object]], assets.get("f", {}))
166
- return {**payload, "results": [
167
- enrich_reader_record(record, files.get(build_reader_asset_key(record), {}))
168
- for record in cast(list[dict[str, object]], payload.get("results", []))
169
- ]}
170
-
171
-
172
- def reader_resolved_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]:
173
- source = record.get("Link") or build_record_link(record)
174
- extension = str(record.get("Extension") or "").lower().lstrip(".")
175
- repo = cast(str, record.get("Repo", "")).split("/")[-1]
176
- folders = [str(item) for item in cast(list[object], record.get("Folder", []))]
177
- return {
178
- "url": source, "download": source, "extension": extension,
179
- "original_extension": extension, "title": record.get("File") or record.get("Name") or "在线阅读",
180
- # Keep the exact indexed filename separate from the display title.
181
- # The stem may itself end in an extension, or include trailing spaces.
182
- "filename": build_record_relative_path(record).rsplit("/", 1)[-1],
183
- "path": "/".join([repo, *folders]), "folder": "/".join(folders), "repo": repo,
184
- **reader_asset_fields(asset, extension),
185
- }
 
1
+ """Compatibility import for backend.search.corpus.domain.records."""
2
+ import sys
3
+ from backend.search.corpus.domain import records as _implementation
4
+ from backend.search.corpus.domain.records import (
5
+ READER_ASSET_MODES as READER_ASSET_MODES,
6
+ READER_NATIVE_FOLIATE_EXTENSIONS as READER_NATIVE_FOLIATE_EXTENSIONS,
7
+ add_reader_assets as add_reader_assets,
8
+ build_browser_file_name as build_browser_file_name,
9
+ build_reader_asset_key as build_reader_asset_key,
10
+ build_record_link as build_record_link,
11
+ build_record_path_url as build_record_path_url,
12
+ build_record_relative_path as build_record_relative_path,
13
+ dataset_file_url as dataset_file_url,
14
+ dataset_file_urls as dataset_file_urls,
15
+ enrich_browser_entry as enrich_browser_entry,
16
+ enrich_reader_record as enrich_reader_record,
17
+ reader_asset_fields as reader_asset_fields,
18
+ reader_asset_url as reader_asset_url,
19
+ reader_extension_for_asset as reader_extension_for_asset,
20
+ reader_resolved_record as reader_resolved_record,
21
+ )
22
+
23
+ sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/runtime/application/lifecycle.py CHANGED
@@ -9,8 +9,8 @@ from typing import Any, Literal, Protocol
9
  import aiohttp
10
 
11
  from backend.reader.document.application.ranges import RangeFlightState
12
- from backend.reader_range_cache import RangeCacheState
13
- from backend.search_execution import SearchExecutor
14
 
15
 
16
  class LifecycleState(RangeCacheState, RangeFlightState, Protocol):
 
9
  import aiohttp
10
 
11
  from backend.reader.document.application.ranges import RangeFlightState
12
+ from backend.reader.document.domain.range_cache import RangeCacheState
13
+ from backend.search.infrastructure.executor import SearchExecutor
14
 
15
 
16
  class LifecycleState(RangeCacheState, RangeFlightState, Protocol):
backend/search/application/bootstrap.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed construction of initial search pages from caller-owned state."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Callable, Iterable, Mapping, Sequence
5
+
6
+ SearchRecord = dict[str, object]
7
+
8
+
9
+ def trim_initial_results(raw: Iterable[SearchRecord]) -> list[SearchRecord]:
10
+ return [{"Repo": record.get("Repo", ""), "File": record.get("File", ""),
11
+ "Extension": record.get("Extension", ""), "Folder": record.get("Folder", []),
12
+ "Size": record.get("Size", ""), "HasTxt": record.get("HasTxt", "")} for record in raw]
13
+
14
+
15
+ def build_initial_payload(repo: str | None, get_page_size: Callable[[], int],
16
+ get_repos: Callable[[], Mapping[str, Sequence[int]]],
17
+ get_records: Callable[[], Sequence[SearchRecord]],
18
+ get_trim: Callable[[], Callable[[Sequence[SearchRecord]], list[SearchRecord]]],
19
+ get_generation: Callable[[], Callable[[], str]]) -> dict[str, object]:
20
+ """Preserve snapshot lookup, projection and generation evaluation order."""
21
+ if repo:
22
+ indices = get_repos().get(repo, [])
23
+ result_records = [get_records()[index] for index in indices[:get_page_size()]]
24
+ mode = "repo"
25
+ total = len(indices)
26
+ else:
27
+ result_records = get_records()[:get_page_size()]
28
+ mode = "global"
29
+ total = len(get_records())
30
+ return {"mode": mode, "repo": repo, "sort": "relevance", "page": 1, "page_size": get_page_size(),
31
+ "total": total, "results": get_trim()(result_records), "generation": get_generation()()}
backend/search/corpus/application/preparation.py CHANGED
@@ -8,8 +8,8 @@ from collections.abc import Callable, Iterable
8
  from dataclasses import dataclass
9
  from pathlib import Path
10
 
11
- from backend.data_formats import CompactTreeNode, CompactBrowserEntry
12
- from backend.search_indexes import PostingIndex
13
  from backend.search.corpus.domain.metadata import Record
14
 
15
  Tree = dict[str, list[Record]]
 
8
  from dataclasses import dataclass
9
  from pathlib import Path
10
 
11
+ from backend.search.corpus.domain.formats import CompactTreeNode, CompactBrowserEntry
12
+ from backend.search.corpus.infrastructure.indexes import PostingIndex
13
  from backend.search.corpus.domain.metadata import Record
14
 
15
  Tree = dict[str, list[Record]]
backend/search/corpus/domain/folder_contents.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Directory browser lookup against a caller-owned search index snapshot."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Callable, Mapping, Sequence
5
+ from typing import cast
6
+
7
+ SearchRecord = dict[str, object]
8
+ BrowserEntries = Mapping[str, Mapping[str, SearchRecord]]
9
+ FolderIndex = Mapping[str, Mapping[str, Sequence[int]]]
10
+ RepoIndices = Mapping[str, Sequence[int]]
11
+
12
+
13
+ def get_folder_contents(repo: str, path: str, *,
14
+ get_browser: Callable[[], BrowserEntries],
15
+ get_folder_index: Callable[[], FolderIndex],
16
+ get_repo_indices: Callable[[], RepoIndices],
17
+ get_records: Callable[[], Sequence[SearchRecord]],
18
+ enrich_browser_entry: Callable[[str, str, SearchRecord], SearchRecord],
19
+ build_record_link: Callable[[SearchRecord], str],
20
+ build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord:
21
+ """Prefer precomputed entries, otherwise count and project the indexed subtree."""
22
+ if repo in get_browser():
23
+ repo_browser = get_browser().get(repo, {}) or {}
24
+ if path in repo_browser:
25
+ return enrich_browser_entry(repo, path, repo_browser[path])
26
+ if path == "" and "" in repo_browser:
27
+ return enrich_browser_entry(repo, path, repo_browser[""])
28
+ return _from_index(repo, path, get_folder_index, get_repo_indices, get_records,
29
+ build_record_link, build_record_path_url)
30
+
31
+
32
+ def _from_index(repo: str, path: str, get_folder_index: Callable[[], FolderIndex],
33
+ get_repo_indices: Callable[[], RepoIndices], get_records: Callable[[], Sequence[SearchRecord]],
34
+ build_record_link: Callable[[SearchRecord], str],
35
+ build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord:
36
+ path_parts = [p for p in path.strip("/").split("/") if p]
37
+ path_depth = len(path_parts)
38
+ repo_folders = get_folder_index().get(repo)
39
+ candidate_indices = (repo_folders.get("/".join(path_parts), [])
40
+ if repo_folders is not None else get_repo_indices().get(repo, []))
41
+
42
+ def is_under(rec_folders: list[str], prefix: list[str]) -> bool:
43
+ return rec_folders[:len(prefix)] == prefix
44
+ matching = [get_records()[i] for i in candidate_indices
45
+ if is_under(cast(list[str], get_records()[i].get("Folder", []) or []), path_parts)]
46
+ result_folders = _subfolder_results(matching, path_parts, path_depth)
47
+ direct_files = _direct_file_results(matching, path_depth, build_record_link, build_record_path_url)
48
+ return {"folders": result_folders, "files": direct_files, "current_path": path}
49
+
50
+
51
+ def _subfolder_results(matching: Sequence[SearchRecord], path_parts: list[str],
52
+ path_depth: int) -> list[SearchRecord]:
53
+ subfolder_names: set[str] = set()
54
+ subfolder_counts: dict[str, int] = {}
55
+ for rec in matching:
56
+ folders = cast(list[str], rec.get("Folder", []) or [])
57
+ if len(folders) > path_depth:
58
+ name = folders[path_depth]
59
+ subfolder_names.add(name)
60
+ subfolder_counts[name] = subfolder_counts.get(name, 0) + 1
61
+ result_folders: list[SearchRecord] = []
62
+ for fname in sorted(subfolder_names):
63
+ full_path = "/".join(path_parts + [fname]) if path_parts else fname
64
+ result_folders.append({"name": fname, "path": full_path, "count": subfolder_counts.get(fname, 0)})
65
+ return result_folders
66
+
67
+
68
+ def _direct_file_results(matching: Sequence[SearchRecord], path_depth: int,
69
+ build_record_link: Callable[[SearchRecord], str],
70
+ build_record_path_url: Callable[[SearchRecord], str]) -> list[SearchRecord]:
71
+ direct_files: list[SearchRecord] = []
72
+ for rec in matching:
73
+ folders = cast(list[str], rec.get("Folder", []) or [])
74
+ if len(folders) == path_depth:
75
+ direct_files.append({
76
+ "name": rec.get("File", ""),
77
+ "ext": rec.get("Extension", ""),
78
+ "link": rec.get("Link") or build_record_link(rec),
79
+ "path": rec.get("Path") or build_record_path_url(rec),
80
+ "hasTxt": rec.get("HasTxt", False),
81
+ "size": rec.get("Size", ""),
82
+ })
83
+ direct_files.sort(key=lambda f: cast(str, f["name"]))
84
+ return direct_files
backend/search/corpus/domain/folder_tree.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build search filter trees from a caller-owned index snapshot."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Mapping, Sequence
5
+ from typing import NotRequired, TypedDict, cast
6
+
7
+
8
+ class FolderTreeNode(TypedDict):
9
+ name: str
10
+ path: str
11
+ children: list[FolderTreeNode]
12
+ count: int
13
+ hasDirectFiles: bool
14
+ hasChildren: bool
15
+ showSelfToggle: bool
16
+ isRoot: NotRequired[bool]
17
+
18
+
19
+ def build_folder_tree(repo: str, folder_index: Mapping[str, Mapping[str, Sequence[int]]],
20
+ repo_records_map: Mapping[str, Sequence[int]],
21
+ records: Sequence[dict[str, object]]) -> list[FolderTreeNode]:
22
+ """Preserve corpus counts, stable child order and direct-file toggles."""
23
+ if repo not in folder_index:
24
+ return []
25
+ repo_name_short = repo.split("/")[-1]
26
+ tree_root: FolderTreeNode = {
27
+ "name": repo_name_short,
28
+ "path": "",
29
+ "children": [],
30
+ "count": 0,
31
+ "hasDirectFiles": False,
32
+ "hasChildren": False,
33
+ "showSelfToggle": False,
34
+ "isRoot": True,
35
+ }
36
+ node_map: dict[str, FolderTreeNode] = {"": tree_root}
37
+ for path, idx_list in folder_index[repo].items():
38
+ if path == "":
39
+ tree_root["count"] = len(idx_list)
40
+ continue
41
+ parts = path.split("/")
42
+ for depth in range(1, len(parts) + 1):
43
+ key = "/".join(parts[:depth])
44
+ if key not in node_map:
45
+ parent_key = "/".join(parts[:depth - 1]) if depth > 1 else ""
46
+ parent = node_map[parent_key]
47
+ node: FolderTreeNode = {
48
+ "name": parts[depth - 1],
49
+ "path": key,
50
+ "children": [],
51
+ "count": 0,
52
+ "hasDirectFiles": False,
53
+ "hasChildren": False,
54
+ "showSelfToggle": False,
55
+ }
56
+ node_map[key] = node
57
+ parent["children"].append(node)
58
+ node_map[path]["count"] = len(idx_list)
59
+ direct_file_dirs: set[str] = set()
60
+ for idx in repo_records_map.get(repo, []):
61
+ rec = records[idx]
62
+ folders = cast(list[str], rec.get("Folder", []) or [])
63
+ direct_file_dirs.add("/".join(folders))
64
+ for path_key, node in node_map.items():
65
+ node["hasDirectFiles"] = path_key in direct_file_dirs
66
+ node["children"].sort(key=lambda child: child["name"])
67
+ node["hasChildren"] = len(node["children"]) > 0
68
+ node["showSelfToggle"] = bool(path_key and node["hasDirectFiles"] and node["hasChildren"])
69
+ return [tree_root]
backend/search/corpus/domain/formats.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decode the current compact corpus and directory formats without runtime state."""
2
+
3
+ from typing import TypedDict, cast
4
+
5
+
6
+ class CompactCorpus(TypedDict, total=False):
7
+ rp: list[str]
8
+ fd: list[list[str]]
9
+ rc: list[object]
10
+
11
+
12
+ class CompactTreeNode(TypedDict, total=False):
13
+ n: str
14
+ c: int
15
+ df: bool
16
+ ch: list["CompactTreeNode"]
17
+
18
+
19
+ class CompactFolder(TypedDict, total=False):
20
+ n: str
21
+ c: int
22
+
23
+
24
+ class CompactFile(TypedDict, total=False):
25
+ n: str
26
+ e: str
27
+ t: bool
28
+ s: int | str
29
+
30
+
31
+ class CompactBrowserEntry(TypedDict, total=False):
32
+ d: list[CompactFolder]
33
+ f: list[CompactFile]
34
+
35
+
36
+ def decode_search_payload(data: object) -> list[dict[str, object]]:
37
+ if not isinstance(data, dict):
38
+ return []
39
+ compact = cast(CompactCorpus, data)
40
+ repos = compact.get("rp", []) or []
41
+ folders = compact.get("fd", []) or []
42
+ records: list[dict[str, object]] = []
43
+ for raw_item in compact.get("rc", []) or []:
44
+ if not isinstance(raw_item, list):
45
+ continue
46
+ item = cast(list[object], raw_item)
47
+ if len(item) < 6:
48
+ continue
49
+ repo = repos[item[0]] if isinstance(item[0], int) and 0 <= item[0] < len(repos) else ""
50
+ folder = folders[item[3]] if isinstance(item[3], int) and 0 <= item[3] < len(folders) else []
51
+ records.append({
52
+ "Repo": repo,
53
+ "File": item[1],
54
+ "Extension": item[2],
55
+ "Folder": folder,
56
+ "Size": item[4],
57
+ "HasTxt": bool(item[5]),
58
+ })
59
+ return records
60
+
61
+
62
+ def decode_tree_node(node: CompactTreeNode, parent_path: str = "", is_root: bool = False) -> dict[str, object]:
63
+ name = node.get("n", "")
64
+ path = "" if is_root else (f"{parent_path}/{name}" if parent_path else name)
65
+ children = [decode_tree_node(child, path, False) for child in node.get("ch", [])]
66
+ decoded: dict[str, object] = {
67
+ "name": name,
68
+ "path": path,
69
+ "count": node.get("c", 0),
70
+ "hasDirectFiles": node.get("df", False),
71
+ "hasChildren": len(children) > 0,
72
+ "showSelfToggle": bool(path and node.get("df", False) and len(children) > 0),
73
+ "children": children,
74
+ }
75
+ if is_root:
76
+ decoded["isRoot"] = True
77
+ return decoded
78
+
79
+
80
+ def decode_folder_tree_data(data: dict[str, list[CompactTreeNode]] | None) -> dict[str, list[dict[str, object]]]:
81
+ return {repo: [decode_tree_node(node, "", True) for node in nodes]
82
+ for repo, nodes in (data or {}).items()}
83
+
84
+
85
+ def decode_browser_entry(entry: CompactBrowserEntry, current_path: str = "") -> dict[str, object]:
86
+ return {
87
+ "folders": [
88
+ {
89
+ "name": item.get("n", ""),
90
+ "path": f"{current_path}/{item.get('n', '')}" if current_path else item.get("n", ""),
91
+ "count": item.get("c", 0),
92
+ }
93
+ for item in entry.get("d", [])
94
+ ],
95
+ "files": [
96
+ {
97
+ "name": item.get("n", ""),
98
+ "ext": item.get("e", ""),
99
+ "hasTxt": item.get("t", False),
100
+ "size": item.get("s", ""),
101
+ }
102
+ for item in entry.get("f", [])
103
+ ],
104
+ "current_path": current_path,
105
+ }
106
+
107
+
108
+ def decode_folder_browser_data(data: dict[str, dict[str, CompactBrowserEntry]] | None) -> dict[str, dict[str, dict[str, object]]]:
109
+ return {repo: {path: decode_browser_entry(entry, path) for path, entry in (browser or {}).items()}
110
+ for repo, browser in (data or {}).items()}
backend/search/corpus/domain/records.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure record paths and reader projections shared by search and reader APIs."""
2
+ import posixpath
3
+ import re
4
+ from typing import cast
5
+ from urllib.parse import quote
6
+
7
+
8
+ READER_ASSET_MODES = {
9
+ "p": "pdf", "e": "epub", "d": "docx", "h": "html",
10
+ "t": "txt", "k": "md", "i": "webp", "a": "audio", "v": "video", "f": "swf",
11
+ }
12
+ READER_NATIVE_FOLIATE_EXTENSIONS = frozenset({"epub", "mobi", "azw", "azw3", "fb2"})
13
+
14
+
15
+ def build_record_relative_path(rec: dict[str, object]) -> str:
16
+ file_name = cast(str, rec.get("File", ""))
17
+ extension = cast(str, rec.get("Extension", ""))
18
+ full_name = f"{file_name}.{extension}" if extension else file_name
19
+ folders = cast(list[str], rec.get("Folder", []) or [])
20
+ return posixpath.join(*folders, full_name) if folders else full_name
21
+
22
+
23
+ def build_reader_asset_key(rec: dict[str, object]) -> str:
24
+ return f"{rec.get('Repo', '')}\0{build_record_relative_path(rec)}"
25
+
26
+
27
+ def dataset_file_url(repo: str, relative_path: str, action: str = "resolve") -> str:
28
+ return f"https://huggingface.co/datasets/{repo}/{action}/main/{quote(relative_path, safe='/')}"
29
+
30
+
31
+ def dataset_file_urls(repo: str, relative_path: str) -> tuple[str, str]:
32
+ """Produce source and browser URLs using the same encoded path."""
33
+ encoded = quote(relative_path, safe="/")
34
+ prefix = f"https://huggingface.co/datasets/{repo}"
35
+ return f"{prefix}/resolve/main/{encoded}", f"{prefix}/blob/main/{encoded}"
36
+
37
+
38
+ def build_record_link(rec: dict[str, object]) -> str:
39
+ return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec))
40
+
41
+
42
+ def build_record_path_url(rec: dict[str, object]) -> str:
43
+ return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec), "blob")
44
+
45
+
46
+ def build_browser_file_name(file_item: dict[str, object]) -> str:
47
+ name = str(file_item.get("name", "") or "file")
48
+ ext = str(file_item.get("ext", "") or "")
49
+ # Browser metadata stores the source record's stem and last extension in
50
+ # separate fields; a repeated suffix in the stem is still significant.
51
+ if not ext:
52
+ return name
53
+ return f"{name}.{ext}"
54
+
55
+
56
+ def enrich_browser_entry(repo: str, path: str, entry: dict[str, object]) -> dict[str, object]:
57
+ decoded = dict(entry or {})
58
+ decoded["current_path"] = decoded.get("current_path", path)
59
+ folders: list[dict[str, object]] = []
60
+ for folder in cast(list[dict[str, object]], decoded.get("folders", []) or []):
61
+ item = dict(folder)
62
+ if "path" not in item:
63
+ name = item.get("name", "")
64
+ item["path"] = f"{path}/{name}" if path else name
65
+ folders.append(item)
66
+ files: list[dict[str, object]] = []
67
+ for file_item in cast(list[dict[str, object]], decoded.get("files", []) or []):
68
+ item = dict(file_item)
69
+ full_name = build_browser_file_name(item)
70
+ rel_path = f"{path}/{full_name}" if path else full_name
71
+ if not item.get("link") and not item.get("path"):
72
+ item["link"], item["path"] = dataset_file_urls(repo, rel_path)
73
+ else:
74
+ item["link"] = item.get("link") or dataset_file_url(repo, rel_path)
75
+ item["path"] = item.get("path") or dataset_file_url(repo, rel_path, "blob")
76
+ files.append(item)
77
+ decoded["folders"] = folders
78
+ decoded["files"] = files
79
+ return decoded
80
+
81
+
82
+ def reader_asset_url(asset: dict[str, object]) -> str:
83
+ path = quote(str(asset.get("p") or ""), safe="/")
84
+ return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + path
85
+
86
+
87
+ def reader_extension_for_asset(asset: dict[str, object], original_extension: str = "") -> str:
88
+ asset_path = str(asset.get("p") or "")
89
+ if asset.get('c'):
90
+ return 'epub-chapters'
91
+ if asset_path.endswith(("page-manifest.json", "reading-manifest.json")):
92
+ return "image-pages" if asset.get("m") == "i" else "pdf-pages"
93
+ if asset.get("m") == "e":
94
+ match = re.search(r"/(?:document|book)\.(epub|mobi|azw|azw3|fb2)$", asset_path, re.IGNORECASE)
95
+ if match:
96
+ return match.group(1).lower()
97
+ extension = str(original_extension or "").lower().lstrip(".")
98
+ return extension if extension in READER_NATIVE_FOLIATE_EXTENSIONS else "epub"
99
+ mode = asset.get("m")
100
+ return READER_ASSET_MODES.get(mode, "") if isinstance(mode, str) else ""
101
+
102
+
103
+ def _reader_bucket_url(path: str) -> str:
104
+ return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + quote(path, safe="/")
105
+
106
+
107
+ def reader_asset_fields(asset: dict[str, object], original_extension: str) -> dict[str, str]:
108
+ ocr_path = str(asset.get("o") or "")
109
+ ocr_bucket = asset.get("b") == "vomebook/pdf-pages-v2" or asset.get("ob") == "vomebook/pdf-pages-v2"
110
+ fields: dict[str, str] = {}
111
+ if ocr_path.endswith("/ocr-manifest.json") and ocr_bucket:
112
+ fields["ocr_manifest"] = _reader_bucket_url(ocr_path)
113
+ fields["ocr_mode"] = str(asset.get("om") or "")
114
+ if asset.get("s") == 3:
115
+ return fields
116
+ if asset.get("s") != 2 or asset.get("m") not in READER_ASSET_MODES or not asset.get("p"):
117
+ return fields
118
+ if str(original_extension).lower().lstrip('.') == 'djvu':
119
+ # Existing OCR remains independent. Native DjVu reading starts at the
120
+ # dataset source, never an older image stream, manifest or derivative.
121
+ return fields
122
+ if (asset.get('m') == 'p' and not asset.get('c') and str(asset['p']).endswith('/page-manifest.json')
123
+ and str(original_extension).lower().lstrip('.') != 'djvu'):
124
+ # Legacy page indexes no longer own PDF/converted-PDF reading. Keep
125
+ # independent OCR metadata and prefer the validated PDF companion.
126
+ if asset.get('pd') and asset.get('pdb') in {'vomebook/reader-assets-v2', 'vomebook/pdf-pages-v2'}:
127
+ fields.update(url=_reader_bucket_url(cast(str, asset['pd'])), extension='pdf')
128
+ return fields
129
+ fields.update({"url": reader_asset_url(asset), "extension": reader_extension_for_asset(asset, original_extension)})
130
+ if asset.get("pd") and asset.get("pdb") in {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}:
131
+ fields["pdf_document"] = _reader_bucket_url(cast(str, asset["pd"]))
132
+ if asset.get("c"):
133
+ if asset.get("cb") == "vomebook/reader-assets-v2":
134
+ fields["chapter_manifest"] = _reader_bucket_url(cast(str, asset["c"]))
135
+ elif asset.get("cb") == "vomebook/pdf-pages-v2":
136
+ fields["chapter_manifest"] = "/api/reader-bucket-resource?path=" + quote(cast(str, asset["c"]), safe="/")
137
+ return fields
138
+
139
+
140
+ def enrich_reader_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]:
141
+ result = dict(record)
142
+ fields = reader_asset_fields(asset, cast(str, record.get("Extension", "")))
143
+ direct_modes = {
144
+ "pdf": ("pdf", "pdf"), "djvu": ("djvu", "pdf"), "vcf": ("vcf", "text"), "ini": ("ini", "text"),
145
+ "tif": ("image", "image"), "tiff": ("image", "image"),
146
+ }
147
+ direct_extension = str(record.get("Extension") or "").lower().lstrip(".")
148
+ if 'url' not in fields and direct_extension in direct_modes:
149
+ # A PDF without a converted/page asset remains directly readable from
150
+ # its immutable source dataset after the derived asset store changes.
151
+ fields.update(url=cast(str, record.get("Link") or build_record_link(record)),
152
+ extension=direct_modes[direct_extension][0])
153
+ if fields:
154
+ for source, target in (("url", "ReaderLink"), ("extension", "ReaderExtension"),
155
+ ("chapter_manifest", "ReaderChapterManifest"),
156
+ ("ocr_manifest", "ReaderOcrManifest"), ("ocr_mode", "ReaderOcrMode"),
157
+ ("pdf_document", "ReaderPdfDocument")):
158
+ if source in fields:
159
+ result[target] = fields[source]
160
+ result["DownloadLink"] = record.get("Link") or build_record_link(record)
161
+ return result
162
+
163
+
164
+ def add_reader_assets(payload: dict[str, object], assets: dict[str, object]) -> dict[str, object]:
165
+ files = cast(dict[str, dict[str, object]], assets.get("f", {}))
166
+ return {**payload, "results": [
167
+ enrich_reader_record(record, files.get(build_reader_asset_key(record), {}))
168
+ for record in cast(list[dict[str, object]], payload.get("results", []))
169
+ ]}
170
+
171
+
172
+ def reader_resolved_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]:
173
+ source = record.get("Link") or build_record_link(record)
174
+ extension = str(record.get("Extension") or "").lower().lstrip(".")
175
+ repo = cast(str, record.get("Repo", "")).split("/")[-1]
176
+ folders = [str(item) for item in cast(list[object], record.get("Folder", []))]
177
+ return {
178
+ "url": source, "download": source, "extension": extension,
179
+ "original_extension": extension, "title": record.get("File") or record.get("Name") or "在线阅读",
180
+ # Keep the exact indexed filename separate from the display title.
181
+ # The stem may itself end in an extension, or include trailing spaces.
182
+ "filename": build_record_relative_path(record).rsplit("/", 1)[-1],
183
+ "path": "/".join([repo, *folders]), "folder": "/".join(folders), "repo": repo,
184
+ **reader_asset_fields(asset, extension),
185
+ }
backend/search/corpus/domain/words.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure search token matching and word-index construction."""
2
+ from collections.abc import Callable, Iterable, Mapping, Sequence
3
+ import hashlib
4
+ import re
5
+ from typing import cast
6
+
7
+
8
+ def records_digest(records: Sequence[Mapping[str, object]]) -> bytes:
9
+ digest = hashlib.sha256()
10
+ for record in records:
11
+ for value in (record.get("_file_lower", ""), record.get("_repo_lower", ""),
12
+ record.get("_folder_path_lower", "")):
13
+ digest.update(cast(str, value).encode("utf-8"))
14
+ digest.update(b"\0")
15
+ return digest.digest()
16
+
17
+
18
+ def tokenize(text: str, segment: Callable[[str], list[str]]) -> list[str]:
19
+ tokens: list[str] = []
20
+ text_lower = text.lower()
21
+ tokens.extend(re.findall(r"[a-z0-9]+", text_lower))
22
+ chinese_text = re.sub(r"[a-z0-9\s]+", " ", text_lower)
23
+ chinese_text = re.sub(r"[^\u4e00-\u9fff\u3400-\u4dbf\s]+", " ", chinese_text)
24
+ chinese_tokens = segment(chinese_text)
25
+ tokens.extend([token.strip() for token in chinese_tokens if token.strip()])
26
+ chinese_token_set = set(chinese_tokens)
27
+ for ch in text_lower:
28
+ if "\u4e00" <= ch <= "\u9fff" or "\u3400" <= ch <= "\u4dbf":
29
+ if ch not in chinese_token_set:
30
+ tokens.append(ch)
31
+ # Stable token order keeps rebuilt vocabularies reproducible across hash seeds.
32
+ return list(dict.fromkeys(tokens))
33
+
34
+
35
+ def matches_file_token(record: Mapping[str, object], token: str) -> bool:
36
+ return (token in cast(str, record.get("_full_file_lower", record.get("_file_lower", "")))
37
+ or token in cast(str, record.get("_repo_lower", "")))
38
+
39
+
40
+ def matches_file_query(record: Mapping[str, object], tokens: Iterable[str], fuzzy_tokens: set[str], *,
41
+ tokenize_text: Callable[[str], list[str]],
42
+ file_match: Callable[[Mapping[str, object], str], bool],
43
+ fuzzy_match: Callable[[str, str], bool]) -> bool:
44
+ file_tokens = tokenize_text(cast(str, record.get("_full_file_lower", record.get("_file_lower", "")))) if fuzzy_tokens else []
45
+ return all(file_match(record, token) or (
46
+ token in fuzzy_tokens and any(fuzzy_match(token, word) for word in file_tokens)
47
+ ) for token in tokens)
48
+
49
+
50
+ def build_vocab_by_len(words: Iterable[str], vocab: dict[int, list[str]]) -> None:
51
+ for word in words:
52
+ vocab.setdefault(len(word), []).append(word)
53
+ # Generated postings are sorted by term; rebuilt indexes must traverse the
54
+ # same vocabulary regardless of insertion order or Python hash seed.
55
+ for bucket in vocab.values():
56
+ bucket.sort()
57
+
58
+
59
+ def build_word_index(records: Sequence[Mapping[str, object]], index: dict[str, set[int]],
60
+ tokenize_text: Callable[[str], list[str]]) -> None:
61
+ for idx, record in enumerate(records):
62
+ file_name = cast(str, record.get("File", ""))
63
+ folders = cast(list[str], record.get("Folder", []))
64
+ for token in tokenize_text(" ".join([file_name] + folders)):
65
+ index.setdefault(token, set()).add(idx)
backend/search/corpus/infrastructure/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """search corpus infrastructure package."""
backend/search/corpus/infrastructure/indexes.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Readers for the generated word and n-gram posting files.
2
+
3
+ The generated formats are deliberately small and self-describing. Keeping
4
+ their parsing independent from the FastAPI application makes malformed input
5
+ handling testable without importing application state.
6
+ """
7
+
8
+ import gzip
9
+ from collections.abc import Iterator
10
+ from pathlib import Path
11
+ from typing import Literal, overload
12
+
13
+ try:
14
+ import _search_index_native as _native_index
15
+ except ImportError:
16
+ _native_index = None
17
+
18
+ _native_read_entries = getattr(_native_index, "read_entries", None)
19
+ _native_decode_postings = getattr(_native_index, "decode_postings", None)
20
+
21
+
22
+ NGRAM_MAGIC = b"VNG3"
23
+ WORD_INDEX_MAGIC = b"VWI2"
24
+ WORD_INDEX_TOKENIZER = "jieba-0.42.1-cjk-char-v1"
25
+
26
+ PostingLocation = tuple[int, int, int]
27
+ Posting = set[int] | PostingLocation
28
+ PostingIndex = dict[str, Posting]
29
+
30
+
31
+ def decode_varint(data: bytes, offset: int) -> tuple[int, int]:
32
+ value = 0
33
+ shift = 0
34
+ while offset < len(data):
35
+ byte = data[offset]
36
+ offset += 1
37
+ value |= (byte & 0x7F) << shift
38
+ if not byte & 0x80:
39
+ return value, offset
40
+ shift += 7
41
+ raise ValueError("truncated varint")
42
+
43
+
44
+ def decode_postings(data: bytes | memoryview, record_count: int | None = None) -> set[int]:
45
+ # Non-byte, strided, or mutable-backed buffers retain Python iteration semantics.
46
+ if (_native_decode_postings is not None and record_count is None and
47
+ (type(data) is bytes or (type(data) is memoryview and data.readonly and
48
+ type(data.obj) is bytes and data.format == "B" and
49
+ data.ndim == 1 and data.c_contiguous))):
50
+ try:
51
+ return _native_decode_postings(data)
52
+ except OverflowError:
53
+ # Python integers support valid varints and cumulative IDs wider than 64 bits.
54
+ pass
55
+ return _decode_postings_python(data, record_count)
56
+
57
+
58
+ def _decode_postings_python(data: bytes | memoryview, record_count: int | None = None) -> set[int]:
59
+ record_ids: set[int] = set()
60
+ previous = 0
61
+ value = shift = 0
62
+ for byte in data:
63
+ value |= (byte & 0x7F) << shift
64
+ if byte & 0x80:
65
+ shift += 7
66
+ continue
67
+ previous += value
68
+ if record_count is not None and previous >= record_count:
69
+ raise ValueError("posting record id out of range")
70
+ record_ids.add(previous)
71
+ value = shift = 0
72
+ if shift:
73
+ raise ValueError("truncated varint")
74
+ return record_ids
75
+
76
+
77
+ def _bounded_slice(data: bytes, offset: int, length: int) -> tuple[int, int]:
78
+ end = offset + length
79
+ if length < 0 or end < offset or end > len(data):
80
+ raise ValueError("truncated postings")
81
+ return offset, end
82
+
83
+
84
+ def _validate_postings(data: bytes, start: int, end: int, record_count: int) -> int:
85
+ """Count distinct monotonic IDs without allocating a temporary posting set."""
86
+ previous = 0
87
+ last = -1
88
+ count = 0
89
+ value = shift = 0
90
+ for offset in range(start, end):
91
+ byte = data[offset]
92
+ value |= (byte & 0x7F) << shift
93
+ if byte & 0x80:
94
+ shift += 7
95
+ continue
96
+ previous += value
97
+ if previous >= record_count:
98
+ raise ValueError("posting record id out of range")
99
+ if previous != last:
100
+ count += 1
101
+ last = previous
102
+ value = shift = 0
103
+ if shift:
104
+ raise ValueError("truncated varint")
105
+ return count
106
+
107
+
108
+ def _read_posting_entries(data: bytes, offset: int, count: int, record_count: int,
109
+ materialize: bool = True) -> Iterator[tuple[str, PostingLocation, set[int] | None]]:
110
+ """Yield validated entries while leaving storage policy to each loader."""
111
+ for _ in range(count):
112
+ key_length, offset = decode_varint(data, offset)
113
+ key_start, offset = _bounded_slice(data, offset, key_length)
114
+ key = data[key_start:offset].decode("utf-8")
115
+ posting_count, offset = decode_varint(data, offset)
116
+ posting_length, offset = decode_varint(data, offset)
117
+ posting_start, offset = _bounded_slice(data, offset, posting_length)
118
+ decoded = decode_postings(memoryview(data)[posting_start:offset], record_count) if materialize else None
119
+ actual_count = len(decoded) if decoded is not None else _validate_postings(data, posting_start, offset, record_count)
120
+ if actual_count != posting_count:
121
+ raise ValueError("posting count mismatch")
122
+ yield key, (posting_start, offset, posting_count), decoded
123
+ if offset != len(data):
124
+ raise ValueError("trailing postings")
125
+
126
+
127
+ def _load_posting_entries(data: bytes, offset: int, count: int, record_count: int,
128
+ materialize: bool) -> PostingIndex:
129
+ if _native_read_entries is not None:
130
+ try:
131
+ return _native_read_entries(data, offset, count, record_count, materialize)
132
+ except OverflowError:
133
+ # Retain arbitrary-width varint behavior for unusual valid inputs.
134
+ pass
135
+ if materialize:
136
+ entries: PostingIndex = {}
137
+ for key, _, decoded in _read_posting_entries(data, offset, count, record_count, True):
138
+ if decoded is None:
139
+ raise RuntimeError("materialized posting missing")
140
+ entries[key] = decoded
141
+ return entries
142
+ return {key: location for key, location, _ in _read_posting_entries(data, offset, count, record_count, False)}
143
+
144
+
145
+ def load_ngram_index(
146
+ path: Path,
147
+ width: int,
148
+ record_count: int,
149
+ expected_digest: bytes,
150
+ ) -> tuple[PostingIndex, bytes]:
151
+ try:
152
+ data = gzip.decompress(path.read_bytes())
153
+ if not data.startswith(NGRAM_MAGIC) or len(data) < 37 or data[4] != width:
154
+ return {}, b""
155
+ if data[5:37] != expected_digest:
156
+ return {}, b""
157
+ offset = 37
158
+ stored_record_count, offset = decode_varint(data, offset)
159
+ count, offset = decode_varint(data, offset)
160
+ if stored_record_count != record_count:
161
+ return {}, b""
162
+ postings = _load_posting_entries(data, offset, count, record_count, False)
163
+ return postings, data
164
+ except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError):
165
+ return {}, b""
166
+
167
+
168
+ @overload
169
+ def load_word_index(path: Path, record_count: int, expected_digest: bytes,
170
+ materialize: Literal[False]) -> tuple[PostingIndex, bytes]: ...
171
+
172
+
173
+ @overload
174
+ def load_word_index(path: Path, record_count: int, expected_digest: bytes,
175
+ materialize: Literal[True] = True) -> PostingIndex: ...
176
+
177
+
178
+ def load_word_index(path: Path, record_count: int, expected_digest: bytes,
179
+ materialize: bool = True) -> PostingIndex | tuple[PostingIndex, bytes]:
180
+ try:
181
+ data = gzip.decompress(path.read_bytes())
182
+ if not data.startswith(WORD_INDEX_MAGIC):
183
+ return {} if materialize else ({}, b"")
184
+ offset = len(WORD_INDEX_MAGIC)
185
+ tokenizer_length, offset = decode_varint(data, offset)
186
+ tokenizer_start, offset = _bounded_slice(data, offset, tokenizer_length)
187
+ tokenizer = data[tokenizer_start:offset].decode("utf-8")
188
+ digest_start, offset = _bounded_slice(data, offset, 32)
189
+ if tokenizer != WORD_INDEX_TOKENIZER or data[digest_start:offset] != expected_digest:
190
+ return {} if materialize else ({}, b"")
191
+ stored_record_count, offset = decode_varint(data, offset)
192
+ count, offset = decode_varint(data, offset)
193
+ if stored_record_count != record_count:
194
+ return {} if materialize else ({}, b"")
195
+ entries = _load_posting_entries(data, offset, count, record_count, materialize)
196
+ return entries if materialize else (entries, data)
197
+ except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError):
198
+ return {} if materialize else ({}, b"")
199
+
200
+
201
+ def resolve_postings(value: Posting | frozenset[int] | bytes | memoryview, buffer: bytes) -> set[int]:
202
+ if isinstance(value, tuple):
203
+ start, end, _ = value
204
+ return decode_postings(memoryview(buffer)[start:end])
205
+ return set(value) if isinstance(value, (set, frozenset)) else decode_postings(value)
backend/search/corpus/infrastructure/selection.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Select a verified, immutable local search-data generation before startup.
2
+
3
+ The caller supplies the build-materialized directory. Selection is opt-in and
4
+ all-or-nothing: hashes, lengths, path containment and gzip/JSON structure are
5
+ checked before any application paths are changed. This module never writes a
6
+ bucket pointer or downloads data and does not replace a running process's data.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import gzip
11
+ import hashlib
12
+ import json
13
+ import re
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import cast
17
+ from urllib.parse import quote
18
+
19
+ from backend.search.corpus.infrastructure.indexes import load_ngram_index, load_word_index
20
+
21
+
22
+ SHA = re.compile(r"[0-9a-f]{64}\Z")
23
+ MANDATORY = frozenset({"search_data.json.gz", "folder_tree.json.gz", "folder_browser.json.gz",
24
+ "search_words.bin.gz", "search_ngrams_2.bin.gz", "search_ngrams_3.bin.gz",
25
+ "initial/global.json", "initial/manifest.json", "sidebar/global.json", "sidebar/manifest.json"})
26
+ MAX_FILE = 32 * 1024 * 1024
27
+ MAX_EXPANDED = 256 * 1024 * 1024
28
+ MAX_FILES = 1024
29
+
30
+
31
+ def as_mapping(value: object, label: str) -> dict[str, object]:
32
+ if not isinstance(value, dict):
33
+ raise ValueError(f"{label} must be an object")
34
+ mapping = cast(dict[object, object], value)
35
+ if any(not isinstance(key, str) for key in mapping):
36
+ raise ValueError(f"{label} keys must be strings")
37
+ return cast(dict[str, object], mapping)
38
+
39
+
40
+ def as_list(value: object, label: str) -> list[object]:
41
+ if not isinstance(value, list):
42
+ raise ValueError(f"{label} must be an array")
43
+ return cast(list[object], value)
44
+
45
+
46
+ def canonical(value: object) -> bytes:
47
+ return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
48
+ allow_nan=False) + "\n").encode("utf-8")
49
+
50
+
51
+ def read_compressed_mapping(path: Path, label: str) -> dict[str, object]:
52
+ """Bound expanded generated JSON before interpreting any directory data."""
53
+ try:
54
+ with gzip.open(path, "rb") as stream:
55
+ raw = stream.read(MAX_EXPANDED + 1)
56
+ except (OSError, EOFError) as error:
57
+ raise ValueError(f"invalid compressed {label}") from error
58
+ if len(raw) > MAX_EXPANDED:
59
+ raise ValueError(f"expanded {label} exceeds limit")
60
+ try:
61
+ return as_mapping(json.loads(raw), label)
62
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
63
+ raise ValueError(f"invalid {label} JSON") from error
64
+
65
+
66
+ def read_json_mapping(path: Path, label: str) -> dict[str, object]:
67
+ try:
68
+ return as_mapping(json.loads(path.read_bytes()), label)
69
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
70
+ raise ValueError(f"invalid {label} JSON") from error
71
+
72
+
73
+ def append_bootstrap_record(global_prefix: list[dict[str, object]], repo_prefix: list[dict[str, object]],
74
+ record: dict[str, object]) -> None:
75
+ """Keep bounded prefixes; avoid retaining every decoded corpus record."""
76
+ if len(global_prefix) < 500:
77
+ global_prefix.append(record)
78
+ if len(repo_prefix) < 500:
79
+ repo_prefix.append(record)
80
+
81
+
82
+ def validate_directory_data(root: Path, repos: list[str]) -> dict[str, dict[str, object]]:
83
+ tree = read_compressed_mapping(root / "folder_tree.json.gz", "Space folder tree")
84
+ browser = read_compressed_mapping(root / "folder_browser.json.gz", "Space folder browser")
85
+ if set(tree) != set(repos) or set(browser) != set(repos):
86
+ raise ValueError("Space directory repositories mismatch")
87
+ roots: dict[str, dict[str, object]] = {}
88
+ for repo in repos:
89
+ nodes = as_list(tree[repo], "Space folder roots")
90
+ pending = list(nodes)
91
+ while pending:
92
+ node = as_mapping(pending.pop(), "Space folder node")
93
+ if not isinstance(node.get("n"), str) or type(node.get("c")) is not int or cast(int, node["c"]) < 0:
94
+ raise ValueError("invalid Space folder node")
95
+ if not isinstance(node.get("df"), bool):
96
+ raise ValueError("invalid Space folder node")
97
+ pending.extend(as_list(node.get("ch"), "Space folder children"))
98
+ paths = as_mapping(browser[repo], "Space folder browser paths")
99
+ if "" not in paths:
100
+ raise ValueError("Space folder browser root missing")
101
+ for path, value in paths.items():
102
+ entry = as_mapping(value, "Space folder browser entry")
103
+ for folder in as_list(entry.get("d"), "Space folder browser folders"):
104
+ item = as_mapping(folder, "Space folder browser folder")
105
+ if not isinstance(item.get("n"), str) or type(item.get("c")) is not int or cast(int, item["c"]) < 0:
106
+ raise ValueError("invalid Space folder browser folder")
107
+ for file in as_list(entry.get("f"), "Space folder browser files"):
108
+ item = as_mapping(file, "Space folder browser file")
109
+ if (not isinstance(item.get("n"), str) or not isinstance(item.get("e"), str)
110
+ or not isinstance(item.get("t"), bool)
111
+ or not isinstance(item.get("s"), (int, str)) or isinstance(item.get("s"), bool)):
112
+ raise ValueError("invalid Space folder browser file")
113
+ if path == "":
114
+ roots[repo] = entry
115
+ return roots
116
+
117
+
118
+ def safe_name(name: object) -> bool:
119
+ if (not isinstance(name, str) or not name or name.startswith("/") or "\\" in name
120
+ or any(part in {"", ".", ".."} for part in name.split("/"))
121
+ or any(ord(char) < 32 or ord(char) == 127 for char in name)):
122
+ return False
123
+ return name in MANDATORY or bool(re.fullmatch(r"(?:initial|sidebar)/repos/[^/]+\.json", name))
124
+
125
+
126
+ @dataclass(frozen=True)
127
+ class SelectedGeneration:
128
+ generation: str
129
+ directory: Path
130
+ file_count: int
131
+ record_count: int
132
+
133
+
134
+ def inspect_generation(directory: Path, generation: str) -> SelectedGeneration:
135
+ """Verify every advertised Space member and return the immutable selection."""
136
+ if not SHA.fullmatch(generation):
137
+ raise ValueError("invalid search generation identity")
138
+ if directory.is_symlink() or not directory.is_dir():
139
+ raise ValueError("generation directory must be an ordinary directory")
140
+ root = directory.resolve()
141
+ report_file = root / "generation-manifest.json"
142
+ if report_file.is_symlink() or not report_file.is_file() or report_file.stat().st_size > 1024 * 1024:
143
+ raise ValueError("missing or oversized local generation manifest")
144
+ raw_manifest = report_file.read_bytes()
145
+ manifest = as_mapping(json.loads(raw_manifest), "search generation manifest")
146
+ if (manifest.get("version") != 1 or manifest.get("kind") != "search-snapshot-local"
147
+ or manifest.get("generation") != generation
148
+ or manifest.get("object_layout") != "objects/sha256/<first-two>/<sha256>"):
149
+ raise ValueError("invalid search generation manifest")
150
+ excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"}
151
+ identity = {key: value for key, value in manifest.items() if key not in excluded}
152
+ if hashlib.sha256(canonical(identity)).hexdigest() != generation:
153
+ raise ValueError("search manifest identity mismatch")
154
+ objects = as_mapping(manifest.get("objects"), "generation objects")
155
+ files = as_mapping(manifest.get("files"), "generation files")
156
+ entries = as_mapping(objects.get("space"), "Space objects")
157
+ original = as_mapping(files.get("space"), "Space files")
158
+ if set(entries) != set(original):
159
+ raise ValueError("Space manifest member mismatch")
160
+ actual: set[str] = set()
161
+ for path in root.rglob("*"):
162
+ if path.is_symlink():
163
+ raise ValueError("symlinks are forbidden in generation files")
164
+ if path.is_file() and path != report_file:
165
+ actual.add(path.relative_to(root).as_posix())
166
+ elif not path.is_dir() and path != report_file:
167
+ raise ValueError("generation contains a non-file object")
168
+ if actual != set(entries):
169
+ raise ValueError("Space generation contains missing or unlisted files")
170
+ if not MANDATORY <= set(entries) or len(entries) > MAX_FILES:
171
+ raise ValueError("Space generation is incomplete")
172
+ for name, item in entries.items():
173
+ if not safe_name(name):
174
+ raise ValueError("invalid Space member")
175
+ metadata = as_mapping(item, "Space member metadata")
176
+ original_metadata = as_mapping(original[name], "original Space member metadata")
177
+ digest, size = metadata.get("sha256"), metadata.get("bytes")
178
+ if (not isinstance(digest, str) or not SHA.fullmatch(digest) or type(size) is not int
179
+ or not 1 <= size <= MAX_FILE or original_metadata != {"sha256": digest, "bytes": size}
180
+ or metadata.get("object") != f"objects/sha256/{digest[:2]}/{digest}"):
181
+ raise ValueError("Space member identity mismatch")
182
+ path = root.joinpath(*name.split("/"))
183
+ if not path.is_file() or root not in path.resolve().parents or path.stat().st_size != size:
184
+ raise ValueError("Space member missing or wrong size")
185
+ if hashlib.sha256(path.read_bytes()).hexdigest() != digest:
186
+ raise ValueError("Space member digest mismatch")
187
+ corpus_path = root / "search_data.json.gz"
188
+ with gzip.open(corpus_path, "rb") as stream:
189
+ decoded = stream.read(MAX_EXPANDED + 1)
190
+ if len(decoded) > MAX_EXPANDED:
191
+ raise ValueError("expanded search corpus exceeds limit")
192
+ corpus = as_mapping(json.loads(decoded), "Space corpus")
193
+ rows = as_list(corpus.get("rc"), "Space corpus records")
194
+ if corpus.get("v") != 2 or len(rows) != manifest.get("record_count") or not rows:
195
+ raise ValueError("Space corpus record count mismatch")
196
+ # Index files are not allowed to silently degrade into an empty/rebuilt
197
+ # index when the selected generation is loaded by the actual application.
198
+ repos = as_list(corpus.get("rp"), "Space corpus repositories")
199
+ folders = as_list(corpus.get("fd"), "Space corpus folders")
200
+ if (not repos or any(not isinstance(repo, str) or not re.fullmatch(r"VoiceOfML/[A-Za-z0-9._-]+", repo)
201
+ for repo in repos)):
202
+ raise ValueError("invalid Space corpus repository dictionary")
203
+ repo_names = cast(list[str], repos)
204
+ if len(set(repo_names)) != len(repo_names) or len({repo.split("/")[-1] for repo in repo_names}) != len(repo_names):
205
+ raise ValueError("duplicate Space corpus repository")
206
+ folder_names: list[list[str]] = []
207
+ for value in folders:
208
+ folder = as_list(value, "Space corpus folder")
209
+ if any(not isinstance(part, str) for part in folder):
210
+ raise ValueError("invalid Space corpus folder")
211
+ folder_names.append(cast(list[str], folder))
212
+ digest_builder = hashlib.sha256()
213
+ # Bootstrap pages contain at most 500 rows; retain only those prefixes and
214
+ # counts rather than materializing another complete Python corpus.
215
+ repo_prefixes: dict[str, list[dict[str, object]]] = {repo: [] for repo in repo_names}
216
+ repo_counts = dict.fromkeys(repo_names, 0)
217
+ global_prefix: list[dict[str, object]] = []
218
+ for row in rows:
219
+ item = as_list(row, "Space corpus record")
220
+ if (len(item) != 6 or type(item[0]) is not int or not 0 <= item[0] < len(repo_names)
221
+ or not isinstance(item[1], str) or not isinstance(item[2], str) or type(item[3]) is not int
222
+ or not 0 <= item[3] < len(folder_names) or type(item[5]) is not int or item[5] not in (0, 1)):
223
+ raise ValueError("invalid Space corpus record")
224
+ if not isinstance(item[4], (int, str)) or isinstance(item[4], bool):
225
+ raise ValueError("invalid Space corpus record size")
226
+ repo = repo_names[item[0]]
227
+ repo_counts[repo] += 1
228
+ if len(global_prefix) < 500 or len(repo_prefixes[repo]) < 500:
229
+ record: dict[str, object] = {"Repo": repo, "File": item[1], "Extension": item[2],
230
+ "Folder": folder_names[item[3]], "Size": item[4], "HasTxt": bool(item[5])}
231
+ append_bootstrap_record(global_prefix, repo_prefixes[repo], record)
232
+ for text in (item[1], repo_names[item[0]], "/".join(folder_names[item[3]])):
233
+ digest_builder.update(text.lower().encode("utf-8"))
234
+ digest_builder.update(b"\0")
235
+ browser_roots = validate_directory_data(root, repo_names)
236
+ digest = digest_builder.digest()
237
+ words, _ = load_word_index(root / "search_words.bin.gz", len(rows), digest, materialize=False)
238
+ if not words:
239
+ raise ValueError("Space word index is missing, invalid or empty")
240
+ for width in (2, 3):
241
+ grams, _ = load_ngram_index(root / f"search_ngrams_{width}.bin.gz", width, len(rows), digest)
242
+ if not grams:
243
+ raise ValueError(f"Space {width}-gram index is missing, invalid or empty")
244
+ for family in ("initial", "sidebar"):
245
+ listing = read_json_mapping(root / family / "manifest.json", "Space bootstrap manifest")
246
+ urls = as_list(listing.get("urls"), "Space bootstrap URLs")
247
+ if not urls:
248
+ raise ValueError("invalid Space bootstrap manifest")
249
+ prefix = f"/data/{family}/"
250
+ listed: set[str] = set()
251
+ for url in urls:
252
+ if not isinstance(url, str) or not url.startswith(prefix):
253
+ raise ValueError("invalid Space bootstrap URL")
254
+ name = f"{family}/" + url[len(prefix):]
255
+ if not safe_name(name) or name not in entries or name in listed or name.endswith("/manifest.json"):
256
+ raise ValueError("missing or duplicated Space bootstrap member")
257
+ listed.add(name)
258
+ expected = {name for name in entries if name == f"{family}/global.json"
259
+ or name.startswith(f"{family}/repos/")}
260
+ wanted = {f"{family}/global.json"} | {
261
+ f"{family}/repos/{quote(repo.split('/')[-1], safe='')}.json" for repo in repo_names}
262
+ if listed != expected or listed != wanted:
263
+ raise ValueError("Space bootstrap manifest does not cover its members")
264
+ for repo in [None, *repo_names]:
265
+ name = "initial/global.json" if repo is None else f"initial/repos/{quote(repo.split('/')[-1], safe='')}.json"
266
+ payload = read_json_mapping(root / name, "Space initial payload")
267
+ expected_records = global_prefix if repo is None else repo_prefixes[repo]
268
+ expected_total = len(rows) if repo is None else repo_counts[repo]
269
+ page_size = payload.get("page_size")
270
+ if (payload.get("version") != 2 or payload.get("mode") != ("global" if repo is None else "repo")
271
+ or payload.get("repo") != repo or payload.get("sort") != "relevance" or payload.get("page") != 1
272
+ or type(page_size) is not int or not 1 <= page_size <= 500
273
+ or payload.get("total") != expected_total
274
+ or payload.get("results") != expected_records[:page_size]):
275
+ raise ValueError("Space initial payload does not match corpus")
276
+ sidebar = read_json_mapping(root / "sidebar/global.json", "Space sidebar payload")
277
+ repo_summaries = as_list(sidebar.get("repos"), "Space sidebar repositories")
278
+ expected_summaries = [{"name": repo, "count": repo_counts[repo]} for repo in sorted(repo_names)]
279
+ if repo_summaries != expected_summaries:
280
+ raise ValueError("Space sidebar repositories do not match corpus")
281
+ for repo in repo_names:
282
+ name = f"sidebar/repos/{quote(repo.split('/')[-1], safe='')}.json"
283
+ payload = read_json_mapping(root / name, "Space sidebar repository")
284
+ root_entry = browser_roots[repo]
285
+ if (payload.get("repo") != repo or payload.get("path") != ""
286
+ or payload.get("folders") != root_entry.get("d")
287
+ or payload.get("files") != root_entry.get("f")):
288
+ raise ValueError("invalid Space sidebar repository")
289
+ return SelectedGeneration(generation=generation, directory=root, file_count=len(entries),
290
+ record_count=len(rows))
backend/search/domain/browse.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plan empty-query browsing against caller-owned search indexes."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Callable, Sequence
5
+
6
+ Size = int | float | None
7
+ Paths = Sequence[str] | None
8
+ RecordFilter = Callable[[Sequence[int], Paths, Paths, Paths, Size, Size, str], list[int]]
9
+ MixedRecordFilter = Callable[[Sequence[int], Paths, Paths, Size, Size], list[int]]
10
+ MixedFilter = Callable[[Sequence[int], Paths, Paths], Sequence[int]]
11
+ MixedCandidates = Callable[[Paths, Paths, Paths], list[int] | None]
12
+
13
+
14
+ def browse_order(repos: Paths, extensions: Paths, folders: Paths, min_size: Size, max_size: Size,
15
+ folder_match_mode: str, folder_selfs: Paths, folder_subtrees: Paths, sort: str, *,
16
+ get_precomputed: Callable[[Paths, str], Sequence[int]],
17
+ get_mixed_candidates: MixedCandidates, get_initial: Callable[[Paths], Sequence[int]],
18
+ filter_mixed: MixedFilter, filter_records: RecordFilter,
19
+ filter_mixed_records: MixedRecordFilter, key_name: Callable[[int], str], key_size: Callable[[int], tuple[int | float, str]]) -> Sequence[int]:
20
+ """Preserve precomputed order identity or filter a bounded corpus snapshot."""
21
+ has_filters = (extensions or folders or min_size is not None or max_size is not None
22
+ or folder_match_mode == "mixed")
23
+ if not has_filters and (not repos or len(repos) == 1):
24
+ return get_precomputed(repos, sort)
25
+ filtered = _filtered_order(repos, extensions, folders, min_size, max_size, folder_match_mode,
26
+ folder_selfs, folder_subtrees, get_mixed_candidates, get_initial,
27
+ filter_mixed, filter_records, filter_mixed_records)
28
+ if sort == "name":
29
+ filtered.sort(key=key_name)
30
+ elif sort == "size":
31
+ filtered.sort(key=key_size)
32
+ return filtered
33
+
34
+
35
+ def _filtered_order(repos: Paths, extensions: Paths, folders: Paths, min_size: Size, max_size: Size,
36
+ folder_match_mode: str, folder_selfs: Paths, folder_subtrees: Paths,
37
+ get_mixed_candidates: MixedCandidates, get_initial: Callable[[Paths], Sequence[int]],
38
+ filter_mixed: MixedFilter, filter_records: RecordFilter,
39
+ filter_mixed_records: MixedRecordFilter) -> list[int]:
40
+ if folder_match_mode == "mixed":
41
+ indices = get_mixed_candidates(repos, folder_selfs, folder_subtrees)
42
+ if indices is None:
43
+ indices = get_initial(repos)
44
+ mixed = filter_mixed(indices, folder_selfs, folder_subtrees)
45
+ return filter_mixed_records(mixed, repos, extensions, min_size, max_size)
46
+ indices = get_initial(repos)
47
+ return filter_records(indices, repos, extensions, folders, min_size, max_size, folder_match_mode)
backend/search/domain/candidates.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed literal n-gram candidate selection over caller-owned search state."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Callable, Iterable, Mapping, Sequence
5
+ import re
6
+ from backend.search.corpus.infrastructure.indexes import Posting, PostingIndex
7
+
8
+ PostingResolver = Callable[[Posting, bytes], set[int]]
9
+
10
+
11
+ def wildcard_literal_candidates(query: str, repos: Iterable[str] | None,
12
+ get_candidates: Callable[[str, Iterable[str] | None], set[int] | None],
13
+ get_scope: Callable[[Iterable[str] | None], Sequence[int]]) -> list[int]:
14
+ """Bound wildcard search by a safe mandatory CJK, digit or ASCII run.
15
+
16
+ Python IGNORECASE additionally equates i, k and s to non-ASCII characters;
17
+ those letters are deliberately excluded. The selected safe run is guaranteed
18
+ by any match, while the wildcard matcher still verifies every candidate.
19
+ """
20
+ chunks = re.findall(r"[\u3400-\u4DBF\u4E00-\u9FFF0-9a-hjl-rt-zA-HJL-RT-Z]{2,}", query)
21
+ # Prefer an available non-ASCII run even when a longer format suffix is
22
+ # present: common extensions can otherwise expand tens of thousands of IDs.
23
+ native = [chunk for chunk in chunks if any(ord(char) > 127 for char in chunk)]
24
+ selected = native or chunks
25
+ candidates = get_candidates(max(selected, key=len).lower(), repos) if selected else None
26
+ return sorted(get_scope(repos) if candidates is None else candidates)
27
+
28
+
29
+ def literal_candidates(query: str, repos: Iterable[str] | None,
30
+ get_postings: Callable[[], Mapping[int, PostingIndex]],
31
+ get_buffers: Callable[[], Mapping[int, bytes]],
32
+ get_repos: Callable[[], Mapping[str, Sequence[int]]],
33
+ get_records: Callable[[], Sequence[dict[str, object]]],
34
+ get_resolver: Callable[[], PostingResolver]) -> set[int] | None:
35
+ """Return an exact posting intersection, or None when no index is usable.
36
+
37
+ Index records, repository lists and published postings remain caller-owned.
38
+ The first decoded posting is owned by the resolver and may be narrowed in
39
+ place exactly as before; no state is cached or published by this helper.
40
+ """
41
+ width = 3 if len(query) >= 3 and get_postings().get(3) else 2
42
+ postings = get_postings().get(width)
43
+ if not postings or len(query) < width:
44
+ return None
45
+ entries: list[Posting] = []
46
+ for gram in dict.fromkeys(query[index:index + width] for index in range(len(query) - width + 1)):
47
+ encoded = postings.get(gram)
48
+ if encoded is None:
49
+ return set()
50
+ entries.append(encoded)
51
+ entries.sort(key=lambda entry: entry[2] if isinstance(entry, tuple) else len(entry))
52
+ candidates: set[int] | None = None
53
+ repo_scope = set(repos) if repos else None
54
+ for encoded in entries:
55
+ matches = get_resolver()(encoded, get_buffers().get(width, b""))
56
+ if candidates is None:
57
+ candidates = matches
58
+ if repo_scope is not None:
59
+ if len(candidates) <= 2048 and sum(
60
+ len(get_repos().get(repo, ())) for repo in repo_scope) > len(candidates) * 8:
61
+ candidates = {idx for idx in candidates if 0 <= idx < len(get_records())
62
+ and get_records()[idx].get("Repo", "") in repo_scope}
63
+ else:
64
+ allowed: set[int] = set()
65
+ for repo in repo_scope:
66
+ allowed.update(get_repos().get(repo, []))
67
+ candidates.intersection_update(allowed)
68
+ else:
69
+ candidates.intersection_update(matches)
70
+ if not candidates:
71
+ return set()
72
+ return candidates or set()
backend/search/domain/filters.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed search record filters over a caller-owned corpus snapshot."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Iterable, Mapping, Sequence
5
+ from typing import cast
6
+
7
+ SearchRecord = dict[str, object]
8
+ FolderIndex = Mapping[str, Mapping[str, Sequence[int]]]
9
+ RepoIndex = Mapping[str, Sequence[int]]
10
+
11
+
12
+ def score_record(record: SearchRecord, query_tokens: Iterable[str], search_folders: bool = True) -> int:
13
+ score = 0
14
+ file_name = cast(str, record.get("_file_lower", ""))
15
+ repo = cast(str, record.get("_repo_lower", ""))
16
+ folder_text = cast(str, record.get("_folder_text", ""))
17
+ for token in query_tokens:
18
+ if token in file_name:
19
+ score += 3
20
+ if search_folders and token in folder_text:
21
+ score += 2
22
+ if token in repo:
23
+ score += 1
24
+ return score
25
+
26
+
27
+ def apply_filters(records: Sequence[SearchRecord], indices: Iterable[int], repos: Sequence[str] | None = None,
28
+ extensions: Sequence[str] | None = None, folders: Sequence[str] | None = None,
29
+ min_size: int | float | None = None, max_size: int | float | None = None,
30
+ folder_match_mode: str = "prefix") -> list[int]:
31
+ repos_set = set(repos) if repos else None
32
+ extensions_lower = {extension.lower() for extension in extensions} if extensions else None
33
+ folder_set = {folder.strip("/") for folder in folders} if folders else None
34
+ if folder_match_mode != "exact" and folder_set and "" in folder_set:
35
+ # Unlike the Worker, an empty API prefix includes the complete scope.
36
+ folder_set = None
37
+ folder_prefix = next(iter(folder_set)) + "/" if folder_set and len(folder_set) == 1 and folder_match_mode != "exact" else None
38
+ result: list[int] = []
39
+ for idx in indices:
40
+ record = records[idx]
41
+ if repos_set and record.get("Repo") not in repos_set:
42
+ continue
43
+ if extensions_lower and record.get("_ext_lower", "") not in extensions_lower:
44
+ continue
45
+ rec_path = ""
46
+ if folder_set:
47
+ rec_path = (cast(str, record["_folder_path"]) if "_folder_path" in record
48
+ else "/".join(cast(list[str], record.get("Folder", []) or [])))
49
+ matched = rec_path in folder_set
50
+ if not matched and folder_match_mode != "exact":
51
+ if folder_prefix is not None:
52
+ matched = rec_path.startswith(folder_prefix)
53
+ else:
54
+ end = rec_path.rfind("/")
55
+ while end > 0:
56
+ if rec_path[:end] in folder_set:
57
+ matched = True
58
+ break
59
+ end = rec_path.rfind("/", 0, end)
60
+ if not matched:
61
+ continue
62
+ size = record.get("Size")
63
+ if size and isinstance(size, (int, float)) and size > 0:
64
+ if min_size is not None and size < min_size:
65
+ continue
66
+ if max_size is not None and size > max_size:
67
+ continue
68
+ result.append(idx)
69
+ return result
70
+
71
+
72
+ def apply_mixed_folder_filters(records: Sequence[SearchRecord], indices: Sequence[int],
73
+ self_folders: Sequence[str] | None = None,
74
+ subtree_folders: Sequence[str] | None = None) -> Sequence[int]:
75
+ self_set = {str(path).strip("/") for path in (self_folders or [])}
76
+ subtree_set = {str(path).strip("/") for path in (subtree_folders or []) if str(path).strip("/")}
77
+ if not self_set and not subtree_set:
78
+ return indices
79
+ result: list[int] = []
80
+ for idx in indices:
81
+ rec_folders = cast(list[str], records[idx].get("Folder", []) or [])
82
+ rec_path = "/".join(rec_folders)
83
+ if rec_path in self_set:
84
+ result.append(idx)
85
+ continue
86
+ if not subtree_set:
87
+ continue
88
+ if rec_path in subtree_set:
89
+ result.append(idx)
90
+ continue
91
+ matched = False
92
+ prefix = ""
93
+ for depth, part in enumerate(rec_folders):
94
+ # A slash may itself be part of a folder component; only actual
95
+ # component boundaries are eligible subtree matches.
96
+ prefix = part if depth == 0 else prefix + "/" + part
97
+ if prefix in subtree_set:
98
+ matched = True
99
+ break
100
+ if matched:
101
+ result.append(idx)
102
+ return result
103
+
104
+
105
+ def mixed_folder_index_candidates(records: Sequence[SearchRecord], folder_index: FolderIndex,
106
+ repo_records_map: RepoIndex, repos: Sequence[str] | None,
107
+ self_folders: Sequence[str] | None = None,
108
+ subtree_folders: Sequence[str] | None = None) -> list[int] | None:
109
+ """Return a bounded corpus-ordered superset, or None to retain a full scan."""
110
+ if len(self_folders or ()) + len(subtree_folders or ()) > 64:
111
+ return None
112
+ paths = {str(path).strip("/") for path in (self_folders or [])}
113
+ paths.update(str(path).strip("/") for path in (subtree_folders or []) if str(path).strip("/"))
114
+ if not paths:
115
+ return None
116
+ selected_repos = sorted(set(repos)) if repos else list(repo_records_map)
117
+ scope_size = sum(len(repo_records_map.get(repo, ())) for repo in selected_repos) if repos else len(records)
118
+ # Broad selections fall back rather than allocating an unbounded set.
119
+ limit = min(32768, max(64, scope_size // 2))
120
+ postings: list[Sequence[int]] = []
121
+ estimated = 0
122
+ for repo in selected_repos:
123
+ folders = folder_index.get(repo, {})
124
+ for path in paths:
125
+ indices = folders.get(path, ())
126
+ estimated += len(indices)
127
+ if estimated > limit:
128
+ return None
129
+ if indices:
130
+ postings.append(indices)
131
+ candidates: set[int] = set()
132
+ for indices in postings:
133
+ candidates.update(indices)
134
+ return sorted(candidates)
backend/search/domain/matching.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded exact, wildcard and fuzzy search matching."""
2
+ from collections.abc import Callable
3
+ import re
4
+
5
+
6
+ def compile_exact_matcher(query: str) -> Callable[[str], bool]:
7
+ if "*" not in query and "?" not in query:
8
+ lower = query.lower()
9
+ return lambda text: lower in text.lower()
10
+ if not query.strip("*"):
11
+ # An unanchored sequence of stars matches the empty substring.
12
+ return lambda _text: True
13
+ if "*" in query and "?" in query and not query.strip("*?"):
14
+ # Stars may match nothing; each question consumes a non-LF code point.
15
+ required = query.count("?")
16
+
17
+ def matches_question_run(text: str) -> bool:
18
+ start = 0
19
+ while start < len(text):
20
+ end = text.find("\n", start)
21
+ if end < 0:
22
+ end = len(text)
23
+ if end - start >= required:
24
+ return True
25
+ start = max(start, end) + 1
26
+ return False
27
+
28
+ return matches_question_run
29
+ if "*" not in query:
30
+ # Escaped fixed-width literals and dots need no variable-length regex
31
+ # repetition, retaining IGNORECASE and dot's LF behavior.
32
+ fixed = re.compile("".join("." if char == "?" else re.escape(char) for char in query), re.IGNORECASE)
33
+ if len(query) < 128 or not any(char != "?" for char in query):
34
+ return lambda text: fixed.search(text) is not None
35
+ literals = [re.compile(re.escape(char), re.IGNORECASE)
36
+ for char in dict.fromkeys(query) if char != "?"]
37
+ return lambda text: ((len(text) <= 4096 or all(literal.search(text) for literal in literals))
38
+ and fixed.search(text) is not None)
39
+ # In substring matching, stars at either boundary can match zero chars.
40
+ # Keep Unicode IGNORECASE behavior, unlike the literal .lower() branch.
41
+ core = query.strip("*")
42
+ if core and "*" not in core and "?" not in core:
43
+ literal = re.compile(re.escape(core), re.IGNORECASE)
44
+ return lambda text: literal.search(text) is not None
45
+ if "*" in core and "?" not in core and "\n" not in core:
46
+ # A leftmost match for each mandatory chunk leaves the most room for
47
+ # later chunks. Wildcard dots cannot cross LF in Python's regex rules.
48
+ chunks = [re.compile(re.escape(part), re.IGNORECASE)
49
+ for part in re.split(r"\*+", core)]
50
+
51
+ def matches_chunks(text: str) -> bool:
52
+ for line in text.split("\n"):
53
+ position = 0
54
+ for chunk in chunks:
55
+ match = chunk.search(line, position)
56
+ if match is None:
57
+ break
58
+ position = match.end()
59
+ else:
60
+ return True
61
+ return False
62
+
63
+ return matches_chunks
64
+ # A leading/trailing wildcard run followed/preceded by a fixed literal
65
+ # has only one variable-width part. Strip its boundary stars: they can
66
+ # always match zero characters in an unanchored search. The remaining
67
+ # questions have fixed width and therefore cannot backtrack exponentially.
68
+ core_parts = core.split("*")
69
+ nonempty_parts = [part for part in core_parts if part]
70
+ if len(nonempty_parts) == 2:
71
+ first, last = nonempty_parts
72
+ first_questions = first and not first.strip("?") and "?" not in last
73
+ last_questions = last and not last.strip("?") and "?" not in first
74
+ if first_questions or last_questions:
75
+ fixed = first + last
76
+ expression = re.compile("".join("." if char == "?" else re.escape(char) for char in fixed), re.IGNORECASE)
77
+ if len(fixed) >= 128:
78
+ literals = [re.compile(re.escape(char), re.IGNORECASE)
79
+ for char in dict.fromkeys(fixed) if char != "?"]
80
+ return lambda text: ((len(text) <= 4096 or all(literal.search(text) for literal in literals))
81
+ and expression.search(text) is not None)
82
+ return lambda text: expression.search(text) is not None
83
+ # Bitset NFA: each bit is a pattern position. Collapse adjacent stars so
84
+ # epsilon closure needs one shift. No input can cause regex backtracking.
85
+ pattern = re.sub(r"\*+", "*", query)
86
+ stars = questions = 0
87
+ literal_bits: dict[str, int] = {}
88
+ for index, char in enumerate(pattern):
89
+ bit = 1 << index
90
+ if char == "*":
91
+ stars |= bit
92
+ elif char == "?":
93
+ questions |= bit
94
+ else:
95
+ literal_bits[char] = literal_bits.get(char, 0) | bit
96
+ # Single-character regexes retain Python IGNORECASE's Unicode semantics.
97
+ literals = [(re.compile(re.escape(char), re.IGNORECASE), bits)
98
+ for char, bits in literal_bits.items()]
99
+ masks: dict[str, int] = {}
100
+ end = 1 << len(pattern)
101
+ start = 1 | ((1 & stars) << 1)
102
+
103
+ def matches(text: str) -> bool:
104
+ # Every literal is mandatory; C-level scans reject unrelated fields early.
105
+ if any(regex.search(text) is None for regex, _ in literals):
106
+ return False
107
+ active = start
108
+ for char in text:
109
+ mask = masks.get(char)
110
+ if mask is None:
111
+ mask = sum(bits for regex, bits in literals if regex.fullmatch(char))
112
+ if len(masks) >= 512:
113
+ masks.clear()
114
+ masks[char] = mask
115
+ wildcard = char != "\n"
116
+ active = ((active & (mask | (questions if wildcard else 0))) << 1) | (
117
+ active & stars if wildcard else 0) | 1
118
+ active |= (active & stars) << 1
119
+ if active & end:
120
+ return True
121
+ return False
122
+ return matches
123
+
124
+
125
+ def matches_exact_query(text: str, query: str) -> bool:
126
+ return compile_exact_matcher(query)(text)
127
+
128
+
129
+ def split_exact_terms(query: str) -> list[str]:
130
+ """Whitespace separates literal terms; each term must match independently."""
131
+ return [term for term in query.split() if term]
132
+
133
+ def edit_distance(s1: str, s2: str, max_dist: int = 2) -> int:
134
+ if abs(len(s1) - len(s2)) > max_dist:
135
+ return 999
136
+ prev = list(range(len(s2) + 1))
137
+ for i, c1 in enumerate(s1):
138
+ curr = [i + 1]
139
+ for j, c2 in enumerate(s2):
140
+ cost = 0 if c1 == c2 else 1
141
+ curr.append(min(prev[j + 1] + 1, curr[j] + 1, prev[j] + cost))
142
+ if min(curr) > max_dist:
143
+ return 999
144
+ prev = curr
145
+ return prev[-1]
146
+
147
+ def could_be_fuzzy(tok: str, word: str, max_dist: int = 2) -> bool:
148
+ if abs(len(tok) - len(word)) > max_dist:
149
+ return False
150
+ if len(tok) < 4:
151
+ return True
152
+ counts: dict[str, int] = {}
153
+ for ch in tok:
154
+ counts[ch] = counts.get(ch, 0) + 1
155
+ diff = 0
156
+ for ch in word:
157
+ if counts.get(ch, 0) > 0:
158
+ counts[ch] -= 1
159
+ else:
160
+ diff += 1
161
+ if diff > 2 * max_dist:
162
+ return False
163
+ for remaining in counts.values():
164
+ diff += remaining
165
+ if diff > 2 * max_dist:
166
+ return False
167
+ return True
168
+
169
+
170
+ def fuzzy_distance_budget(token: str) -> int:
171
+ """Short tokens cannot tolerate the same edit radius as longer words."""
172
+ if len(token) <= 1:
173
+ return 0
174
+ return 1 if len(token) <= 3 else 2
175
+
176
+
177
+ def is_fuzzy_match(token: str, word: str) -> bool:
178
+ limit = fuzzy_distance_budget(token)
179
+ return could_be_fuzzy(token, word, limit) and edit_distance(token, word, max_dist=limit) <= limit
backend/search/domain/ordering.py CHANGED
@@ -10,8 +10,8 @@ from collections.abc import Callable, Iterable, Mapping, Sequence
10
  from dataclasses import dataclass
11
  from typing import Protocol, TypedDict, cast
12
 
13
- from backend.search_browse import MixedCandidates, MixedFilter, MixedRecordFilter, RecordFilter as BrowseRecordFilter
14
- from backend.search_indexes import Posting
15
 
16
  Record = dict[str, object]
17
  Paths = Sequence[str] | None
 
10
  from dataclasses import dataclass
11
  from typing import Protocol, TypedDict, cast
12
 
13
+ from backend.search.domain.browse import MixedCandidates, MixedFilter, MixedRecordFilter, RecordFilter as BrowseRecordFilter
14
+ from backend.search.corpus.infrastructure.indexes import Posting
15
 
16
  Record = dict[str, object]
17
  Paths = Sequence[str] | None
backend/search/domain/term_candidates.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Word and fuzzy candidate selection for a single search term."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Callable, Mapping, Sequence
5
+ from typing import cast
6
+
7
+ from backend.search.infrastructure.executor import check_search_cancelled
8
+
9
+ SearchRecord = dict[str, object]
10
+
11
+
12
+ def term_candidates(term: str, query_token_count: int, posting_cache: dict[str, set[int]],
13
+ search_folders: bool, *, tokenize: Callable[[str], list[str]],
14
+ scoped_word_postings: Callable[[str, bool], set[int]],
15
+ get_word_index: Callable[[], Mapping[str, object]],
16
+ get_records: Callable[[], Sequence[SearchRecord]],
17
+ get_vocab: Callable[[], Mapping[int, list[str]]],
18
+ is_fuzzy_match: Callable[[str, str], bool]) -> tuple[set[int], set[str]]:
19
+ """Intersect term postings without truncating before record filters."""
20
+ query_tokens = tokenize(term)
21
+ return candidates_for_tokens(query_tokens, query_token_count, posting_cache, search_folders,
22
+ tokenize=tokenize, scoped_word_postings=scoped_word_postings,
23
+ get_word_index=get_word_index, get_records=get_records, get_vocab=get_vocab,
24
+ is_fuzzy_match=is_fuzzy_match)
25
+
26
+
27
+ def candidates_for_tokens(query_tokens: Sequence[str], query_token_count: int, posting_cache: dict[str, set[int]],
28
+ search_folders: bool, *, tokenize: Callable[[str], list[str]],
29
+ scoped_word_postings: Callable[[str, bool], set[int]],
30
+ get_word_index: Callable[[], Mapping[str, object]],
31
+ get_records: Callable[[], Sequence[SearchRecord]],
32
+ get_vocab: Callable[[], Mapping[int, list[str]]],
33
+ is_fuzzy_match: Callable[[str, str], bool]) -> tuple[set[int], set[str]]:
34
+ """Resolve already-tokenized input without repeating tokenization."""
35
+ # Candidate caps before repository and record filtering can lose valid hits.
36
+ fuzzy_candidate_limit = None
37
+ fuzzy_tokens: set[str] = set()
38
+
39
+ def query_postings(token: str) -> set[int]:
40
+ if token not in posting_cache:
41
+ posting_cache[token] = scoped_word_postings(token, search_folders)
42
+ return posting_cache[token]
43
+
44
+ exact_constraint = _exact_constraint(query_tokens, get_word_index, query_postings)
45
+ token_candidates: list[set[int]] = []
46
+ for tok in query_tokens:
47
+ check_search_cancelled()
48
+ candidates: set[int] = query_postings(tok) if tok in get_word_index() else set()
49
+ if not candidates:
50
+ fuzzy_tokens.add(tok)
51
+ candidates = _fuzzy_candidates(tok, exact_constraint, fuzzy_candidate_limit, search_folders,
52
+ get_records, get_vocab, tokenize, is_fuzzy_match, query_postings)
53
+ if not candidates:
54
+ return set(), fuzzy_tokens
55
+ token_candidates.append(candidates)
56
+ return _intersect_candidates(token_candidates), fuzzy_tokens
57
+
58
+
59
+ def _exact_constraint(query_tokens: Sequence[str], get_word_index: Callable[[], Mapping[str, object]],
60
+ query_postings: Callable[[str], set[int]]) -> set[int] | None:
61
+ exact_constraint: set[int] | None = None
62
+ for tok in query_tokens:
63
+ if tok not in get_word_index():
64
+ continue
65
+ postings = query_postings(tok)
66
+ if not postings:
67
+ continue
68
+ exact_constraint = set(postings) if exact_constraint is None else exact_constraint.intersection(postings)
69
+ return exact_constraint
70
+
71
+
72
+ def _intersect_candidates(token_candidates: list[set[int]]) -> set[int]:
73
+ if not token_candidates:
74
+ return set()
75
+ token_candidates.sort(key=len)
76
+ matched = set(token_candidates[0])
77
+ for candidates in token_candidates[1:]:
78
+ matched.intersection_update(candidates)
79
+ if not matched:
80
+ break
81
+ return matched
82
+
83
+
84
+ def _fuzzy_candidates(tok: str, exact_constraint: set[int] | None, limit: int | None, search_folders: bool,
85
+ get_records: Callable[[], Sequence[SearchRecord]],
86
+ get_vocab: Callable[[], Mapping[int, list[str]]], tokenize: Callable[[str], list[str]],
87
+ is_fuzzy_match: Callable[[str, str], bool],
88
+ query_postings: Callable[[str], set[int]]) -> set[int]:
89
+ if exact_constraint is not None:
90
+ return _fuzzy_record_candidates(tok, exact_constraint, limit, search_folders,
91
+ get_records, tokenize, is_fuzzy_match)
92
+ return _fuzzy_vocabulary_candidates(tok, limit, get_vocab, is_fuzzy_match, query_postings)
93
+
94
+
95
+ def _fuzzy_record_candidates(tok: str, exact_constraint: set[int], limit: int | None, search_folders: bool,
96
+ get_records: Callable[[], Sequence[SearchRecord]],
97
+ tokenize: Callable[[str], list[str]],
98
+ is_fuzzy_match: Callable[[str, str], bool]) -> set[int]:
99
+ candidates: set[int] = set()
100
+ for offset, idx in enumerate(sorted(exact_constraint)):
101
+ if offset % 256 == 0:
102
+ check_search_cancelled()
103
+ rec = get_records()[idx]
104
+ record_tokens = tokenize(" ".join([cast(str, rec.get("File", "")),
105
+ *(cast(list[str], rec.get("Folder", []) or []) if search_folders else [])]))
106
+ if any(is_fuzzy_match(tok, word) for word in record_tokens):
107
+ candidates.add(idx)
108
+ if limit is not None and len(candidates) >= limit:
109
+ break
110
+ return candidates
111
+
112
+
113
+ def _fuzzy_vocabulary_candidates(tok: str, limit: int | None,
114
+ get_vocab: Callable[[], Mapping[int, list[str]]],
115
+ is_fuzzy_match: Callable[[str, str], bool],
116
+ query_postings: Callable[[str], set[int]]) -> set[int]:
117
+ candidates: set[int] = set()
118
+ tok_len = len(tok)
119
+ for delta in (-2, -1, 0, 1, 2):
120
+ for offset, vocab_word in enumerate(get_vocab().get(tok_len + delta, [])):
121
+ if offset % 256 == 0:
122
+ check_search_cancelled()
123
+ if is_fuzzy_match(tok, vocab_word):
124
+ candidates.update(query_postings(vocab_word))
125
+ if limit is not None and len(candidates) >= limit:
126
+ break
127
+ if limit is not None and len(candidates) >= limit:
128
+ break
129
+ return candidates
backend/search/http/body_limit.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bound search uploads before JSON parsing; leave application failures untouched."""
2
+ import asyncio
3
+
4
+ from starlette.responses import Response
5
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
6
+
7
+ SEARCH_BODY_MAX_BYTES = 8 * 1024 * 1024
8
+ SEARCH_BODY_TIMEOUT_SECONDS = 15.0
9
+
10
+
11
+ class SearchBodyLimitMiddleware:
12
+ def __init__(self, app: ASGIApp) -> None:
13
+ self.app = app
14
+
15
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
16
+ path = scope.get("path", "")
17
+ if (scope["type"] != "http" or scope["method"] != "POST"
18
+ or not (path == "/api/search" or path.startswith("/api/search/"))):
19
+ await self.app(scope, receive, send)
20
+ return
21
+ # Count actual wire bytes, including chunked uploads and misleading
22
+ # Content-Length. A bytearray also bounds overhead from tiny chunks.
23
+ body = bytearray()
24
+ status = None
25
+ chunk = b""
26
+ message: Message = {}
27
+ deadline = asyncio.timeout(SEARCH_BODY_TIMEOUT_SECONDS)
28
+ try:
29
+ async with deadline:
30
+ while True:
31
+ message = await receive()
32
+ if message["type"] == "http.disconnect":
33
+ status = 204
34
+ break
35
+ chunk = message.get("body", b"")
36
+ if len(body) + len(chunk) > SEARCH_BODY_MAX_BYTES:
37
+ status = 413
38
+ break
39
+ body.extend(chunk)
40
+ if not message.get("more_body", False):
41
+ break
42
+ # receive may complete synchronously for buffered messages.
43
+ await asyncio.sleep(0)
44
+ except TimeoutError:
45
+ if not deadline.expired():
46
+ raise
47
+ status = 408
48
+ del message, chunk
49
+ if status is not None:
50
+ body.clear()
51
+ await Response(status_code=status, headers={"Cache-Control": "no-store"})(scope, receive, send)
52
+ return
53
+ buffered: bytes | None = bytes(body)
54
+ body.clear()
55
+
56
+ async def replay() -> Message:
57
+ nonlocal buffered
58
+ if buffered is not None:
59
+ payload, buffered = buffered, None
60
+ return {"type": "http.request", "body": payload, "more_body": False}
61
+ return await receive()
62
+
63
+ # The upload deadline ends before validation, routing or response send.
64
+ await self.app(scope, replay, send)
backend/search/http/responses.py CHANGED
@@ -14,7 +14,7 @@ from backend.search.application.requests import (
14
  NormalizeSearchList, SearchFunction, SearchParameters, normalize_search_parameters,
15
  )
16
  from backend.search.http.schemas import SearchRequest
17
- from backend.search_execution import SearchBusy
18
 
19
 
20
  JsonObject = dict[str, object]
 
14
  NormalizeSearchList, SearchFunction, SearchParameters, normalize_search_parameters,
15
  )
16
  from backend.search.http.schemas import SearchRequest
17
+ from backend.search.infrastructure.executor import SearchBusy
18
 
19
 
20
  JsonObject = dict[str, object]