vomebook commited on
Commit ·
1655778
1
Parent(s): 8f2e8ae
Layer corpus preparation and search position persistence
Browse files- backend/app.py +68 -120
- backend/search/corpus/__init__.py +1 -0
- backend/search/corpus/application/__init__.py +1 -0
- backend/search/corpus/application/preparation.py +129 -0
- backend/search/corpus/domain/__init__.py +1 -0
- backend/search/corpus/domain/metadata.py +77 -0
- config/types/jsconfig.check.json +4 -0
- config/types/jsconfig.search-exact.json +4 -0
- config/types/jsconfig.strict.json +4 -0
- eslint.config.mjs +1 -1
- pyrightconfig.strict.json +5 -0
- scripts/build/check_reader_release.mjs +1 -0
- scripts/build/compose_app.mjs +1 -0
- static/app.js +24 -224
- static/index.html +3 -0
- static/reader-resources.js +1 -0
- static/search/positions/application/persistence.js +138 -0
- static/search/positions/domain/policy.js +49 -0
- static/search/positions/infrastructure/indexed-db.js +134 -0
- static/search/search-session.js +1 -1
- static/sw.js +3 -0
- tests/backend/test_coverage_safety.py +105 -0
- tests/search/browser/test_position_controls.py +3 -3
- tests/search/browser/test_position_window.py +13 -13
- tests/search/browser/test_prefetch_pipeline.py +3 -3
- tests/search/browser/test_recent_search_pages.py +28 -28
- tests/search/browser/test_search_positions.py +19 -20
- tests/search/browser/test_search_session_browser.py +4 -4
- tests/search/build/test_search_record_path_build.mjs +2 -1
- tests/search/reader-navigation/test_search_history_races.mjs +1 -0
- tests/search/session/test_positions_persistence.mjs +137 -0
- tests/support/classic_search_modules.js +3 -1
- typings/reader-globals.d.ts +1 -0
- typings/search-positions.d.ts +55 -0
backend/app.py
CHANGED
|
@@ -97,6 +97,13 @@ from backend.search.http.responses import (
|
|
| 97 |
SearchCacheIdentity, SearchResponseDependencies, build_search_api_response as _build_search_api_response,
|
| 98 |
build_response as _build_response, search_method_not_allowed, search_repo_not_found, search_validation_response,
|
| 99 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
from backend.search_transport import SearchBodyLimitMiddleware
|
| 101 |
from backend.search_indexes import (
|
| 102 |
NGRAM_MAGIC as NGRAM_MAGIC, WORD_INDEX_MAGIC as WORD_INDEX_MAGIC,
|
|
@@ -110,8 +117,9 @@ from backend.reader_assets import (
|
|
| 110 |
from backend.reader_v3_catalog import load_reading_catalog, merge_sidecar as merge_v3_sidecar
|
| 111 |
from backend.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell
|
| 112 |
from backend.data_formats import (
|
| 113 |
-
decode_browser_entry as decode_browser_entry, decode_folder_browser_data
|
| 114 |
-
|
|
|
|
| 115 |
)
|
| 116 |
from backend.record_metadata import (
|
| 117 |
READER_ASSET_MODES as READER_ASSET_MODES,
|
|
@@ -547,37 +555,10 @@ def build_indexes(build_words: bool = True, build_reader: bool = True):
|
|
| 547 |
reader_legacy_source_id_indices = {}
|
| 548 |
_reader_indexes_ready = False
|
| 549 |
_reader_index_build = None
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
if ext:
|
| 555 |
-
extension_counts[ext] = extension_counts.get(ext, 0) + 1
|
| 556 |
-
extension_records_map.setdefault(ext, []).append(idx)
|
| 557 |
-
repo_ext = repo_extension_counts.setdefault(repo, {})
|
| 558 |
-
repo_ext[ext] = repo_ext.get(ext, 0) + 1
|
| 559 |
-
file_name = cast(str, rec.get("File", ""))
|
| 560 |
-
original_extension = cast(str, rec.get("Extension") or "")
|
| 561 |
-
folders = cast(list[str], rec.get("Folder", []))
|
| 562 |
-
if repo not in folder_index:
|
| 563 |
-
folder_index[repo] = {}
|
| 564 |
-
for depth in range(len(folders) + 1):
|
| 565 |
-
folder_path = "/".join(folders[:depth]) if depth > 0 else ""
|
| 566 |
-
folder_index[repo].setdefault(folder_path, []).append(idx)
|
| 567 |
-
repo_records_map.setdefault(repo, []).append(idx)
|
| 568 |
-
folders_lower = [f.lower() for f in (folders or [])]
|
| 569 |
-
rec["_file_lower"] = file_name.lower()
|
| 570 |
-
rec["_full_file_lower"] = (file_name + ("." + original_extension if original_extension else "")).lower()
|
| 571 |
-
rec["_folders_lower"] = folders_lower
|
| 572 |
-
rec["_folder_text"] = " ".join(folders_lower)
|
| 573 |
-
rec["_folder_path_lower"] = "/".join(folders_lower)
|
| 574 |
-
rec["_folder_path"] = "/".join(folders)
|
| 575 |
-
rec["_ext_lower"] = ext
|
| 576 |
-
rec["_repo_lower"] = repo.lower()
|
| 577 |
-
repo_list = sorted(
|
| 578 |
-
[RepoSummary(name=r, count=c) for r, c in repo_counts.items()],
|
| 579 |
-
key=lambda x: x["name"],
|
| 580 |
-
)
|
| 581 |
if build_words:
|
| 582 |
build_word_index()
|
| 583 |
else:
|
|
@@ -586,102 +567,69 @@ def build_indexes(build_words: bool = True, build_reader: bool = True):
|
|
| 586 |
vocab_by_len = {}
|
| 587 |
extension_list = sorted(extension_counts.keys())
|
| 588 |
all_indices = list(range(len(records)))
|
| 589 |
-
sorted_by_name =
|
| 590 |
-
sorted_by_size =
|
| 591 |
-
-_record_size(records[i]),
|
| 592 |
-
cast(str, records[i].get("File") or "").lower(),
|
| 593 |
-
))
|
| 594 |
for repo, repo_indices in repo_records_map.items():
|
| 595 |
-
repo_sorted_by_name[repo] =
|
| 596 |
-
repo_sorted_by_size[repo] =
|
| 597 |
-
-_record_size(records[i]),
|
| 598 |
-
cast(str, records[i].get("File") or "").lower(),
|
| 599 |
-
))
|
| 600 |
# These complete, ordered postings are read-only after publication.
|
| 601 |
# Packed IDs avoid retaining a Python pointer (and often an int) per slot.
|
| 602 |
sorted_by_name = array('I', sorted_by_name)
|
| 603 |
sorted_by_size = array('I', sorted_by_size)
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
for key, indices in mapping.items():
|
| 607 |
-
mapping[key] = array('I', indices)
|
| 608 |
if build_reader:
|
| 609 |
_build_reader_indexes()
|
| 610 |
|
| 611 |
def search_data_generation(raw: bytes, index_paths: Iterable[Path]) -> str:
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
timings["words_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 661 |
-
stage_start = time.perf_counter()
|
| 662 |
-
loaded_ngrams = {
|
| 663 |
-
width: load_ngram_index(path, width, len(records), digest)
|
| 664 |
-
for width, path in NGRAM_PATHS.items()
|
| 665 |
-
}
|
| 666 |
-
ngram_postings = {width: loaded[0] for width, loaded in loaded_ngrams.items()}
|
| 667 |
-
ngram_posting_buffers = {width: loaded[1] for width, loaded in loaded_ngrams.items()}
|
| 668 |
-
timings["ngrams_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 669 |
-
stage_start = time.perf_counter()
|
| 670 |
-
_search_generation = search_data_generation(raw, [WORD_INDEX_PATH, *NGRAM_PATHS.values()])
|
| 671 |
-
timings["fingerprint_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 672 |
-
print(f"🧭 已加载词索引: {len(word_index)}")
|
| 673 |
-
print(f"🔎 已加载 ngram 索引: 2={len(ngram_postings[2])}, 3={len(ngram_postings[3])}")
|
| 674 |
-
build_initial_payloads()
|
| 675 |
-
precompute_injected_html()
|
| 676 |
-
del raw
|
| 677 |
-
stage_start = time.perf_counter()
|
| 678 |
-
# A generated postings file avoids corpus tokenization, but query tokenization
|
| 679 |
-
# still needs jieba's dictionary. Prepare it before accepting the first query,
|
| 680 |
-
# after releasing the decoded source and finishing index-loading temporaries.
|
| 681 |
-
jieba.initialize()
|
| 682 |
-
timings["tokenizer_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 683 |
-
timings["total_ms"] = round((time.perf_counter() - start) * 1000, 2)
|
| 684 |
-
print("search_performance " + json.dumps({"stage": "startup", "word_index": word_index_source, **timings}))
|
| 685 |
|
| 686 |
def score_record(rec_idx: int, query_tokens: Iterable[str], search_folders: bool = True) -> int:
|
| 687 |
return _score_record(records[rec_idx], query_tokens, search_folders)
|
|
|
|
| 97 |
SearchCacheIdentity, SearchResponseDependencies, build_search_api_response as _build_search_api_response,
|
| 98 |
build_response as _build_response, search_method_not_allowed, search_repo_not_found, search_validation_response,
|
| 99 |
)
|
| 100 |
+
from backend.search.corpus.application.preparation import (
|
| 101 |
+
CorpusPaths, CorpusPublication, PreparationDependencies,
|
| 102 |
+
load_data as _load_corpus, search_data_generation as _corpus_generation,
|
| 103 |
+
)
|
| 104 |
+
from backend.search.corpus.domain.metadata import (
|
| 105 |
+
MetadataMaps, populate_metadata, name_order, size_order, pack_postings,
|
| 106 |
+
)
|
| 107 |
from backend.search_transport import SearchBodyLimitMiddleware
|
| 108 |
from backend.search_indexes import (
|
| 109 |
NGRAM_MAGIC as NGRAM_MAGIC, WORD_INDEX_MAGIC as WORD_INDEX_MAGIC,
|
|
|
|
| 117 |
from backend.reader_v3_catalog import load_reading_catalog, merge_sidecar as merge_v3_sidecar
|
| 118 |
from backend.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell
|
| 119 |
from backend.data_formats import (
|
| 120 |
+
decode_browser_entry as decode_browser_entry, decode_folder_browser_data as decode_folder_browser_data,
|
| 121 |
+
decode_folder_tree_data as decode_folder_tree_data, decode_search_payload as decode_search_payload,
|
| 122 |
+
decode_tree_node as decode_tree_node,
|
| 123 |
)
|
| 124 |
from backend.record_metadata import (
|
| 125 |
READER_ASSET_MODES as READER_ASSET_MODES,
|
|
|
|
| 555 |
reader_legacy_source_id_indices = {}
|
| 556 |
_reader_indexes_ready = False
|
| 557 |
_reader_index_build = None
|
| 558 |
+
repo_list = populate_metadata(records, MetadataMaps(
|
| 559 |
+
folder_index, extension_counts, extension_records_map,
|
| 560 |
+
repo_extension_counts, repo_counts, repo_records_map,
|
| 561 |
+
))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
if build_words:
|
| 563 |
build_word_index()
|
| 564 |
else:
|
|
|
|
| 567 |
vocab_by_len = {}
|
| 568 |
extension_list = sorted(extension_counts.keys())
|
| 569 |
all_indices = list(range(len(records)))
|
| 570 |
+
sorted_by_name = name_order(_candidate_records, all_indices)
|
| 571 |
+
sorted_by_size = size_order(_candidate_records, all_indices, lambda record: _record_size(record))
|
|
|
|
|
|
|
|
|
|
| 572 |
for repo, repo_indices in repo_records_map.items():
|
| 573 |
+
repo_sorted_by_name[repo] = name_order(_candidate_records, repo_indices)
|
| 574 |
+
repo_sorted_by_size[repo] = size_order(_candidate_records, repo_indices, lambda record: _record_size(record))
|
|
|
|
|
|
|
|
|
|
| 575 |
# These complete, ordered postings are read-only after publication.
|
| 576 |
# Packed IDs avoid retaining a Python pointer (and often an int) per slot.
|
| 577 |
sorted_by_name = array('I', sorted_by_name)
|
| 578 |
sorted_by_size = array('I', sorted_by_size)
|
| 579 |
+
pack_postings(repo_records_map, repo_sorted_by_name, repo_sorted_by_size,
|
| 580 |
+
extension_records_map, *folder_index.values())
|
|
|
|
|
|
|
| 581 |
if build_reader:
|
| 582 |
_build_reader_indexes()
|
| 583 |
|
| 584 |
def search_data_generation(raw: bytes, index_paths: Iterable[Path]) -> str:
|
| 585 |
+
return _corpus_generation(raw, index_paths, semantics=SEARCH_SEMANTICS_VERSION,
|
| 586 |
+
python_version=str(sys.version_info[:3]), tokenizer_version=jieba.__version__)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def load_data() -> None:
|
| 590 |
+
# Assign each phase immediately, including partial state on later failure.
|
| 591 |
+
def publish_records(value: list[SearchRecord]) -> None:
|
| 592 |
+
global records
|
| 593 |
+
records = value
|
| 594 |
+
|
| 595 |
+
def publish_tree(value: dict[str, list[JsonObject]]) -> None:
|
| 596 |
+
global folder_tree_data
|
| 597 |
+
folder_tree_data = value
|
| 598 |
+
|
| 599 |
+
def publish_browser(value: dict[str, dict[str, JsonObject]]) -> None:
|
| 600 |
+
global folder_browser_data
|
| 601 |
+
folder_browser_data = value
|
| 602 |
+
|
| 603 |
+
def publish_words(value: PostingIndex, buffer: bytes) -> None:
|
| 604 |
+
global word_index, word_index_buffer
|
| 605 |
+
word_index, word_index_buffer = value, buffer
|
| 606 |
+
|
| 607 |
+
def publish_ngrams(value: dict[int, PostingIndex], buffers: dict[int, bytes]) -> None:
|
| 608 |
+
global ngram_postings, ngram_posting_buffers
|
| 609 |
+
ngram_postings, ngram_posting_buffers = value, buffers
|
| 610 |
+
|
| 611 |
+
def publish_generation(value: str) -> None:
|
| 612 |
+
global _search_generation
|
| 613 |
+
_search_generation = value
|
| 614 |
+
|
| 615 |
+
_load_corpus(
|
| 616 |
+
lambda: CorpusPaths(DATA_PATH, FOLDER_TREE_PATH, FOLDER_BROWSER_PATH, WORD_INDEX_PATH, NGRAM_PATHS),
|
| 617 |
+
CorpusPublication(publish_records, publish_tree, publish_browser, publish_words,
|
| 618 |
+
publish_ngrams, publish_generation),
|
| 619 |
+
PreparationDependencies(
|
| 620 |
+
decode_records=lambda value: decode_search_payload(value),
|
| 621 |
+
decode_tree=lambda value: decode_folder_tree_data(value),
|
| 622 |
+
decode_browser=lambda value: decode_folder_browser_data(value),
|
| 623 |
+
build_metadata=lambda: build_indexes(build_words=False, build_reader=False),
|
| 624 |
+
record_count=lambda: len(records), records_digest=lambda: records_digest(),
|
| 625 |
+
read_words=lambda path, count, digest: load_word_index(path, count, digest, materialize=False),
|
| 626 |
+
read_ngrams=lambda path, width, count, digest: load_ngram_index(path, width, count, digest),
|
| 627 |
+
build_words=lambda: build_word_index(), build_vocab=lambda: build_vocab_by_len(),
|
| 628 |
+
word_count=lambda: len(word_index), generation=lambda raw, paths: search_data_generation(raw, paths),
|
| 629 |
+
build_initial=lambda: build_initial_payloads(), precompute_html=lambda: precompute_injected_html(),
|
| 630 |
+
initialize_tokenizer=lambda: jieba.initialize(),
|
| 631 |
+
),
|
| 632 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 633 |
|
| 634 |
def score_record(rec_idx: int, query_tokens: Iterable[str], search_folders: bool = True) -> int:
|
| 635 |
return _score_record(records[rec_idx], query_tokens, search_folders)
|
backend/search/corpus/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Corpus preparation for search."""
|
backend/search/corpus/application/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Corpus loading and preparation phases."""
|
backend/search/corpus/application/preparation.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load the corpus and checked indexes, publishing each completed phase in order."""
|
| 2 |
+
|
| 3 |
+
import gzip
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import time
|
| 7 |
+
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]]
|
| 16 |
+
Browser = dict[str, dict[str, Record]]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass(frozen=True)
|
| 20 |
+
class CorpusPaths:
|
| 21 |
+
data: Path
|
| 22 |
+
tree: Path
|
| 23 |
+
browser: Path
|
| 24 |
+
words: Path
|
| 25 |
+
ngrams: dict[int, Path]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass(frozen=True)
|
| 29 |
+
class CorpusPublication:
|
| 30 |
+
records: Callable[[list[Record]], None]
|
| 31 |
+
tree: Callable[[Tree], None]
|
| 32 |
+
browser: Callable[[Browser], None]
|
| 33 |
+
words: Callable[[PostingIndex, bytes], None]
|
| 34 |
+
ngrams: Callable[[dict[int, PostingIndex], dict[int, bytes]], None]
|
| 35 |
+
generation: Callable[[str], None]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass(frozen=True)
|
| 39 |
+
class PreparationDependencies:
|
| 40 |
+
decode_records: Callable[[object], list[Record]]
|
| 41 |
+
decode_tree: Callable[[dict[str, list[CompactTreeNode]] | None], Tree]
|
| 42 |
+
decode_browser: Callable[[dict[str, dict[str, CompactBrowserEntry]] | None], Browser]
|
| 43 |
+
build_metadata: Callable[[], None]
|
| 44 |
+
record_count: Callable[[], int]
|
| 45 |
+
records_digest: Callable[[], bytes]
|
| 46 |
+
read_words: Callable[[Path, int, bytes], tuple[PostingIndex, bytes]]
|
| 47 |
+
read_ngrams: Callable[[Path, int, int, bytes], tuple[PostingIndex, bytes]]
|
| 48 |
+
build_words: Callable[[], None]
|
| 49 |
+
build_vocab: Callable[[], None]
|
| 50 |
+
word_count: Callable[[], int]
|
| 51 |
+
generation: Callable[[bytes, Iterable[Path]], str]
|
| 52 |
+
build_initial: Callable[[], None]
|
| 53 |
+
precompute_html: Callable[[], None]
|
| 54 |
+
initialize_tokenizer: Callable[[], None]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def search_data_generation(raw: bytes, index_paths: Iterable[Path], *,
|
| 58 |
+
semantics: str, python_version: str, tokenizer_version: str) -> str:
|
| 59 |
+
digest = hashlib.sha256()
|
| 60 |
+
digest.update(semantics.encode())
|
| 61 |
+
digest.update(python_version.encode())
|
| 62 |
+
digest.update(tokenizer_version.encode())
|
| 63 |
+
digest.update(hashlib.sha256(raw).digest())
|
| 64 |
+
for path in index_paths:
|
| 65 |
+
# Hash compressed index content, including the filename and missing marker.
|
| 66 |
+
digest.update(path.name.encode())
|
| 67 |
+
digest.update(hashlib.sha256(path.read_bytes()).digest() if path.exists() else b"missing")
|
| 68 |
+
return "api:" + digest.hexdigest()
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def load_data(paths: Callable[[], CorpusPaths], publish: CorpusPublication, deps: PreparationDependencies) -> None:
|
| 72 |
+
start = time.perf_counter()
|
| 73 |
+
stage_start = start
|
| 74 |
+
timings: dict[str, float] = {}
|
| 75 |
+
if paths().data.exists():
|
| 76 |
+
raw = gzip.decompress(paths().data.read_bytes())
|
| 77 |
+
publish.records(deps.decode_records(json.loads(raw.decode("utf-8"))))
|
| 78 |
+
else:
|
| 79 |
+
print("⚠ 数据文件不存在")
|
| 80 |
+
publish.records([])
|
| 81 |
+
return
|
| 82 |
+
if paths().tree.exists():
|
| 83 |
+
publish.tree(deps.decode_tree(json.loads(gzip.decompress(paths().tree.read_bytes()).decode("utf-8"))))
|
| 84 |
+
else:
|
| 85 |
+
publish.tree({})
|
| 86 |
+
if paths().browser.exists():
|
| 87 |
+
publish.browser(deps.decode_browser(json.loads(gzip.decompress(paths().browser.read_bytes()).decode("utf-8"))))
|
| 88 |
+
else:
|
| 89 |
+
publish.browser({})
|
| 90 |
+
timings["data_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 91 |
+
print(f"📖 已加载 {deps.record_count()} 条记录 ({time.perf_counter() - start:.2f}s)")
|
| 92 |
+
stage_start = time.perf_counter()
|
| 93 |
+
# Normal search startup leaves Reader ID/pool preparation lazy.
|
| 94 |
+
deps.build_metadata()
|
| 95 |
+
digest = deps.records_digest()
|
| 96 |
+
timings["metadata_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 97 |
+
stage_start = time.perf_counter()
|
| 98 |
+
words, buffer = deps.read_words(paths().words, deps.record_count(), digest)
|
| 99 |
+
publish.words(words, buffer)
|
| 100 |
+
word_index_source = "generated" if words else "rebuilt"
|
| 101 |
+
if words:
|
| 102 |
+
deps.build_vocab()
|
| 103 |
+
else:
|
| 104 |
+
publish.words(words, b"")
|
| 105 |
+
deps.build_words()
|
| 106 |
+
timings["words_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 107 |
+
stage_start = time.perf_counter()
|
| 108 |
+
loaded_ngrams = {
|
| 109 |
+
width: deps.read_ngrams(path, width, deps.record_count(), digest)
|
| 110 |
+
for width, path in paths().ngrams.items()
|
| 111 |
+
}
|
| 112 |
+
postings = {width: loaded[0] for width, loaded in loaded_ngrams.items()}
|
| 113 |
+
buffers = {width: loaded[1] for width, loaded in loaded_ngrams.items()}
|
| 114 |
+
publish.ngrams(postings, buffers)
|
| 115 |
+
timings["ngrams_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 116 |
+
stage_start = time.perf_counter()
|
| 117 |
+
publish.generation(deps.generation(raw, [paths().words, *paths().ngrams.values()]))
|
| 118 |
+
timings["fingerprint_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 119 |
+
print(f"🧭 已加载词索引: {deps.word_count()}")
|
| 120 |
+
print(f"🔎 已加载 ngram 索引: 2={len(postings[2])}, 3={len(postings[3])}")
|
| 121 |
+
deps.build_initial()
|
| 122 |
+
deps.precompute_html()
|
| 123 |
+
del raw
|
| 124 |
+
stage_start = time.perf_counter()
|
| 125 |
+
# Release source bytes before warming query tokenization.
|
| 126 |
+
deps.initialize_tokenizer()
|
| 127 |
+
timings["tokenizer_ms"] = round((time.perf_counter() - stage_start) * 1000, 2)
|
| 128 |
+
timings["total_ms"] = round((time.perf_counter() - start) * 1000, 2)
|
| 129 |
+
print("search_performance " + json.dumps({"stage": "startup", "word_index": word_index_source, **timings}))
|
backend/search/corpus/domain/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Corpus metadata and posting construction."""
|
backend/search/corpus/domain/metadata.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Derived corpus fields and mutable postings, populated in publication order."""
|
| 2 |
+
|
| 3 |
+
from array import array
|
| 4 |
+
from collections.abc import Callable, MutableSequence, Sequence
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import cast
|
| 7 |
+
|
| 8 |
+
from backend.catalog.application.metadata import RepoSummary
|
| 9 |
+
|
| 10 |
+
Record = dict[str, object]
|
| 11 |
+
Postings = MutableSequence[int]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass(frozen=True)
|
| 15 |
+
class MetadataMaps:
|
| 16 |
+
"""References to the fresh maps already published by the process owner."""
|
| 17 |
+
|
| 18 |
+
folders: dict[str, dict[str, Postings]]
|
| 19 |
+
extension_counts: dict[str, int]
|
| 20 |
+
extension_records: dict[str, Postings]
|
| 21 |
+
repo_extension_counts: dict[str, dict[str, int]]
|
| 22 |
+
repo_counts: dict[str, int]
|
| 23 |
+
repo_records: dict[str, Postings]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def populate_metadata(records: Sequence[Record], maps: MetadataMaps) -> list[RepoSummary]:
|
| 27 |
+
"""Keep earlier records and postings visible if a later record is malformed."""
|
| 28 |
+
for idx, rec in enumerate(records):
|
| 29 |
+
repo = cast(str, rec.get("Repo", ""))
|
| 30 |
+
maps.repo_counts[repo] = maps.repo_counts.get(repo, 0) + 1
|
| 31 |
+
ext = cast(str, rec.get("Extension") or "").lower()
|
| 32 |
+
if ext:
|
| 33 |
+
maps.extension_counts[ext] = maps.extension_counts.get(ext, 0) + 1
|
| 34 |
+
maps.extension_records.setdefault(ext, []).append(idx)
|
| 35 |
+
repo_ext = maps.repo_extension_counts.setdefault(repo, {})
|
| 36 |
+
repo_ext[ext] = repo_ext.get(ext, 0) + 1
|
| 37 |
+
file_name = cast(str, rec.get("File", ""))
|
| 38 |
+
original_extension = cast(str, rec.get("Extension") or "")
|
| 39 |
+
folders = cast(list[str], rec.get("Folder", []))
|
| 40 |
+
if repo not in maps.folders:
|
| 41 |
+
maps.folders[repo] = {}
|
| 42 |
+
for depth in range(len(folders) + 1):
|
| 43 |
+
folder_path = "/".join(folders[:depth]) if depth > 0 else ""
|
| 44 |
+
maps.folders[repo].setdefault(folder_path, []).append(idx)
|
| 45 |
+
maps.repo_records.setdefault(repo, []).append(idx)
|
| 46 |
+
folders_lower = [f.lower() for f in (folders or [])]
|
| 47 |
+
rec["_file_lower"] = file_name.lower()
|
| 48 |
+
rec["_full_file_lower"] = (file_name + ("." + original_extension if original_extension else "")).lower()
|
| 49 |
+
rec["_folders_lower"] = folders_lower
|
| 50 |
+
rec["_folder_text"] = " ".join(folders_lower)
|
| 51 |
+
rec["_folder_path_lower"] = "/".join(folders_lower)
|
| 52 |
+
rec["_folder_path"] = "/".join(folders)
|
| 53 |
+
rec["_ext_lower"] = ext
|
| 54 |
+
rec["_repo_lower"] = repo.lower()
|
| 55 |
+
return sorted(
|
| 56 |
+
[RepoSummary(name=repo, count=count) for repo, count in maps.repo_counts.items()],
|
| 57 |
+
key=lambda item: item["name"],
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def name_order(read_records: Callable[[], Sequence[Record]], indices: Sequence[int]) -> list[int]:
|
| 62 |
+
return sorted(indices, key=lambda i: cast(str, read_records()[i].get("File") or "").lower())
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def size_order(read_records: Callable[[], Sequence[Record]], indices: Sequence[int],
|
| 66 |
+
size: Callable[[Record], int | float]) -> list[int]:
|
| 67 |
+
return sorted(indices, key=lambda i: (
|
| 68 |
+
-size(read_records()[i]),
|
| 69 |
+
cast(str, read_records()[i].get("File") or "").lower(),
|
| 70 |
+
))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def pack_postings(*mappings: dict[str, Postings]) -> None:
|
| 74 |
+
"""Replace each completed posting in place; retain the published map identity."""
|
| 75 |
+
for mapping in mappings:
|
| 76 |
+
for key, indices in mapping.items():
|
| 77 |
+
mapping[key] = array('I', indices)
|
config/types/jsconfig.check.json
CHANGED
|
@@ -87,6 +87,10 @@
|
|
| 87 |
"../../static/search/download-controller.js",
|
| 88 |
"../../static/search/reader-navigation.js",
|
| 89 |
"../../typings/search-reader-host.d.ts",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
"../../static/search/reader-host/presentation/return-position.js",
|
| 91 |
"../../static/search/reader-host/application/host.js",
|
| 92 |
"../../static/search/search-session.js",
|
|
|
|
| 87 |
"../../static/search/download-controller.js",
|
| 88 |
"../../static/search/reader-navigation.js",
|
| 89 |
"../../typings/search-reader-host.d.ts",
|
| 90 |
+
"../../typings/search-positions.d.ts",
|
| 91 |
+
"../../static/search/positions/domain/policy.js",
|
| 92 |
+
"../../static/search/positions/infrastructure/indexed-db.js",
|
| 93 |
+
"../../static/search/positions/application/persistence.js",
|
| 94 |
"../../static/search/reader-host/presentation/return-position.js",
|
| 95 |
"../../static/search/reader-host/application/host.js",
|
| 96 |
"../../static/search/search-session.js",
|
config/types/jsconfig.search-exact.json
CHANGED
|
@@ -16,6 +16,10 @@
|
|
| 16 |
"../../static/search/search-session.js",
|
| 17 |
"../../static/search/reader-navigation.js",
|
| 18 |
"../../typings/search-reader-host.d.ts",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
"../../static/search/reader-host/presentation/return-position.js",
|
| 20 |
"../../static/search/reader-host/application/host.js",
|
| 21 |
"../../static/search/download-controller.js",
|
|
|
|
| 16 |
"../../static/search/search-session.js",
|
| 17 |
"../../static/search/reader-navigation.js",
|
| 18 |
"../../typings/search-reader-host.d.ts",
|
| 19 |
+
"../../typings/search-positions.d.ts",
|
| 20 |
+
"../../static/search/positions/domain/policy.js",
|
| 21 |
+
"../../static/search/positions/infrastructure/indexed-db.js",
|
| 22 |
+
"../../static/search/positions/application/persistence.js",
|
| 23 |
"../../static/search/reader-host/presentation/return-position.js",
|
| 24 |
"../../static/search/reader-host/application/host.js",
|
| 25 |
"../../static/search/download-controller.js",
|
config/types/jsconfig.strict.json
CHANGED
|
@@ -69,6 +69,10 @@
|
|
| 69 |
"../../static/search/search-session.js",
|
| 70 |
"../../static/search/reader-navigation.js",
|
| 71 |
"../../typings/search-reader-host.d.ts",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
"../../static/search/reader-host/presentation/return-position.js",
|
| 73 |
"../../static/search/reader-host/application/host.js",
|
| 74 |
"../../static/search/download-controller.js",
|
|
|
|
| 69 |
"../../static/search/search-session.js",
|
| 70 |
"../../static/search/reader-navigation.js",
|
| 71 |
"../../typings/search-reader-host.d.ts",
|
| 72 |
+
"../../typings/search-positions.d.ts",
|
| 73 |
+
"../../static/search/positions/domain/policy.js",
|
| 74 |
+
"../../static/search/positions/infrastructure/indexed-db.js",
|
| 75 |
+
"../../static/search/positions/application/persistence.js",
|
| 76 |
"../../static/search/reader-host/presentation/return-position.js",
|
| 77 |
"../../static/search/reader-host/application/host.js",
|
| 78 |
"../../static/search/download-controller.js",
|
eslint.config.mjs
CHANGED
|
@@ -21,7 +21,7 @@ export default [
|
|
| 21 |
module: "readonly", require: "readonly",
|
| 22 |
...Object.fromEntries(["VoiceOfMLReaderSecurity", "VoiceOfMLReader", "VoiceOfMLReaderResources",
|
| 23 |
"VoiceOfMLReaderStore", "VoiceOfMLReaderChapters", "VoiceOfMLReaderVirtual", "VoiceOfMLReaderNavigation", "VoiceOfMLReaderHost", "VoiceOfMLReaderReturn",
|
| 24 |
-
"VoiceOfMLDownloadController", "VoiceOfMLSearchSession", "VoiceOfMLReaderRequests", "VoiceOfMLReaderRuntime",
|
| 25 |
"VoiceOfMLReaderAdapters", "VoiceOfMLReaderScroll", "DOMPurify", "marked"]
|
| 26 |
.map(name => [name, "readonly"])) }
|
| 27 |
},
|
|
|
|
| 21 |
module: "readonly", require: "readonly",
|
| 22 |
...Object.fromEntries(["VoiceOfMLReaderSecurity", "VoiceOfMLReader", "VoiceOfMLReaderResources",
|
| 23 |
"VoiceOfMLReaderStore", "VoiceOfMLReaderChapters", "VoiceOfMLReaderVirtual", "VoiceOfMLReaderNavigation", "VoiceOfMLReaderHost", "VoiceOfMLReaderReturn",
|
| 24 |
+
"VoiceOfMLDownloadController", "VoiceOfMLSearchSession", "VoiceOfMLPositionPolicy", "VoiceOfMLPositionStorage", "VoiceOfMLSearchPositions", "VoiceOfMLSearchWindowPage", "VoiceOfMLReaderRequests", "VoiceOfMLReaderRuntime",
|
| 25 |
"VoiceOfMLReaderAdapters", "VoiceOfMLReaderScroll", "DOMPurify", "marked"]
|
| 26 |
.map(name => [name, "readonly"])) }
|
| 27 |
},
|
pyrightconfig.strict.json
CHANGED
|
@@ -9,6 +9,11 @@
|
|
| 9 |
"backend/catalog/http/responses.py",
|
| 10 |
"backend/search_execution.py",
|
| 11 |
"backend/search/__init__.py",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
"backend/search/application/__init__.py",
|
| 13 |
"backend/search/application/requests.py",
|
| 14 |
"backend/search/application/execution.py",
|
|
|
|
| 9 |
"backend/catalog/http/responses.py",
|
| 10 |
"backend/search_execution.py",
|
| 11 |
"backend/search/__init__.py",
|
| 12 |
+
"backend/search/corpus/__init__.py",
|
| 13 |
+
"backend/search/corpus/application/__init__.py",
|
| 14 |
+
"backend/search/corpus/application/preparation.py",
|
| 15 |
+
"backend/search/corpus/domain/__init__.py",
|
| 16 |
+
"backend/search/corpus/domain/metadata.py",
|
| 17 |
"backend/search/application/__init__.py",
|
| 18 |
"backend/search/application/requests.py",
|
| 19 |
"backend/search/application/execution.py",
|
scripts/build/check_reader_release.mjs
CHANGED
|
@@ -272,6 +272,7 @@ function crossCheck(githubRoot, hfRoot) {
|
|
| 272 |
"search/presentation/sidebar-render.js",
|
| 273 |
"search/reader-navigation.js",
|
| 274 |
"search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js",
|
|
|
|
| 275 |
"reader.css",
|
| 276 |
"reader/core/reader-request-manager.js",
|
| 277 |
"reader/formats/reader-chapter-repository.js",
|
|
|
|
| 272 |
"search/presentation/sidebar-render.js",
|
| 273 |
"search/reader-navigation.js",
|
| 274 |
"search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js",
|
| 275 |
+
"search/positions/domain/policy.js", "search/positions/infrastructure/indexed-db.js", "search/positions/application/persistence.js",
|
| 276 |
"reader.css",
|
| 277 |
"reader/core/reader-request-manager.js",
|
| 278 |
"reader/formats/reader-chapter-repository.js",
|
scripts/build/compose_app.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { pathToFileURL } from "node:url";
|
|
| 7 |
export const APP_DEPENDENCIES = Object.freeze([
|
| 8 |
"reader-resources.js", "reader/core/reader-contract.js", "search/reader-navigation.js",
|
| 9 |
"search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js",
|
|
|
|
| 10 |
"search/search-session.js", "search/download-controller.js", "search/size-format.js", "search/record-path.js",
|
| 11 |
"search/highlight.js", "search/response-cache.js", "search/file-types.js", "search/response-validation.js", "search/result-identity.js",
|
| 12 |
"search/input/domain/ownership.js", "search/input/application/controller.js",
|
|
|
|
| 7 |
export const APP_DEPENDENCIES = Object.freeze([
|
| 8 |
"reader-resources.js", "reader/core/reader-contract.js", "search/reader-navigation.js",
|
| 9 |
"search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js",
|
| 10 |
+
"search/positions/domain/policy.js", "search/positions/infrastructure/indexed-db.js", "search/positions/application/persistence.js",
|
| 11 |
"search/search-session.js", "search/download-controller.js", "search/size-format.js", "search/record-path.js",
|
| 12 |
"search/highlight.js", "search/response-cache.js", "search/file-types.js", "search/response-validation.js", "search/result-identity.js",
|
| 13 |
"search/input/domain/ownership.js", "search/input/application/controller.js",
|
static/app.js
CHANGED
|
@@ -322,12 +322,12 @@ const SEARCH_VIEW_SNAPSHOT_VERSION = 1;
|
|
| 322 |
const searchViewSnapshots = new Map();
|
| 323 |
const SEARCH_VIEW_SNAPSHOT_MAX = 20;
|
| 324 |
const SEARCH_VIEW_SNAPSHOT_BYTES_MAX = 8 * 1024 * 1024;
|
| 325 |
-
const
|
| 326 |
-
const
|
| 327 |
-
|
| 328 |
-
|
|
|
|
| 329 |
let displayedSearchView = null;
|
| 330 |
-
let positionSaveTimer = null;
|
| 331 |
let positionRestore = null;
|
| 332 |
let resultWindow = null;
|
| 333 |
let returnPositionTarget = null;
|
|
@@ -350,7 +350,7 @@ function resetPositionControlScroll() {
|
|
| 350 |
|
| 351 |
function prepareReturnPosition(key, updateControls = true) {
|
| 352 |
resetPositionControlScroll();
|
| 353 |
-
const saved =
|
| 354 |
setReturnPositionTarget(validSearchPosition(saved) && (saved.index > 0 || saved.offset > 0) ? saved : null);
|
| 355 |
if (updateControls) updateSearchPositionControls();
|
| 356 |
}
|
|
@@ -484,7 +484,6 @@ function setupSearchPositionControls() {
|
|
| 484 |
else updateCurrentResultPosition();
|
| 485 |
});
|
| 486 |
}
|
| 487 |
-
let lastPositionPruneAt = 0;
|
| 488 |
let displayedViewRevision = 0;
|
| 489 |
let measuredHeightRevision = 0;
|
| 490 |
const searchSnapshotSources = new WeakMap();
|
|
@@ -492,101 +491,16 @@ const searchSnapshotResultBudgets = new WeakMap();
|
|
| 492 |
const searchSnapshotHeightValues = new WeakMap();
|
| 493 |
const searchSnapshotCloneSources = new WeakMap();
|
| 494 |
let snapshotCloneTask = null;
|
| 495 |
-
const searchViewportSnapshots = new Map();
|
| 496 |
-
const SEARCH_VIEWPORT_MAX = 64;
|
| 497 |
-
const SEARCH_VIEWPORT_BYTES_MAX = 64 * 1024;
|
| 498 |
const resultRowRecords = new WeakMap();
|
| 499 |
-
const searchViewportSources = new WeakMap();
|
| 500 |
const searchPageMetadata = new WeakMap();
|
| 501 |
-
const recentSearchPages = new Map();
|
| 502 |
-
const recentSearchPageSources = new WeakMap();
|
| 503 |
-
const RECENT_SEARCH_PAGE_MAX = 32;
|
| 504 |
-
const RECENT_SEARCH_PAGE_BYTES_MAX = 256 * 1024;
|
| 505 |
-
const RECENT_SEARCH_PAGE_TTL = 7 * 24 * 60 * 60 * 1000;
|
| 506 |
|
| 507 |
function rememberSearchPageMetadata(data) {
|
| 508 |
if (data?.results?.[0] && typeof data.generation === "string") searchPageMetadata.set(data.results[0], {
|
| 509 |
generation: data.generation, total: data.total, page: data.page, page_size: data.page_size });
|
| 510 |
}
|
| 511 |
|
| 512 |
-
function cacheRecentSearchPage(entry) {
|
| 513 |
-
const id = JSON.stringify(entry.id);
|
| 514 |
-
recentSearchPages.delete(id); recentSearchPages.set(id, entry);
|
| 515 |
-
while (recentSearchPages.size > RECENT_SEARCH_PAGE_MAX) recentSearchPages.delete(recentSearchPages.keys().next().value);
|
| 516 |
-
}
|
| 517 |
-
|
| 518 |
-
function pruneSearchContentStore(store, limit, ttl) {
|
| 519 |
-
const index = store.index("savedAt");
|
| 520 |
-
const expired = index.openKeyCursor(IDBKeyRange.upperBound(Date.now() - ttl, true));
|
| 521 |
-
expired.onsuccess = event => {
|
| 522 |
-
const cursor = event.target.result;
|
| 523 |
-
if (cursor) { store.delete(cursor.primaryKey); cursor.continue(); }
|
| 524 |
-
};
|
| 525 |
-
let skipped = false;
|
| 526 |
-
index.openKeyCursor(null, "prev").onsuccess = event => {
|
| 527 |
-
const cursor = event.target.result;
|
| 528 |
-
if (!cursor) return;
|
| 529 |
-
// Jump over retained keys inside IndexedDB instead of visiting each in JS.
|
| 530 |
-
if (!skipped) { skipped = true; cursor.advance(limit); return; }
|
| 531 |
-
store.delete(cursor.primaryKey); cursor.continue();
|
| 532 |
-
};
|
| 533 |
-
}
|
| 534 |
-
|
| 535 |
-
function saveRecentSearchPages(position, view, visibleEnd) {
|
| 536 |
-
const size = JSON.parse(view.key).pageSize;
|
| 537 |
-
let store;
|
| 538 |
-
for (let page = Math.floor(position.index / size) + 1; page <= Math.floor(visibleEnd / size) + 1; page++) {
|
| 539 |
-
const start = (page - 1) * size, length = Math.min(size, view.total - start);
|
| 540 |
-
const metadata = view.window || searchPageMetadata.get(view.results[start]);
|
| 541 |
-
if (!metadata?.generation || metadata.total !== view.total || (view.window && !view.window.pages.has(page))) continue;
|
| 542 |
-
const id = [view.key, page], previous = recentSearchPages.get(JSON.stringify(id));
|
| 543 |
-
const source = previous && recentSearchPageSources.get(previous);
|
| 544 |
-
if (source?.first === view.results[start] && source.last === view.results[start + length - 1]
|
| 545 |
-
&& previous.generation === metadata.generation && Date.now() - previous.savedAt < 60000) {
|
| 546 |
-
cacheRecentSearchPage(previous); continue;
|
| 547 |
-
}
|
| 548 |
-
const results = view.results.slice(start, start + length);
|
| 549 |
-
if (results.length !== length || Object.keys(results).length !== length || results.some(record => !record)) continue;
|
| 550 |
-
const entry = { id, key: view.key, page, page_size: size, total: view.total, generation: metadata.generation,
|
| 551 |
-
results: results.map(cloneSearchResult), savedAt: Date.now() };
|
| 552 |
-
if (new TextEncoder().encode(JSON.stringify(entry)).byteLength > RECENT_SEARCH_PAGE_BYTES_MAX) continue;
|
| 553 |
-
cacheRecentSearchPage(entry);
|
| 554 |
-
recentSearchPageSources.set(entry, {first: results[0], last: results[length - 1]});
|
| 555 |
-
if (searchPositionDB?.objectStoreNames.contains("recent-pages")) try {
|
| 556 |
-
if (!store) store = searchPositionDB.transaction("recent-pages", "readwrite").objectStore("recent-pages");
|
| 557 |
-
store.put(entry);
|
| 558 |
-
} catch (_) {}
|
| 559 |
-
}
|
| 560 |
-
if (store) try { pruneSearchContentStore(store, RECENT_SEARCH_PAGE_MAX, RECENT_SEARCH_PAGE_TTL); } catch (_) {}
|
| 561 |
-
}
|
| 562 |
-
|
| 563 |
async function readRecentSearchPage(key, page, expected, timeoutMs = 150, signal = null) {
|
| 564 |
-
|
| 565 |
-
let entry = recentSearchPages.get(JSON.stringify(id));
|
| 566 |
-
if (!entry && searchPositionDB?.objectStoreNames.contains("recent-pages")) entry = await new Promise(resolve => {
|
| 567 |
-
let settled = false;
|
| 568 |
-
const finish = value => {
|
| 569 |
-
if (settled) return;
|
| 570 |
-
settled = true;
|
| 571 |
-
clearTimeout(timer);
|
| 572 |
-
signal?.removeEventListener("abort", abort);
|
| 573 |
-
resolve(value);
|
| 574 |
-
};
|
| 575 |
-
const abort = () => finish(null);
|
| 576 |
-
const timer = setTimeout(abort, timeoutMs);
|
| 577 |
-
if (signal?.aborted) { abort(); return; }
|
| 578 |
-
signal?.addEventListener("abort", abort, { once: true });
|
| 579 |
-
try {
|
| 580 |
-
const request = searchPositionDB.transaction("recent-pages").objectStore("recent-pages").get(id);
|
| 581 |
-
request.onsuccess = () => finish(request.result);
|
| 582 |
-
request.onerror = abort;
|
| 583 |
-
} catch (_) { abort(); }
|
| 584 |
-
});
|
| 585 |
-
if (!entry || entry.key !== key || entry.savedAt < Date.now() - RECENT_SEARCH_PAGE_TTL || !expected.generation
|
| 586 |
-
|| !Array.isArray(entry.results) || Object.keys(entry.results).length !== entry.results.length) return null;
|
| 587 |
-
try { validatePositionWindowPage(entry, page, expected.query.pageSize, expected); } catch (_) { return null; }
|
| 588 |
-
cacheRecentSearchPage(entry);
|
| 589 |
-
return entry;
|
| 590 |
}
|
| 591 |
|
| 592 |
async function loadCachedPreviewPage(window, page) {
|
|
@@ -616,70 +530,19 @@ async function loadCachedPreviewPage(window, page) {
|
|
| 616 |
}
|
| 617 |
|
| 618 |
function saveSearchViewport(position, view) {
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
if (source && previous.total === view.total && previous.generation === generation
|
| 625 |
-
&& previous.measurementKey === getHeightMeasurementKey() && Date.now() - previous.savedAt < 24 * 60 * 60 * 1000) {
|
| 626 |
-
let covered = true;
|
| 627 |
-
for (let index = position.index; index <= visibleEnd; index++) {
|
| 628 |
-
const saved = source.get(index);
|
| 629 |
-
if (!saved || saved.record !== view.results[index] || saved.height !== (VSCROLL.heights[index] || VSCROLL.estimatedHeight)) { covered = false; break; }
|
| 630 |
-
}
|
| 631 |
-
if (covered) return;
|
| 632 |
-
}
|
| 633 |
-
const start = Math.max(0, position.index - 24);
|
| 634 |
-
const end = Math.min(view.results.length, position.index + 56);
|
| 635 |
-
const records = [];
|
| 636 |
-
for (let index = start; index < end; index++) {
|
| 637 |
-
if (view.results[index]) records.push([index, cloneSearchResult(view.results[index]), VSCROLL.heights[index] || VSCROLL.estimatedHeight]);
|
| 638 |
-
}
|
| 639 |
-
const viewport = { key: position.key, savedAt: position.savedAt, anchorId: position.anchorId, index: position.index,
|
| 640 |
-
total: view.total, generation, estimatedHeight: VSCROLL.estimatedHeight, measurementKey: getHeightMeasurementKey(), records: [] };
|
| 641 |
-
// API records can include long URLs. Spend the budget on the visible screen
|
| 642 |
-
// first, then its nearest neighbors, rather than discarding the whole preview.
|
| 643 |
-
const distance = index => Math.max(position.index - index, index - visibleEnd, 0);
|
| 644 |
-
records.sort((a, b) => distance(a[0]) - distance(b[0]) || a[0] - b[0]);
|
| 645 |
-
const encoder = new TextEncoder();
|
| 646 |
-
let bytes = encoder.encode(JSON.stringify(viewport)).byteLength;
|
| 647 |
-
for (const record of records) {
|
| 648 |
-
const cost = encoder.encode(JSON.stringify(record)).byteLength + 1;
|
| 649 |
-
if (bytes + cost > SEARCH_VIEWPORT_BYTES_MAX) continue;
|
| 650 |
-
viewport.records.push(record); bytes += cost;
|
| 651 |
-
}
|
| 652 |
-
viewport.records.sort((a, b) => a[0] - b[0]);
|
| 653 |
-
if (!viewport.records.some(([index]) => index === position.index)) return;
|
| 654 |
-
searchViewportSnapshots.delete(viewport.key);
|
| 655 |
-
searchViewportSnapshots.set(viewport.key, viewport);
|
| 656 |
-
searchViewportSources.set(viewport, new Map(viewport.records.map(([index, , height]) => [index, {record: view.results[index], height}])));
|
| 657 |
-
while (searchViewportSnapshots.size > SEARCH_VIEWPORT_MAX) searchViewportSnapshots.delete(searchViewportSnapshots.keys().next().value);
|
| 658 |
-
if (searchPositionDB?.objectStoreNames.contains("viewports")) try {
|
| 659 |
-
const tx = searchPositionDB.transaction("viewports", "readwrite"), store = tx.objectStore("viewports");
|
| 660 |
-
store.put(viewport);
|
| 661 |
-
pruneSearchContentStore(store, SEARCH_VIEWPORT_MAX, SEARCH_POSITION_TTL);
|
| 662 |
-
} catch (_) {}
|
| 663 |
}
|
| 664 |
|
| 665 |
async function readSearchViewport(key) {
|
| 666 |
-
|
| 667 |
-
if (!searchPositionDB?.objectStoreNames.contains("viewports")) return null;
|
| 668 |
-
return new Promise(resolve => {
|
| 669 |
-
const timer = setTimeout(() => resolve(null), 150);
|
| 670 |
-
try {
|
| 671 |
-
const request = searchPositionDB.transaction("viewports").objectStore("viewports").get(key);
|
| 672 |
-
request.onsuccess = () => { clearTimeout(timer); resolve(request.result); };
|
| 673 |
-
request.onerror = () => { clearTimeout(timer); resolve(null); };
|
| 674 |
-
} catch (_) { clearTimeout(timer); resolve(null); }
|
| 675 |
-
});
|
| 676 |
}
|
| 677 |
|
| 678 |
function validSearchViewport(viewport, position) {
|
| 679 |
-
return
|
| 680 |
-
&& viewport.savedAt >= Date.now() - SEARCH_POSITION_TTL && Number.isInteger(viewport.total) && viewport.total > position.index
|
| 681 |
-
&& Array.isArray(viewport.records) && viewport.records.length <= 80
|
| 682 |
-
&& viewport.records.some(([index, record]) => index === position.index && getResultStableId(record) === position.anchorId);
|
| 683 |
}
|
| 684 |
|
| 685 |
function showSavedSearchViewport(viewport, position, task) {
|
|
@@ -700,47 +563,11 @@ function showSavedSearchViewport(viewport, position, task) {
|
|
| 700 |
}
|
| 701 |
|
| 702 |
function validSearchPosition(value) {
|
| 703 |
-
return
|
| 704 |
-
&& Number.isInteger(value.index) && value.index >= 0
|
| 705 |
-
&& Number.isFinite(value.offset) && value.offset >= 0
|
| 706 |
-
&& Number.isInteger(value.loadedPage) && value.loadedPage >= 1
|
| 707 |
-
&& typeof value.anchorId === "string" && value.savedAt > Date.now() - SEARCH_POSITION_TTL;
|
| 708 |
}
|
| 709 |
|
| 710 |
async function initSearchPositions() {
|
| 711 |
-
await
|
| 712 |
-
let expired = false;
|
| 713 |
-
const timer = setTimeout(() => { expired = true; resolve(); }, 1500);
|
| 714 |
-
try {
|
| 715 |
-
const request = indexedDB.open("voice-search-positions", 4);
|
| 716 |
-
request.onupgradeneeded = () => {
|
| 717 |
-
const db = request.result;
|
| 718 |
-
for (const name of Array.from(db.objectStoreNames)) db.deleteObjectStore(name);
|
| 719 |
-
for (const name of ["positions", "viewports", "recent-pages"]) {
|
| 720 |
-
const store = db.createObjectStore(name, {keyPath: name === "recent-pages" ? "id" : "key"});
|
| 721 |
-
store.createIndex("savedAt", "savedAt");
|
| 722 |
-
}
|
| 723 |
-
};
|
| 724 |
-
request.onerror = request.onblocked = () => { expired = true; clearTimeout(timer); resolve(); };
|
| 725 |
-
request.onsuccess = () => {
|
| 726 |
-
if (expired) { request.result.close(); return; }
|
| 727 |
-
searchPositionDB = request.result;
|
| 728 |
-
searchPositionDB.onversionchange = () => { searchPositionDB.close(); searchPositionDB = null; };
|
| 729 |
-
const transaction = searchPositionDB.transaction("positions", "readwrite");
|
| 730 |
-
const store = transaction.objectStore("positions");
|
| 731 |
-
store.getAll().onsuccess = event => {
|
| 732 |
-
// The position store is capped at 500; read it in one database round trip.
|
| 733 |
-
let count = 0;
|
| 734 |
-
const values = event.target.result.sort((a, b) => b.savedAt - a.savedAt);
|
| 735 |
-
for (const value of values) {
|
| 736 |
-
if (!validSearchPosition(value) || ++count > SEARCH_POSITION_MAX) store.delete(value.key);
|
| 737 |
-
else if (!searchPositions.has(value.key)) searchPositions.set(value.key, value);
|
| 738 |
-
}
|
| 739 |
-
};
|
| 740 |
-
transaction.oncomplete = transaction.onabort = () => { clearTimeout(timer); resolve(); };
|
| 741 |
-
};
|
| 742 |
-
} catch (_) { clearTimeout(timer); resolve(); }
|
| 743 |
-
}));
|
| 744 |
}
|
| 745 |
|
| 746 |
function rememberDisplayedSearchView() {
|
|
@@ -759,52 +586,25 @@ function rememberDisplayedSearchView() {
|
|
| 759 |
}
|
| 760 |
|
| 761 |
function saveSearchPosition() {
|
| 762 |
-
|
| 763 |
const view = displayedSearchView;
|
| 764 |
const target = view && getReturnPositionTarget(view.key);
|
| 765 |
if (target) return target;
|
| 766 |
if (!view || positionRestore || readerHost.overlay || !view.results.length || !VSCROLL.heights.length) return null;
|
| 767 |
-
if (STATE.results !== view.results || (STATE.isLoading && view.key !== getSearchViewKey())) return
|
| 768 |
const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);
|
| 769 |
-
if (!view.results[index]) return
|
| 770 |
const position = { version: 1, key: view.key, index,
|
| 771 |
offset: Math.max(0, getResultScrollTop() - getVirtualOffset(index)),
|
| 772 |
anchorId: getResultStableId(view.results[index]), loadedPage: view.loadedPage,
|
| 773 |
savedAt: Date.now() };
|
| 774 |
-
|
| 775 |
-
if (previous && position.savedAt - previous.savedAt < 1000 && previous.index === position.index
|
| 776 |
-
&& previous.offset === position.offset && previous.anchorId === position.anchorId
|
| 777 |
-
&& previous.loadedPage === position.loadedPage) return previous;
|
| 778 |
-
// Initialization reads newest first; only sort when enforcing the small cap.
|
| 779 |
-
searchPositions.set(view.key, position);
|
| 780 |
-
saveSearchViewport(position, view);
|
| 781 |
-
const prune = Date.now() - lastPositionPruneAt >= 60000 || searchPositions.size > SEARCH_POSITION_MAX;
|
| 782 |
-
if (prune) {
|
| 783 |
-
const ordered = Array.from(searchPositions.values()).sort((a, b) => b.savedAt - a.savedAt);
|
| 784 |
-
ordered.forEach((item, i) => { if (!validSearchPosition(item) || i >= SEARCH_POSITION_MAX) searchPositions.delete(item.key); });
|
| 785 |
-
lastPositionPruneAt = Date.now();
|
| 786 |
-
}
|
| 787 |
-
if (searchPositionDB) try {
|
| 788 |
-
const transaction = searchPositionDB.transaction("positions", "readwrite");
|
| 789 |
-
const store = transaction.objectStore("positions");
|
| 790 |
-
store.put(position);
|
| 791 |
-
let count = 0;
|
| 792 |
-
if (prune) store.index("savedAt").openCursor(null, "prev").onsuccess = event => {
|
| 793 |
-
const cursor = event.target.result;
|
| 794 |
-
if (!cursor) return;
|
| 795 |
-
if (!validSearchPosition(cursor.value) || ++count > SEARCH_POSITION_MAX) cursor.delete();
|
| 796 |
-
cursor.continue();
|
| 797 |
-
};
|
| 798 |
-
transaction.onabort = () => {}; // Memory restoration still works if storage is unavailable.
|
| 799 |
-
} catch (_) {}
|
| 800 |
-
return position;
|
| 801 |
}
|
| 802 |
|
| 803 |
function setupSearchPositionSaving() {
|
| 804 |
DOM.resultsContainer.addEventListener("scroll", () => {
|
| 805 |
if (positionRestore || STATE.isLoading || displayedSearchView?.key !== getSearchViewKey()) return;
|
| 806 |
-
|
| 807 |
-
positionSaveTimer = setTimeout(saveSearchPosition, 250);
|
| 808 |
}, { passive: true });
|
| 809 |
// Query and route handlers save explicitly; capture only filters before mutation.
|
| 810 |
for (const type of ["change", "click"]) document.addEventListener(type, event => {
|
|
@@ -842,7 +642,7 @@ function cancelPositionRestore() {
|
|
| 842 |
|
| 843 |
function tryRestoreSearchPosition(key, options = {}) {
|
| 844 |
const previous = positionRestore?.key === key && positionRestore.failed && !options.position ? positionRestore : null;
|
| 845 |
-
let position = options.position || previous?.position ||
|
| 846 |
if (!validSearchPosition(position)) return false;
|
| 847 |
searchIntentId++;
|
| 848 |
cancelPendingSearchControls();
|
|
@@ -961,7 +761,7 @@ function applyValidatedSearchViewport(snapshot) {
|
|
| 961 |
setResultScrollTop(getVirtualOffset(Math.min(anchor.index, STATE.results.length - 1)) + anchor.offset);
|
| 962 |
VSCROLL.renderStart = -1; VSCROLL.renderEnd = -1;
|
| 963 |
rememberDisplayedSearchView(); renderVisible(); updateStatusBar(); updateLoadInfo(); updatePagingStatus();
|
| 964 |
-
|
| 965 |
}
|
| 966 |
|
| 967 |
function validatePositionWindowPage(data, page, pageSize, expected) {
|
|
@@ -1070,7 +870,7 @@ async function loadResultWindowPage(page, prefetch = false) {
|
|
| 1070 |
displayedSearchView = null;
|
| 1071 |
rememberDisplayedSearchView();
|
| 1072 |
renderVisible(); updateLoadInfo(); updatePagingStatus();
|
| 1073 |
-
|
| 1074 |
return true;
|
| 1075 |
} catch (error) {
|
| 1076 |
if (!resultWindowCurrent(window)) return false;
|
|
|
|
| 322 |
const searchViewSnapshots = new Map();
|
| 323 |
const SEARCH_VIEW_SNAPSHOT_MAX = 20;
|
| 324 |
const SEARCH_VIEW_SNAPSHOT_BYTES_MAX = 8 * 1024 * 1024;
|
| 325 |
+
const positionStorage = VoiceOfMLPositionStorage.create();
|
| 326 |
+
const positionPersistence = VoiceOfMLSearchPositions.create({
|
| 327 |
+
storage: positionStorage, cloneResult: record => cloneSearchResult(record),
|
| 328 |
+
metadata: record => searchPageMetadata.get(/** @type {object} */ (record))
|
| 329 |
+
});
|
| 330 |
let displayedSearchView = null;
|
|
|
|
| 331 |
let positionRestore = null;
|
| 332 |
let resultWindow = null;
|
| 333 |
let returnPositionTarget = null;
|
|
|
|
| 350 |
|
| 351 |
function prepareReturnPosition(key, updateControls = true) {
|
| 352 |
resetPositionControlScroll();
|
| 353 |
+
const saved = positionPersistence.getPosition(key);
|
| 354 |
setReturnPositionTarget(validSearchPosition(saved) && (saved.index > 0 || saved.offset > 0) ? saved : null);
|
| 355 |
if (updateControls) updateSearchPositionControls();
|
| 356 |
}
|
|
|
|
| 484 |
else updateCurrentResultPosition();
|
| 485 |
});
|
| 486 |
}
|
|
|
|
| 487 |
let displayedViewRevision = 0;
|
| 488 |
let measuredHeightRevision = 0;
|
| 489 |
const searchSnapshotSources = new WeakMap();
|
|
|
|
| 491 |
const searchSnapshotHeightValues = new WeakMap();
|
| 492 |
const searchSnapshotCloneSources = new WeakMap();
|
| 493 |
let snapshotCloneTask = null;
|
|
|
|
|
|
|
|
|
|
| 494 |
const resultRowRecords = new WeakMap();
|
|
|
|
| 495 |
const searchPageMetadata = new WeakMap();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
|
| 497 |
function rememberSearchPageMetadata(data) {
|
| 498 |
if (data?.results?.[0] && typeof data.generation === "string") searchPageMetadata.set(data.results[0], {
|
| 499 |
generation: data.generation, total: data.total, page: data.page, page_size: data.page_size });
|
| 500 |
}
|
| 501 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 502 |
async function readRecentSearchPage(key, page, expected, timeoutMs = 150, signal = null) {
|
| 503 |
+
return positionPersistence.readRecentPage(key, page, expected, timeoutMs, signal);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
}
|
| 505 |
|
| 506 |
async function loadCachedPreviewPage(window, page) {
|
|
|
|
| 530 |
}
|
| 531 |
|
| 532 |
function saveSearchViewport(position, view) {
|
| 533 |
+
positionPersistence.saveViewport(position, view, {
|
| 534 |
+
visibleEnd: findVirtualIndex(getResultScrollTop() + DOM.resultsContainer.clientHeight),
|
| 535 |
+
pageSize: STATE.pageSize, measurementKey: getHeightMeasurementKey(), estimatedHeight: VSCROLL.estimatedHeight,
|
| 536 |
+
heightAt: index => VSCROLL.heights[index] || VSCROLL.estimatedHeight
|
| 537 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
}
|
| 539 |
|
| 540 |
async function readSearchViewport(key) {
|
| 541 |
+
return positionPersistence.readViewport(key);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 542 |
}
|
| 543 |
|
| 544 |
function validSearchViewport(viewport, position) {
|
| 545 |
+
return VoiceOfMLPositionPolicy.validViewport(viewport, position, getResultStableId);
|
|
|
|
|
|
|
|
|
|
| 546 |
}
|
| 547 |
|
| 548 |
function showSavedSearchViewport(viewport, position, task) {
|
|
|
|
| 563 |
}
|
| 564 |
|
| 565 |
function validSearchPosition(value) {
|
| 566 |
+
return VoiceOfMLPositionPolicy.validPosition(value);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
}
|
| 568 |
|
| 569 |
async function initSearchPositions() {
|
| 570 |
+
await positionPersistence.init();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 571 |
}
|
| 572 |
|
| 573 |
function rememberDisplayedSearchView() {
|
|
|
|
| 586 |
}
|
| 587 |
|
| 588 |
function saveSearchPosition() {
|
| 589 |
+
positionPersistence.cancelSave();
|
| 590 |
const view = displayedSearchView;
|
| 591 |
const target = view && getReturnPositionTarget(view.key);
|
| 592 |
if (target) return target;
|
| 593 |
if (!view || positionRestore || readerHost.overlay || !view.results.length || !VSCROLL.heights.length) return null;
|
| 594 |
+
if (STATE.results !== view.results || (STATE.isLoading && view.key !== getSearchViewKey())) return positionPersistence.getPosition(view.key) || null;
|
| 595 |
const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);
|
| 596 |
+
if (!view.results[index]) return positionPersistence.getPosition(view.key) || null;
|
| 597 |
const position = { version: 1, key: view.key, index,
|
| 598 |
offset: Math.max(0, getResultScrollTop() - getVirtualOffset(index)),
|
| 599 |
anchorId: getResultStableId(view.results[index]), loadedPage: view.loadedPage,
|
| 600 |
savedAt: Date.now() };
|
| 601 |
+
return positionPersistence.save(position, () => saveSearchViewport(position, view));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
}
|
| 603 |
|
| 604 |
function setupSearchPositionSaving() {
|
| 605 |
DOM.resultsContainer.addEventListener("scroll", () => {
|
| 606 |
if (positionRestore || STATE.isLoading || displayedSearchView?.key !== getSearchViewKey()) return;
|
| 607 |
+
positionPersistence.scheduleSave(saveSearchPosition);
|
|
|
|
| 608 |
}, { passive: true });
|
| 609 |
// Query and route handlers save explicitly; capture only filters before mutation.
|
| 610 |
for (const type of ["change", "click"]) document.addEventListener(type, event => {
|
|
|
|
| 642 |
|
| 643 |
function tryRestoreSearchPosition(key, options = {}) {
|
| 644 |
const previous = positionRestore?.key === key && positionRestore.failed && !options.position ? positionRestore : null;
|
| 645 |
+
let position = options.position || previous?.position || positionPersistence.getPosition(key);
|
| 646 |
if (!validSearchPosition(position)) return false;
|
| 647 |
searchIntentId++;
|
| 648 |
cancelPendingSearchControls();
|
|
|
|
| 761 |
setResultScrollTop(getVirtualOffset(Math.min(anchor.index, STATE.results.length - 1)) + anchor.offset);
|
| 762 |
VSCROLL.renderStart = -1; VSCROLL.renderEnd = -1;
|
| 763 |
rememberDisplayedSearchView(); renderVisible(); updateStatusBar(); updateLoadInfo(); updatePagingStatus();
|
| 764 |
+
positionPersistence.scheduleSave(saveSearchPosition);
|
| 765 |
}
|
| 766 |
|
| 767 |
function validatePositionWindowPage(data, page, pageSize, expected) {
|
|
|
|
| 870 |
displayedSearchView = null;
|
| 871 |
rememberDisplayedSearchView();
|
| 872 |
renderVisible(); updateLoadInfo(); updatePagingStatus();
|
| 873 |
+
positionPersistence.scheduleSave(saveSearchPosition);
|
| 874 |
return true;
|
| 875 |
} catch (error) {
|
| 876 |
if (!resultWindowCurrent(window)) return false;
|
static/index.html
CHANGED
|
@@ -340,6 +340,9 @@ if ("serviceWorker" in navigator) {
|
|
| 340 |
<script src="/static/search/reader-navigation.js"></script>
|
| 341 |
<script src="/static/search/reader-host/presentation/return-position.js"></script>
|
| 342 |
<script src="/static/search/reader-host/application/host.js"></script>
|
|
|
|
|
|
|
|
|
|
| 343 |
<script src="/static/search/search-session.js"></script>
|
| 344 |
<script src="/static/search/download-controller.js"></script>
|
| 345 |
<script src="/static/search/size-format.js"></script>
|
|
|
|
| 340 |
<script src="/static/search/reader-navigation.js"></script>
|
| 341 |
<script src="/static/search/reader-host/presentation/return-position.js"></script>
|
| 342 |
<script src="/static/search/reader-host/application/host.js"></script>
|
| 343 |
+
<script src="/static/search/positions/domain/policy.js"></script>
|
| 344 |
+
<script src="/static/search/positions/infrastructure/indexed-db.js"></script>
|
| 345 |
+
<script src="/static/search/positions/application/persistence.js"></script>
|
| 346 |
<script src="/static/search/search-session.js"></script>
|
| 347 |
<script src="/static/search/download-controller.js"></script>
|
| 348 |
<script src="/static/search/size-format.js"></script>
|
static/reader-resources.js
CHANGED
|
@@ -128,6 +128,7 @@
|
|
| 128 |
"reader/core/reader-contract.js",
|
| 129 |
"search/reader-navigation.js",
|
| 130 |
"search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js",
|
|
|
|
| 131 |
"reader/core/reader-store.js",
|
| 132 |
"reader/core/reader-request-manager.js",
|
| 133 |
"reader/formats/reader-chapter-repository.js",
|
|
|
|
| 128 |
"reader/core/reader-contract.js",
|
| 129 |
"search/reader-navigation.js",
|
| 130 |
"search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js",
|
| 131 |
+
"search/positions/domain/policy.js", "search/positions/infrastructure/indexed-db.js", "search/positions/application/persistence.js",
|
| 132 |
"reader/core/reader-store.js",
|
| 133 |
"reader/core/reader-request-manager.js",
|
| 134 |
"reader/formats/reader-chapter-repository.js",
|
static/search/positions/application/persistence.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Owns retained positions/content and save scheduling. Geometry is a bounded input.
|
| 2 |
+
(function () {
|
| 3 |
+
/** @param {Parameters<typeof VoiceOfMLSearchPositions.create>[0]} deps
|
| 4 |
+
* @returns {SearchPositionPersistence} */
|
| 5 |
+
function create(deps) {
|
| 6 |
+
const policy = VoiceOfMLPositionPolicy, storage = deps.storage;
|
| 7 |
+
/** @type {Map<string, SearchPosition>} */
|
| 8 |
+
const positions = new Map();
|
| 9 |
+
/** @type {Map<string, SearchPositionViewport>} */
|
| 10 |
+
const viewports = new Map();
|
| 11 |
+
/** @type {Map<string, SearchRecentPage>} */
|
| 12 |
+
const recentPages = new Map();
|
| 13 |
+
/** @type {WeakMap<SearchRecentPage, {first: unknown; last: unknown}>} */
|
| 14 |
+
const pageSources = new WeakMap();
|
| 15 |
+
/** @type {WeakMap<SearchPositionViewport, Map<number, {record: unknown; height: number}>>} */
|
| 16 |
+
const viewportSources = new WeakMap();
|
| 17 |
+
let lastPruneAt = 0;
|
| 18 |
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
| 19 |
+
let saveTimer;
|
| 20 |
+
function cancelSave() { clearTimeout(saveTimer); saveTimer = undefined; }
|
| 21 |
+
/** @param {() => void} save */
|
| 22 |
+
function scheduleSave(save) { cancelSave(); saveTimer = setTimeout(save, 250); }
|
| 23 |
+
function init() {
|
| 24 |
+
return storage.init(values => {
|
| 25 |
+
for (const value of values) if (!positions.has(value.key)) positions.set(value.key, value);
|
| 26 |
+
});
|
| 27 |
+
}
|
| 28 |
+
/** @param {SearchRecentPage} entry */
|
| 29 |
+
function cachePage(entry) {
|
| 30 |
+
const id = JSON.stringify(entry.id);
|
| 31 |
+
recentPages.delete(id); recentPages.set(id, entry);
|
| 32 |
+
while (recentPages.size > policy.RECENT_PAGE_MAX) recentPages.delete(/** @type {string} */ (recentPages.keys().next().value));
|
| 33 |
+
}
|
| 34 |
+
/** @param {SearchPosition} position @param {SearchPositionView} view @param {number} visibleEnd */
|
| 35 |
+
function saveRecentPages(position, view, visibleEnd) {
|
| 36 |
+
const size = JSON.parse(view.key).pageSize;
|
| 37 |
+
const writes = [];
|
| 38 |
+
for (let page = Math.floor(position.index / size) + 1; page <= Math.floor(visibleEnd / size) + 1; page++) {
|
| 39 |
+
const start = (page - 1) * size, length = Math.min(size, view.total - start);
|
| 40 |
+
const metadata = view.window || deps.metadata(view.results[start]);
|
| 41 |
+
if (!metadata?.generation || metadata.total !== view.total || (view.window && !view.window.pages.has(page))) continue;
|
| 42 |
+
/** @type {[string, number]} */
|
| 43 |
+
const id = [view.key, page];
|
| 44 |
+
const previous = recentPages.get(JSON.stringify(id)), source = previous && pageSources.get(previous);
|
| 45 |
+
if (previous && source?.first === view.results[start] && source?.last === view.results[start + length - 1]
|
| 46 |
+
&& previous.generation === metadata.generation && Date.now() - previous.savedAt < 60000) {
|
| 47 |
+
cachePage(previous); continue;
|
| 48 |
+
}
|
| 49 |
+
const results = view.results.slice(start, start + length);
|
| 50 |
+
if (results.length !== length || Object.keys(results).length !== length || results.some(record => !record)) continue;
|
| 51 |
+
const entry = {id, key: view.key, page, page_size: size, total: view.total, generation: metadata.generation,
|
| 52 |
+
results: results.map(deps.cloneResult), savedAt: Date.now()};
|
| 53 |
+
if (new TextEncoder().encode(JSON.stringify(entry)).byteLength > policy.RECENT_PAGE_BYTES_MAX) continue;
|
| 54 |
+
cachePage(entry);
|
| 55 |
+
pageSources.set(entry, {first: results[0], last: results[length - 1]});
|
| 56 |
+
writes.push(entry);
|
| 57 |
+
}
|
| 58 |
+
storage.writeContent("recent-pages", writes, policy.RECENT_PAGE_MAX, policy.RECENT_PAGE_TTL);
|
| 59 |
+
}
|
| 60 |
+
/** @param {string} key @param {number} page
|
| 61 |
+
* @param {VoiceOfMLSearchWindowExpected & {query: {pageSize: number}}} expected
|
| 62 |
+
* @param {number} [timeoutMs] @param {AbortSignal | null} [signal] */
|
| 63 |
+
async function readRecentPage(key, page, expected, timeoutMs = 150, signal = null) {
|
| 64 |
+
const id = [key, page];
|
| 65 |
+
const entry = recentPages.get(JSON.stringify(id)) || await storage.read("recent-pages", id, timeoutMs, signal);
|
| 66 |
+
if (signal?.aborted || !policy.validRecentPage(entry, key, page, expected)) return null;
|
| 67 |
+
cachePage(entry);
|
| 68 |
+
return entry;
|
| 69 |
+
}
|
| 70 |
+
/** @param {string} key */
|
| 71 |
+
async function readViewport(key) {
|
| 72 |
+
return viewports.get(key) || /** @type {SearchPositionViewport | null} */ (await storage.read("viewports", key));
|
| 73 |
+
}
|
| 74 |
+
/** @param {SearchPosition} position @param {SearchPositionView} view @param {SearchPositionGeometry} geometry */
|
| 75 |
+
function saveViewport(position, view, geometry) {
|
| 76 |
+
const {visibleEnd, pageSize, measurementKey, estimatedHeight, heightAt} = geometry;
|
| 77 |
+
saveRecentPages(position, view, visibleEnd);
|
| 78 |
+
const previous = viewports.get(view.key), source = previous && viewportSources.get(previous);
|
| 79 |
+
const pageStart = Math.floor(position.index / pageSize) * pageSize;
|
| 80 |
+
const generation = view.window?.generation || deps.metadata(view.results[pageStart])?.generation;
|
| 81 |
+
if (previous && source && previous.total === view.total && previous.generation === generation
|
| 82 |
+
&& previous.measurementKey === measurementKey && Date.now() - previous.savedAt < 24 * 60 * 60 * 1000) {
|
| 83 |
+
let covered = true;
|
| 84 |
+
for (let index = position.index; index <= visibleEnd; index++) {
|
| 85 |
+
const saved = source.get(index);
|
| 86 |
+
if (!saved || saved.record !== view.results[index] || saved.height !== heightAt(index)) { covered = false; break; }
|
| 87 |
+
}
|
| 88 |
+
if (covered) return;
|
| 89 |
+
}
|
| 90 |
+
const start = Math.max(0, position.index - 24), end = Math.min(view.results.length, position.index + 56);
|
| 91 |
+
/** @type {[number, unknown, number][]} */
|
| 92 |
+
const records = [];
|
| 93 |
+
for (let index = start; index < end; index++) {
|
| 94 |
+
if (view.results[index]) records.push([index, deps.cloneResult(view.results[index]), heightAt(index)]);
|
| 95 |
+
}
|
| 96 |
+
/** @type {SearchPositionViewport} */
|
| 97 |
+
const viewport = {key: position.key, savedAt: position.savedAt, anchorId: position.anchorId, index: position.index,
|
| 98 |
+
total: view.total, generation, estimatedHeight, measurementKey, records: []};
|
| 99 |
+
// Spend the byte budget on visible records before nearest neighbors.
|
| 100 |
+
/** @param {number} index */
|
| 101 |
+
const distance = index => Math.max(position.index - index, index - visibleEnd, 0);
|
| 102 |
+
records.sort((a, b) => distance(a[0]) - distance(b[0]) || a[0] - b[0]);
|
| 103 |
+
const encoder = new TextEncoder();
|
| 104 |
+
let bytes = encoder.encode(JSON.stringify(viewport)).byteLength;
|
| 105 |
+
for (const record of records) {
|
| 106 |
+
const cost = encoder.encode(JSON.stringify(record)).byteLength + 1;
|
| 107 |
+
if (bytes + cost > policy.VIEWPORT_BYTES_MAX) continue;
|
| 108 |
+
viewport.records.push(record); bytes += cost;
|
| 109 |
+
}
|
| 110 |
+
viewport.records.sort((a, b) => a[0] - b[0]);
|
| 111 |
+
if (!viewport.records.some(([index]) => index === position.index)) return;
|
| 112 |
+
viewports.delete(viewport.key); viewports.set(viewport.key, viewport);
|
| 113 |
+
viewportSources.set(viewport, new Map(viewport.records.map(([index, , height]) => [index, {record: view.results[index], height}])));
|
| 114 |
+
while (viewports.size > policy.VIEWPORT_MAX) viewports.delete(/** @type {string} */ (viewports.keys().next().value));
|
| 115 |
+
storage.writeContent("viewports", [viewport], policy.VIEWPORT_MAX, policy.POSITION_TTL);
|
| 116 |
+
}
|
| 117 |
+
/** @param {SearchPosition} position @param {() => void} capture */
|
| 118 |
+
function save(position, capture) {
|
| 119 |
+
const previous = positions.get(position.key);
|
| 120 |
+
if (previous && position.savedAt - previous.savedAt < 1000 && previous.index === position.index
|
| 121 |
+
&& previous.offset === position.offset && previous.anchorId === position.anchorId
|
| 122 |
+
&& previous.loadedPage === position.loadedPage) return previous;
|
| 123 |
+
positions.set(position.key, position);
|
| 124 |
+
capture();
|
| 125 |
+
const prune = Date.now() - lastPruneAt >= 60000 || positions.size > policy.POSITION_MAX;
|
| 126 |
+
if (prune) {
|
| 127 |
+
const ordered = Array.from(positions.values()).sort((a, b) => b.savedAt - a.savedAt);
|
| 128 |
+
ordered.forEach((item, i) => { if (!policy.validPosition(item) || i >= policy.POSITION_MAX) positions.delete(item.key); });
|
| 129 |
+
lastPruneAt = Date.now();
|
| 130 |
+
}
|
| 131 |
+
storage.writePosition(position, prune);
|
| 132 |
+
return position;
|
| 133 |
+
}
|
| 134 |
+
return {positions, viewports, recentPages, init, getPosition: key => positions.get(key), save,
|
| 135 |
+
saveViewport, saveRecentPages, readViewport, readRecentPage, scheduleSave, cancelSave};
|
| 136 |
+
}
|
| 137 |
+
Object.assign(globalThis, {VoiceOfMLSearchPositions: {create}});
|
| 138 |
+
})();
|
static/search/positions/domain/policy.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Persistence budgets and validation of untrusted IndexedDB values.
|
| 2 |
+
(function () {
|
| 3 |
+
const POSITION_MAX = 500, POSITION_TTL = 90 * 24 * 60 * 60 * 1000;
|
| 4 |
+
const VIEWPORT_MAX = 64, VIEWPORT_BYTES_MAX = 64 * 1024;
|
| 5 |
+
const RECENT_PAGE_MAX = 32, RECENT_PAGE_BYTES_MAX = 256 * 1024;
|
| 6 |
+
const RECENT_PAGE_TTL = 7 * 24 * 60 * 60 * 1000;
|
| 7 |
+
|
| 8 |
+
/** @param {unknown} value @returns {value is SearchPosition} */
|
| 9 |
+
function validPosition(value) {
|
| 10 |
+
if (!value || typeof value !== "object") return false;
|
| 11 |
+
const item = /** @type {SearchPosition} */ (value);
|
| 12 |
+
return item.version === 1 && typeof item.key === "string"
|
| 13 |
+
&& Number.isInteger(item.index) && item.index >= 0
|
| 14 |
+
&& Number.isFinite(item.offset) && item.offset >= 0
|
| 15 |
+
&& Number.isInteger(item.loadedPage) && item.loadedPage >= 1
|
| 16 |
+
&& typeof item.anchorId === "string" && item.savedAt > Date.now() - POSITION_TTL;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
/** @param {unknown} value @param {SearchPosition | null | undefined} position
|
| 20 |
+
* @param {(record: unknown) => string} stableId @returns {value is SearchPositionViewport} */
|
| 21 |
+
function validViewport(value, position, stableId) {
|
| 22 |
+
if (!position || !value || typeof value !== "object") return false;
|
| 23 |
+
const viewport = /** @type {SearchPositionViewport} */ (value);
|
| 24 |
+
return viewport.key === position.key && viewport.savedAt >= Date.now() - POSITION_TTL
|
| 25 |
+
&& Number.isInteger(viewport.total) && viewport.total > position.index
|
| 26 |
+
&& Array.isArray(viewport.records) && viewport.records.length <= 80
|
| 27 |
+
&& viewport.records.every(row => Array.isArray(row) && row.length === 3
|
| 28 |
+
&& Number.isInteger(row[0]) && row[0] >= 0 && row[1] !== null && typeof row[1] === "object"
|
| 29 |
+
&& Number.isFinite(row[2]) && row[2] > 0)
|
| 30 |
+
&& viewport.records.some(([index, record]) => index === position.index && stableId(record) === position.anchorId);
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
/** @param {unknown} value @param {string} key @param {number} page
|
| 34 |
+
* @param {VoiceOfMLSearchWindowExpected & {query: {pageSize: number}}} expected
|
| 35 |
+
* @returns {value is SearchRecentPage} */
|
| 36 |
+
function validRecentPage(value, key, page, expected) {
|
| 37 |
+
if (!value || typeof value !== "object") return false;
|
| 38 |
+
const entry = /** @type {SearchRecentPage} */ (value);
|
| 39 |
+
if (entry.key !== key || !Number.isFinite(entry.savedAt) || entry.savedAt < Date.now() - RECENT_PAGE_TTL
|
| 40 |
+
|| !expected.generation || !Array.isArray(entry.results)
|
| 41 |
+
|| Object.keys(entry.results).length !== entry.results.length) return false;
|
| 42 |
+
try { VoiceOfMLSearchWindowPage.validate(entry, page, expected.query.pageSize, expected); }
|
| 43 |
+
catch (_) { return false; }
|
| 44 |
+
return true;
|
| 45 |
+
}
|
| 46 |
+
Object.assign(globalThis, {VoiceOfMLPositionPolicy: {POSITION_MAX, POSITION_TTL, VIEWPORT_MAX,
|
| 47 |
+
VIEWPORT_BYTES_MAX, RECENT_PAGE_MAX, RECENT_PAGE_BYTES_MAX, RECENT_PAGE_TTL,
|
| 48 |
+
validPosition, validViewport, validRecentPage}});
|
| 49 |
+
})();
|
static/search/positions/infrastructure/indexed-db.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Owns the connection and native transaction lifetime; callers keep memory fallback.
|
| 2 |
+
(function () {
|
| 3 |
+
/** @param {IDBObjectStore} store @param {number} limit @param {number} ttl */
|
| 4 |
+
function pruneContent(store, limit, ttl) {
|
| 5 |
+
const index = store.index("savedAt");
|
| 6 |
+
const expired = index.openKeyCursor(IDBKeyRange.upperBound(Date.now() - ttl, true));
|
| 7 |
+
expired.onsuccess = () => {
|
| 8 |
+
const cursor = expired.result;
|
| 9 |
+
if (cursor) { store.delete(cursor.primaryKey); cursor.continue(); }
|
| 10 |
+
};
|
| 11 |
+
let skipped = false;
|
| 12 |
+
const retained = index.openKeyCursor(null, "prev");
|
| 13 |
+
retained.onsuccess = () => {
|
| 14 |
+
const cursor = retained.result;
|
| 15 |
+
if (!cursor) return;
|
| 16 |
+
if (!skipped) { skipped = true; cursor.advance(limit); return; }
|
| 17 |
+
store.delete(cursor.primaryKey); cursor.continue();
|
| 18 |
+
};
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
/** @returns {SearchPositionStorage} */
|
| 22 |
+
function create() {
|
| 23 |
+
/** @type {IDBDatabase | null} */
|
| 24 |
+
let database = null;
|
| 25 |
+
let revision = 0;
|
| 26 |
+
function close() { revision++; database?.close(); database = null; }
|
| 27 |
+
/** @param {(values: SearchPosition[]) => void} accept */
|
| 28 |
+
function init(accept) {
|
| 29 |
+
close();
|
| 30 |
+
const owner = revision;
|
| 31 |
+
return /** @type {Promise<void>} */ (new Promise(resolve => {
|
| 32 |
+
let expired = false;
|
| 33 |
+
const finish = () => { expired = true; clearTimeout(timer); resolve(); };
|
| 34 |
+
const timer = setTimeout(finish, 1500);
|
| 35 |
+
try {
|
| 36 |
+
const request = indexedDB.open("voice-search-positions", 4);
|
| 37 |
+
request.onupgradeneeded = () => {
|
| 38 |
+
const db = request.result;
|
| 39 |
+
for (const name of Array.from(db.objectStoreNames)) db.deleteObjectStore(name);
|
| 40 |
+
for (const name of ["positions", "viewports", "recent-pages"]) {
|
| 41 |
+
const store = db.createObjectStore(name, {keyPath: name === "recent-pages" ? "id" : "key"});
|
| 42 |
+
store.createIndex("savedAt", "savedAt");
|
| 43 |
+
}
|
| 44 |
+
};
|
| 45 |
+
request.onerror = request.onblocked = finish;
|
| 46 |
+
request.onsuccess = () => {
|
| 47 |
+
const db = request.result;
|
| 48 |
+
if (expired || owner !== revision) { db.close(); return; }
|
| 49 |
+
database = db;
|
| 50 |
+
db.onversionchange = () => { db.close(); if (database === db) close(); };
|
| 51 |
+
try {
|
| 52 |
+
const transaction = db.transaction("positions", "readwrite");
|
| 53 |
+
const completion = VoiceOfMLSearchSession.watchTransaction(transaction);
|
| 54 |
+
const store = transaction.objectStore("positions");
|
| 55 |
+
/** @type {SearchPosition[]} */
|
| 56 |
+
const retained = [];
|
| 57 |
+
const read = store.getAll();
|
| 58 |
+
read.onsuccess = () => {
|
| 59 |
+
let count = 0;
|
| 60 |
+
const values = /** @type {SearchPosition[]} */ (read.result).sort((a, b) => b.savedAt - a.savedAt);
|
| 61 |
+
for (const value of values) {
|
| 62 |
+
if (!VoiceOfMLPositionPolicy.validPosition(value) || ++count > VoiceOfMLPositionPolicy.POSITION_MAX) store.delete(value.key);
|
| 63 |
+
else retained.push(value);
|
| 64 |
+
}
|
| 65 |
+
};
|
| 66 |
+
void completion.result.then(success => {
|
| 67 |
+
// The startup deadline releases its waiter, not this connection's
|
| 68 |
+
// hydration. A committed late read must still fill missing keys.
|
| 69 |
+
if (success && owner === revision && database === db) accept(retained);
|
| 70 |
+
finish();
|
| 71 |
+
});
|
| 72 |
+
} catch (_) { finish(); }
|
| 73 |
+
};
|
| 74 |
+
} catch (_) { finish(); }
|
| 75 |
+
}));
|
| 76 |
+
}
|
| 77 |
+
/** @param {string} name @param {IDBValidKey} key @param {number} [timeoutMs]
|
| 78 |
+
* @param {AbortSignal | null} [signal] @returns {Promise<unknown>} */
|
| 79 |
+
function read(name, key, timeoutMs = 150, signal = null) {
|
| 80 |
+
if (!database?.objectStoreNames.contains(name) || signal?.aborted) return Promise.resolve(null);
|
| 81 |
+
return new Promise(resolve => {
|
| 82 |
+
let settled = false;
|
| 83 |
+
/** @type {unknown} */
|
| 84 |
+
let value = null;
|
| 85 |
+
/** @param {unknown} result */
|
| 86 |
+
const finish = result => {
|
| 87 |
+
if (settled) return;
|
| 88 |
+
settled = true; clearTimeout(timer); signal?.removeEventListener("abort", abort); resolve(result);
|
| 89 |
+
};
|
| 90 |
+
const abort = () => finish(null);
|
| 91 |
+
const timer = setTimeout(abort, timeoutMs);
|
| 92 |
+
signal?.addEventListener("abort", abort, {once: true});
|
| 93 |
+
try {
|
| 94 |
+
const transaction = /** @type {IDBDatabase} */ (database).transaction(name);
|
| 95 |
+
const request = transaction.objectStore(name).get(key);
|
| 96 |
+
request.onsuccess = () => { value = request.result; };
|
| 97 |
+
request.onerror = transaction.onerror = transaction.onabort = abort;
|
| 98 |
+
transaction.oncomplete = () => finish(value);
|
| 99 |
+
} catch (_) { abort(); }
|
| 100 |
+
});
|
| 101 |
+
}
|
| 102 |
+
/** @param {string} name @param {object[]} values @param {number} limit @param {number} ttl */
|
| 103 |
+
function writeContent(name, values, limit, ttl) {
|
| 104 |
+
if (!values.length || !database?.objectStoreNames.contains(name)) return;
|
| 105 |
+
try {
|
| 106 |
+
const store = database.transaction(name, "readwrite").objectStore(name);
|
| 107 |
+
for (const value of values) store.put(value);
|
| 108 |
+
pruneContent(store, limit, ttl);
|
| 109 |
+
} catch (_) {}
|
| 110 |
+
}
|
| 111 |
+
/** @param {SearchPosition} position @param {boolean} prune */
|
| 112 |
+
function writePosition(position, prune) {
|
| 113 |
+
if (!database) return;
|
| 114 |
+
try {
|
| 115 |
+
const transaction = database.transaction("positions", "readwrite");
|
| 116 |
+
const store = transaction.objectStore("positions");
|
| 117 |
+
store.put(position);
|
| 118 |
+
let count = 0;
|
| 119 |
+
if (prune) {
|
| 120 |
+
const request = store.index("savedAt").openCursor(null, "prev");
|
| 121 |
+
request.onsuccess = () => {
|
| 122 |
+
const cursor = request.result;
|
| 123 |
+
if (!cursor) return;
|
| 124 |
+
if (!VoiceOfMLPositionPolicy.validPosition(cursor.value) || ++count > VoiceOfMLPositionPolicy.POSITION_MAX) cursor.delete();
|
| 125 |
+
cursor.continue();
|
| 126 |
+
};
|
| 127 |
+
}
|
| 128 |
+
transaction.onabort = () => {}; // Memory restoration remains available.
|
| 129 |
+
} catch (_) {}
|
| 130 |
+
}
|
| 131 |
+
return {get database() { return database; }, close, init, read, writeContent, writePosition};
|
| 132 |
+
}
|
| 133 |
+
Object.assign(globalThis, {VoiceOfMLPositionStorage: {create, pruneContent}});
|
| 134 |
+
})();
|
static/search/search-session.js
CHANGED
|
@@ -199,5 +199,5 @@
|
|
| 199 |
return { openSearchSessionDB, persistSearchSession, restoreSearchSession };
|
| 200 |
}
|
| 201 |
|
| 202 |
-
Object.assign(root, { VoiceOfMLSearchSession: /** @satisfies {SearchSessionApi} */ ({ createSearchSession }) });
|
| 203 |
})(typeof self !== "undefined" ? self : globalThis);
|
|
|
|
| 199 |
return { openSearchSessionDB, persistSearchSession, restoreSearchSession };
|
| 200 |
}
|
| 201 |
|
| 202 |
+
Object.assign(root, { VoiceOfMLSearchSession: /** @satisfies {SearchSessionApi} */ ({ createSearchSession, watchTransaction }) });
|
| 203 |
})(typeof self !== "undefined" ? self : globalThis);
|
static/sw.js
CHANGED
|
@@ -96,6 +96,9 @@ const PRECACHE_URLS = [
|
|
| 96 |
"/static/search/reader-navigation.js",
|
| 97 |
"/static/search/reader-host/presentation/return-position.js",
|
| 98 |
"/static/search/reader-host/application/host.js",
|
|
|
|
|
|
|
|
|
|
| 99 |
"/static/search/input/domain/ownership.js",
|
| 100 |
"/static/search/input/application/controller.js",
|
| 101 |
"/static/search/sidebar/presentation/filter-list.js",
|
|
|
|
| 96 |
"/static/search/reader-navigation.js",
|
| 97 |
"/static/search/reader-host/presentation/return-position.js",
|
| 98 |
"/static/search/reader-host/application/host.js",
|
| 99 |
+
"/static/search/positions/domain/policy.js",
|
| 100 |
+
"/static/search/positions/infrastructure/indexed-db.js",
|
| 101 |
+
"/static/search/positions/application/persistence.js",
|
| 102 |
"/static/search/input/domain/ownership.js",
|
| 103 |
"/static/search/input/application/controller.js",
|
| 104 |
"/static/search/sidebar/presentation/filter-list.js",
|
tests/backend/test_coverage_safety.py
CHANGED
|
@@ -271,6 +271,111 @@ class ReaderAssetBoundsTests(unittest.TestCase):
|
|
| 271 |
|
| 272 |
|
| 273 |
class StartupDataTests(unittest.TestCase):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
def test_uvicorn_entry_exports_the_real_asgi_application(self):
|
| 275 |
entry = importlib.import_module("app")
|
| 276 |
self.assertIs(entry.app, app.app)
|
|
|
|
| 271 |
|
| 272 |
|
| 273 |
class StartupDataTests(unittest.TestCase):
|
| 274 |
+
def test_decoder_hooks_remain_live_between_publication_phases(self):
|
| 275 |
+
with TemporaryDirectory() as temp:
|
| 276 |
+
root = Path(temp)
|
| 277 |
+
data, tree, browser = (root / name for name in ('data.gz', 'tree.gz', 'browser.gz'))
|
| 278 |
+
for path in (data, tree, browser):
|
| 279 |
+
path.write_bytes(gzip.compress(b'{}'))
|
| 280 |
+
published = [{'File': 'hook-record'}]
|
| 281 |
+
old_tree, old_browser = {'old': []}, {'old': {}}
|
| 282 |
+
def decode_records(_value):
|
| 283 |
+
app.decode_folder_tree_data = lambda _tree: (_ for _ in ()).throw(ValueError('tree hook'))
|
| 284 |
+
return published
|
| 285 |
+
with patch.multiple(app, DATA_PATH=data, FOLDER_TREE_PATH=tree, FOLDER_BROWSER_PATH=browser,
|
| 286 |
+
records=[], folder_tree_data=old_tree, folder_browser_data=old_browser), \
|
| 287 |
+
patch.object(app, 'decode_search_payload', side_effect=decode_records), \
|
| 288 |
+
patch.object(app, 'decode_folder_tree_data'), patch.object(app, 'build_indexes') as build:
|
| 289 |
+
with self.assertRaisesRegex(ValueError, 'tree hook'):
|
| 290 |
+
app.load_data()
|
| 291 |
+
self.assertIs(app.records, published)
|
| 292 |
+
self.assertIs(app.folder_tree_data, old_tree)
|
| 293 |
+
self.assertIs(app.folder_browser_data, old_browser)
|
| 294 |
+
build.assert_not_called()
|
| 295 |
+
|
| 296 |
+
def test_load_failure_keeps_each_completed_publication(self):
|
| 297 |
+
with TemporaryDirectory() as temp:
|
| 298 |
+
root = Path(temp)
|
| 299 |
+
data, tree, browser = (root / name for name in ('data.gz', 'tree.gz', 'browser.gz'))
|
| 300 |
+
data.write_bytes(gzip.compress(json.dumps({'rp': ['Fixture/A'], 'fd': [[]],
|
| 301 |
+
'rc': [[0, 'book', 'pdf', 0, 1, False]]}).encode()))
|
| 302 |
+
tree.write_bytes(gzip.compress(b'{'))
|
| 303 |
+
browser.write_bytes(gzip.compress(b'{'))
|
| 304 |
+
old_records, old_tree, old_browser = [], {'old': []}, {'old': {}}
|
| 305 |
+
with patch.multiple(app, DATA_PATH=data, FOLDER_TREE_PATH=tree, FOLDER_BROWSER_PATH=browser,
|
| 306 |
+
records=old_records, folder_tree_data=old_tree, folder_browser_data=old_browser), \
|
| 307 |
+
patch.object(app, 'build_indexes') as build:
|
| 308 |
+
with self.assertRaises(json.JSONDecodeError):
|
| 309 |
+
app.load_data()
|
| 310 |
+
self.assertEqual(app.records[0]['File'], 'book')
|
| 311 |
+
self.assertIsNot(app.records, old_records)
|
| 312 |
+
self.assertIs(app.folder_tree_data, old_tree)
|
| 313 |
+
self.assertIs(app.folder_browser_data, old_browser)
|
| 314 |
+
tree.write_bytes(gzip.compress(b'{}'))
|
| 315 |
+
with self.assertRaises(json.JSONDecodeError):
|
| 316 |
+
app.load_data()
|
| 317 |
+
self.assertEqual(app.folder_tree_data, {})
|
| 318 |
+
self.assertIsNot(app.folder_tree_data, old_tree)
|
| 319 |
+
self.assertIs(app.folder_browser_data, old_browser)
|
| 320 |
+
build.assert_not_called()
|
| 321 |
+
# A missing corpus resets records only; malformed gzip leaves even records intact.
|
| 322 |
+
published = app.records
|
| 323 |
+
data.write_bytes(b'bad gzip')
|
| 324 |
+
with self.assertRaises(gzip.BadGzipFile):
|
| 325 |
+
app.load_data()
|
| 326 |
+
self.assertIs(app.records, published)
|
| 327 |
+
data.unlink()
|
| 328 |
+
app.load_data()
|
| 329 |
+
self.assertEqual(app.records, [])
|
| 330 |
+
self.assertIs(app.folder_browser_data, old_browser)
|
| 331 |
+
build.assert_not_called()
|
| 332 |
+
|
| 333 |
+
def test_load_uses_live_paths_counts_and_bootstrap_publication_order(self):
|
| 334 |
+
saved = {name: getattr(app, name) for name in (
|
| 335 |
+
'records', 'folder_tree_data', 'folder_browser_data', 'word_index', 'word_index_buffer',
|
| 336 |
+
'ngram_postings', 'ngram_posting_buffers', '_search_generation')}
|
| 337 |
+
try:
|
| 338 |
+
with TemporaryDirectory() as temp:
|
| 339 |
+
root = Path(temp)
|
| 340 |
+
data = root / 'data.gz'
|
| 341 |
+
data.write_bytes(gzip.compress(b'{"rc":[]}'))
|
| 342 |
+
words, grams = root / 'new-words.gz', {2: root / 'two.gz', 3: root / 'three.gz'}
|
| 343 |
+
events = []
|
| 344 |
+
def metadata(**options):
|
| 345 |
+
self.assertEqual(options, {'build_words': False, 'build_reader': False})
|
| 346 |
+
app.records = [{}, {}]
|
| 347 |
+
app.WORD_INDEX_PATH = words
|
| 348 |
+
app.NGRAM_PATHS = grams
|
| 349 |
+
def read_words(path, count, digest, *, materialize):
|
| 350 |
+
self.assertEqual((path, count, digest, materialize), (words, 2, b'digest', False))
|
| 351 |
+
return {'fixture': {0}}, b'words'
|
| 352 |
+
def read_ngram(path, width, count, digest):
|
| 353 |
+
self.assertEqual((path, count, digest), (grams[width], 2, b'digest'))
|
| 354 |
+
self.assertEqual(app.word_index_buffer, b'words')
|
| 355 |
+
return {'fixture': {0}}, bytes([width])
|
| 356 |
+
def initial():
|
| 357 |
+
self.assertEqual(app._search_generation, 'api:fixture')
|
| 358 |
+
self.assertEqual(app.ngram_posting_buffers, {2: b'\x02', 3: b'\x03'})
|
| 359 |
+
events.append('initial')
|
| 360 |
+
with patch.multiple(app, DATA_PATH=data, FOLDER_TREE_PATH=root / 'missing-tree',
|
| 361 |
+
FOLDER_BROWSER_PATH=root / 'missing-browser',
|
| 362 |
+
WORD_INDEX_PATH=root / 'old-words', NGRAM_PATHS={}), \
|
| 363 |
+
patch.object(app, 'build_indexes', side_effect=metadata), \
|
| 364 |
+
patch.object(app, 'records_digest', return_value=b'digest'), \
|
| 365 |
+
patch.object(app, 'load_word_index', side_effect=read_words), \
|
| 366 |
+
patch.object(app, 'load_ngram_index', side_effect=read_ngram), \
|
| 367 |
+
patch.object(app, 'build_vocab_by_len', side_effect=lambda: events.append('vocab')), \
|
| 368 |
+
patch.object(app, 'search_data_generation', return_value='api:fixture') as generation, \
|
| 369 |
+
patch.object(app, 'build_initial_payloads', side_effect=initial), \
|
| 370 |
+
patch.object(app, 'precompute_injected_html', side_effect=lambda: events.append('html')), \
|
| 371 |
+
patch.object(app.jieba, 'initialize', side_effect=lambda: events.append('tokenizer')):
|
| 372 |
+
app.load_data()
|
| 373 |
+
self.assertEqual(events, ['vocab', 'initial', 'html', 'tokenizer'])
|
| 374 |
+
generation.assert_called_once_with(b'{"rc":[]}', [words, *grams.values()])
|
| 375 |
+
finally:
|
| 376 |
+
for name, value in saved.items():
|
| 377 |
+
setattr(app, name, value)
|
| 378 |
+
|
| 379 |
def test_uvicorn_entry_exports_the_real_asgi_application(self):
|
| 380 |
entry = importlib.import_module("app")
|
| 381 |
self.assertIs(entry.app, app.app)
|
tests/search/browser/test_position_controls.py
CHANGED
|
@@ -53,7 +53,7 @@ class PositionControlTests(unittest.TestCase):
|
|
| 53 |
def store_position(self, clear_viewport=False):
|
| 54 |
self.page.evaluate('''async clear=>{
|
| 55 |
returnPositionTarget=null;saveSearchPosition();
|
| 56 |
-
const tx=
|
| 57 |
if(clear)tx.objectStore('viewports').clear();
|
| 58 |
await new Promise(resolve=>tx.oncomplete=resolve);
|
| 59 |
}''', clear_viewport)
|
|
@@ -110,7 +110,7 @@ class PositionControlTests(unittest.TestCase):
|
|
| 110 |
self.page.evaluate('doSearch()')
|
| 111 |
self.wait_position(0)
|
| 112 |
self.page.evaluate('saveSearchPosition()')
|
| 113 |
-
self.assertEqual(self.page.evaluate('
|
| 114 |
self.page.locator('#return-to-position-btn').click()
|
| 115 |
self.wait_position(95000)
|
| 116 |
self.page.evaluate('doSearch()')
|
|
@@ -285,7 +285,7 @@ class PositionControlTests(unittest.TestCase):
|
|
| 285 |
setResultScrollTop(getVirtualOffset(50));
|
| 286 |
renderVisible();
|
| 287 |
saveSearchPosition();
|
| 288 |
-
setReturnPositionTarget(
|
| 289 |
updateSearchPositionControls();
|
| 290 |
const before = [DOM.backToTopBtn.hidden, DOM.returnToPositionBtn.hidden];
|
| 291 |
backToSearchTop();
|
|
|
|
| 53 |
def store_position(self, clear_viewport=False):
|
| 54 |
self.page.evaluate('''async clear=>{
|
| 55 |
returnPositionTarget=null;saveSearchPosition();
|
| 56 |
+
const tx=positionStorage.database.transaction(['positions','viewports'],'readwrite');
|
| 57 |
if(clear)tx.objectStore('viewports').clear();
|
| 58 |
await new Promise(resolve=>tx.oncomplete=resolve);
|
| 59 |
}''', clear_viewport)
|
|
|
|
| 110 |
self.page.evaluate('doSearch()')
|
| 111 |
self.wait_position(0)
|
| 112 |
self.page.evaluate('saveSearchPosition()')
|
| 113 |
+
self.assertEqual(self.page.evaluate('positionPersistence.positions.get(getSearchViewKey()).index'),95000)
|
| 114 |
self.page.locator('#return-to-position-btn').click()
|
| 115 |
self.wait_position(95000)
|
| 116 |
self.page.evaluate('doSearch()')
|
|
|
|
| 285 |
setResultScrollTop(getVirtualOffset(50));
|
| 286 |
renderVisible();
|
| 287 |
saveSearchPosition();
|
| 288 |
+
setReturnPositionTarget(positionPersistence.positions.get(getSearchViewKey()));
|
| 289 |
updateSearchPositionControls();
|
| 290 |
const before = [DOM.backToTopBtn.hidden, DOM.returnToPositionBtn.hidden];
|
| 291 |
backToSearchTop();
|
tests/search/browser/test_position_window.py
CHANGED
|
@@ -22,8 +22,8 @@ class PositionWindowTests(unittest.TestCase):
|
|
| 22 |
searchViewSnapshots.clear();
|
| 23 |
window.windowCalls=[];window.windowFailures=new Set();window.windowGeneration='one';
|
| 24 |
window.windowAnchor=49850;window.windowTotal=50001;window.windowStall=0;
|
| 25 |
-
window.originalWindowKey=[...
|
| 26 |
-
const saved=
|
| 27 |
Object.assign(saved,{index:49850,loadedPage:500,anchorId:'VoiceOfML/Test\\0paging-49850.txt',offset:11});
|
| 28 |
// Isolate recovery/demand requests from the normal next-page prefetch.
|
| 29 |
prefetchNextPage=()=>{};
|
|
@@ -93,7 +93,7 @@ class PositionWindowTests(unittest.TestCase):
|
|
| 93 |
self.assertEqual(self.page.evaluate('windowCalls.filter(page=>page===251).length'), 3)
|
| 94 |
self.page.wait_for_timeout(800)
|
| 95 |
self.assertEqual(self.page.evaluate('windowCalls.filter(page=>page===251).length'), 3)
|
| 96 |
-
self.assertEqual(self.page.evaluate('
|
| 97 |
self.page.evaluate('windowFailures.clear()')
|
| 98 |
self.page.locator('#search-window-status button').click()
|
| 99 |
self.wait_anchor(25050)
|
|
@@ -122,7 +122,7 @@ class PositionWindowTests(unittest.TestCase):
|
|
| 122 |
self.assertEqual(self.page.evaluate('gapTransportCalls'), 3)
|
| 123 |
self.assertTrue(self.page.evaluate('resultWindow.failures.get(251) instanceof Error'))
|
| 124 |
self.assertFalse(self.page.evaluate('!!STATE.results[25050]'))
|
| 125 |
-
self.assertEqual(self.page.evaluate('
|
| 126 |
self.page.evaluate('for(let i=0;i<20;i++)renderVisible()')
|
| 127 |
self.page.wait_for_timeout(800)
|
| 128 |
self.assertEqual(self.page.evaluate('gapTransportCalls'), 3)
|
|
@@ -273,8 +273,8 @@ class PositionWindowTests(unittest.TestCase):
|
|
| 273 |
|
| 274 |
def persist_viewport(self):
|
| 275 |
self.page.evaluate('''async () => {
|
| 276 |
-
|
| 277 |
-
await new Promise(resolve=>{const tx=
|
| 278 |
}''')
|
| 279 |
|
| 280 |
def assert_cached_viewport(self, offset=11):
|
|
@@ -295,7 +295,7 @@ class PositionWindowTests(unittest.TestCase):
|
|
| 295 |
self.persist_viewport()
|
| 296 |
self.page.evaluate("STATE.query='paging-other';doSearch()")
|
| 297 |
self.page.wait_for_function('!STATE.isLoading')
|
| 298 |
-
self.page.evaluate("searchViewSnapshots.clear();
|
| 299 |
self.assert_cached_viewport()
|
| 300 |
self.page.evaluate("window.cachedRow=DOM.resultsList.querySelector('[data-index=\"49850\"]');releaseWindow()")
|
| 301 |
self.wait_anchor(49850)
|
|
@@ -306,7 +306,7 @@ class PositionWindowTests(unittest.TestCase):
|
|
| 306 |
self.page.wait_for_timeout(100)
|
| 307 |
self.persist_viewport()
|
| 308 |
# Resizing can change fractional row geometry; restore the saved mobile offset.
|
| 309 |
-
saved_offset = self.page.evaluate('
|
| 310 |
fetcher = self.page.evaluate('fetchPositionPage.toString()')
|
| 311 |
self.page.add_init_script('''document.addEventListener('DOMContentLoaded',()=>{
|
| 312 |
window.windowCalls=[];window.windowFailures=new Set();window.windowGeneration='one';
|
|
@@ -357,10 +357,10 @@ class PositionWindowTests(unittest.TestCase):
|
|
| 357 |
|
| 358 |
def test_saved_viewport_is_bounded_and_not_used_for_another_anchor(self):
|
| 359 |
self.persist_viewport()
|
| 360 |
-
self.assertLessEqual(self.page.evaluate('
|
| 361 |
self.page.evaluate("STATE.query='paging-other';doSearch()")
|
| 362 |
self.page.wait_for_function('!STATE.isLoading')
|
| 363 |
-
self.page.evaluate("searchViewSnapshots.clear();
|
| 364 |
self.page.wait_for_function('!!window.releaseWindow')
|
| 365 |
self.assertFalse(self.page.evaluate('!!positionRestore.preview'))
|
| 366 |
self.page.evaluate('releaseWindow()')
|
|
@@ -376,12 +376,12 @@ class PositionWindowTests(unittest.TestCase):
|
|
| 376 |
}''')
|
| 377 |
self.persist_viewport()
|
| 378 |
self.assertTrue(self.page.evaluate('''() => {
|
| 379 |
-
const saved=
|
| 380 |
-
return saved.records.length<80 && new TextEncoder().encode(JSON.stringify(saved)).byteLength<=
|
| 381 |
}'''))
|
| 382 |
self.page.evaluate("STATE.query='paging-other';doSearch()")
|
| 383 |
self.page.wait_for_function('!STATE.isLoading')
|
| 384 |
-
self.page.evaluate("searchViewSnapshots.clear();
|
| 385 |
self.assert_cached_viewport()
|
| 386 |
self.page.evaluate('releaseWindow()')
|
| 387 |
self.wait_anchor(49850)
|
|
|
|
| 22 |
searchViewSnapshots.clear();
|
| 23 |
window.windowCalls=[];window.windowFailures=new Set();window.windowGeneration='one';
|
| 24 |
window.windowAnchor=49850;window.windowTotal=50001;window.windowStall=0;
|
| 25 |
+
window.originalWindowKey=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
|
| 26 |
+
const saved=positionPersistence.positions.get(originalWindowKey);
|
| 27 |
Object.assign(saved,{index:49850,loadedPage:500,anchorId:'VoiceOfML/Test\\0paging-49850.txt',offset:11});
|
| 28 |
// Isolate recovery/demand requests from the normal next-page prefetch.
|
| 29 |
prefetchNextPage=()=>{};
|
|
|
|
| 93 |
self.assertEqual(self.page.evaluate('windowCalls.filter(page=>page===251).length'), 3)
|
| 94 |
self.page.wait_for_timeout(800)
|
| 95 |
self.assertEqual(self.page.evaluate('windowCalls.filter(page=>page===251).length'), 3)
|
| 96 |
+
self.assertEqual(self.page.evaluate('positionPersistence.positions.get(originalWindowKey).index'), 49850)
|
| 97 |
self.page.evaluate('windowFailures.clear()')
|
| 98 |
self.page.locator('#search-window-status button').click()
|
| 99 |
self.wait_anchor(25050)
|
|
|
|
| 122 |
self.assertEqual(self.page.evaluate('gapTransportCalls'), 3)
|
| 123 |
self.assertTrue(self.page.evaluate('resultWindow.failures.get(251) instanceof Error'))
|
| 124 |
self.assertFalse(self.page.evaluate('!!STATE.results[25050]'))
|
| 125 |
+
self.assertEqual(self.page.evaluate('positionPersistence.positions.get(originalWindowKey).index'), 49850)
|
| 126 |
self.page.evaluate('for(let i=0;i<20;i++)renderVisible()')
|
| 127 |
self.page.wait_for_timeout(800)
|
| 128 |
self.assertEqual(self.page.evaluate('gapTransportCalls'), 3)
|
|
|
|
| 273 |
|
| 274 |
def persist_viewport(self):
|
| 275 |
self.page.evaluate('''async () => {
|
| 276 |
+
positionPersistence.positions.get(originalWindowKey).savedAt=0;saveSearchPosition();
|
| 277 |
+
await new Promise(resolve=>{const tx=positionStorage.database.transaction(['positions','viewports']);tx.oncomplete=resolve});
|
| 278 |
}''')
|
| 279 |
|
| 280 |
def assert_cached_viewport(self, offset=11):
|
|
|
|
| 295 |
self.persist_viewport()
|
| 296 |
self.page.evaluate("STATE.query='paging-other';doSearch()")
|
| 297 |
self.page.wait_for_function('!STATE.isLoading')
|
| 298 |
+
self.page.evaluate("searchViewSnapshots.clear();positionPersistence.viewports.clear();windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")
|
| 299 |
self.assert_cached_viewport()
|
| 300 |
self.page.evaluate("window.cachedRow=DOM.resultsList.querySelector('[data-index=\"49850\"]');releaseWindow()")
|
| 301 |
self.wait_anchor(49850)
|
|
|
|
| 306 |
self.page.wait_for_timeout(100)
|
| 307 |
self.persist_viewport()
|
| 308 |
# Resizing can change fractional row geometry; restore the saved mobile offset.
|
| 309 |
+
saved_offset = self.page.evaluate('positionPersistence.positions.get(originalWindowKey).offset')
|
| 310 |
fetcher = self.page.evaluate('fetchPositionPage.toString()')
|
| 311 |
self.page.add_init_script('''document.addEventListener('DOMContentLoaded',()=>{
|
| 312 |
window.windowCalls=[];window.windowFailures=new Set();window.windowGeneration='one';
|
|
|
|
| 357 |
|
| 358 |
def test_saved_viewport_is_bounded_and_not_used_for_another_anchor(self):
|
| 359 |
self.persist_viewport()
|
| 360 |
+
self.assertLessEqual(self.page.evaluate('positionPersistence.viewports.get(originalWindowKey).records.length'), 80)
|
| 361 |
self.page.evaluate("STATE.query='paging-other';doSearch()")
|
| 362 |
self.page.wait_for_function('!STATE.isLoading')
|
| 363 |
+
self.page.evaluate("searchViewSnapshots.clear();positionPersistence.positions.get(originalWindowKey).anchorId='different';windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")
|
| 364 |
self.page.wait_for_function('!!window.releaseWindow')
|
| 365 |
self.assertFalse(self.page.evaluate('!!positionRestore.preview'))
|
| 366 |
self.page.evaluate('releaseWindow()')
|
|
|
|
| 376 |
}''')
|
| 377 |
self.persist_viewport()
|
| 378 |
self.assertTrue(self.page.evaluate('''() => {
|
| 379 |
+
const saved=positionPersistence.viewports.get(originalWindowKey);
|
| 380 |
+
return saved.records.length<80 && new TextEncoder().encode(JSON.stringify(saved)).byteLength<=VoiceOfMLPositionPolicy.VIEWPORT_BYTES_MAX;
|
| 381 |
}'''))
|
| 382 |
self.page.evaluate("STATE.query='paging-other';doSearch()")
|
| 383 |
self.page.wait_for_function('!STATE.isLoading')
|
| 384 |
+
self.page.evaluate("searchViewSnapshots.clear();positionPersistence.viewports.clear();windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")
|
| 385 |
self.assert_cached_viewport()
|
| 386 |
self.page.evaluate('releaseWindow()')
|
| 387 |
self.wait_anchor(49850)
|
tests/search/browser/test_prefetch_pipeline.py
CHANGED
|
@@ -148,7 +148,7 @@ class PrefetchPipelineTests(unittest.TestCase):
|
|
| 148 |
def test_matching_saved_pages_avoid_network_and_old_generation_is_rejected(self):
|
| 149 |
result = self.page.evaluate('''async () => {
|
| 150 |
cancelSearchPrefetch();
|
| 151 |
-
STATE._pageCache={};searchResponseCache.clear();
|
| 152 |
const key=getSearchViewKey();const template={q:STATE.query,page:1,page_size:100};
|
| 153 |
const metadata={generation:'stable',page:1,page_size:100,total:STATE.total,results:STATE.results};
|
| 154 |
rememberSearchPageMetadata(metadata);
|
|
@@ -156,7 +156,7 @@ class PrefetchPipelineTests(unittest.TestCase):
|
|
| 156 |
for(let page=2;page<=4;page++) {
|
| 157 |
const entry={key,id:[key,page],page,page_size:100,total:STATE.total,generation:'stable',savedAt:Date.now(),
|
| 158 |
results:Array.from({length:Math.min(100,STATE.total-(page-1)*100)},(_,i)=>({ID:String((page-1)*100+i),File:'cached'}))};
|
| 159 |
-
cached.push(entry);
|
| 160 |
}
|
| 161 |
window.networkPages=[];
|
| 162 |
const native=fetchSearchPage;
|
|
@@ -167,7 +167,7 @@ class PrefetchPipelineTests(unittest.TestCase):
|
|
| 167 |
const reused=Object.keys(STATE._pageCache).map(Number);
|
| 168 |
const calls=networkPages.slice();
|
| 169 |
cancelSearchPrefetch();STATE._pageCache={};searchResponseCache.clear();
|
| 170 |
-
cached.forEach(entry=>
|
| 171 |
prefetchSearchPages('/api/search',template);
|
| 172 |
while(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));
|
| 173 |
return {reused,calls,revalidated:networkPages};
|
|
|
|
| 148 |
def test_matching_saved_pages_avoid_network_and_old_generation_is_rejected(self):
|
| 149 |
result = self.page.evaluate('''async () => {
|
| 150 |
cancelSearchPrefetch();
|
| 151 |
+
STATE._pageCache={};searchResponseCache.clear();positionPersistence.recentPages.clear();
|
| 152 |
const key=getSearchViewKey();const template={q:STATE.query,page:1,page_size:100};
|
| 153 |
const metadata={generation:'stable',page:1,page_size:100,total:STATE.total,results:STATE.results};
|
| 154 |
rememberSearchPageMetadata(metadata);
|
|
|
|
| 156 |
for(let page=2;page<=4;page++) {
|
| 157 |
const entry={key,id:[key,page],page,page_size:100,total:STATE.total,generation:'stable',savedAt:Date.now(),
|
| 158 |
results:Array.from({length:Math.min(100,STATE.total-(page-1)*100)},(_,i)=>({ID:String((page-1)*100+i),File:'cached'}))};
|
| 159 |
+
cached.push(entry);positionPersistence.recentPages.set(JSON.stringify(entry.id), entry);
|
| 160 |
}
|
| 161 |
window.networkPages=[];
|
| 162 |
const native=fetchSearchPage;
|
|
|
|
| 167 |
const reused=Object.keys(STATE._pageCache).map(Number);
|
| 168 |
const calls=networkPages.slice();
|
| 169 |
cancelSearchPrefetch();STATE._pageCache={};searchResponseCache.clear();
|
| 170 |
+
cached.forEach(entry=>positionPersistence.recentPages.set(JSON.stringify(entry.id), {...entry,generation:'old'}));
|
| 171 |
prefetchSearchPages('/api/search',template);
|
| 172 |
while(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));
|
| 173 |
return {reused,calls,revalidated:networkPages};
|
tests/search/browser/test_recent_search_pages.py
CHANGED
|
@@ -34,7 +34,7 @@ class RecentSearchPageTests(unittest.TestCase):
|
|
| 34 |
|
| 35 |
def flush(self):
|
| 36 |
self.page.evaluate('''() => new Promise(resolve=>{
|
| 37 |
-
const tx=
|
| 38 |
})''')
|
| 39 |
|
| 40 |
def visit(self, index):
|
|
@@ -51,7 +51,7 @@ class RecentSearchPageTests(unittest.TestCase):
|
|
| 51 |
def begin_restore(self):
|
| 52 |
self.page.evaluate("STATE.query='paging-other';doSearch()")
|
| 53 |
self.page.wait_for_function('!STATE.isLoading')
|
| 54 |
-
self.page.evaluate("searchViewSnapshots.clear();
|
| 55 |
self.page.wait_for_function('positionRestore?.preview && !!window.releaseWindow')
|
| 56 |
|
| 57 |
def wait_cached(self, index):
|
|
@@ -69,8 +69,8 @@ class RecentSearchPageTests(unittest.TestCase):
|
|
| 69 |
TextEncoder.prototype.encode=function(...args){counts.encodes++;return encode.apply(this,args)};
|
| 70 |
try {
|
| 71 |
for(let offset=1;offset<=20;offset++) {setResultScrollTop(getVirtualOffset(49850)+offset);saveSearchPosition()}
|
| 72 |
-
await new Promise(resolve=>{const tx=
|
| 73 |
-
return {...counts,offset:
|
| 74 |
} finally {IDBObjectStore.prototype.put=put;TextEncoder.prototype.encode=encode}
|
| 75 |
}''')
|
| 76 |
self.assertAlmostEqual(result.pop('offset'), 20, delta=1)
|
|
@@ -78,9 +78,9 @@ class RecentSearchPageTests(unittest.TestCase):
|
|
| 78 |
|
| 79 |
def test_new_index_reuses_covering_viewport_and_restores_latest_offset(self):
|
| 80 |
self.fixture.persist_viewport()
|
| 81 |
-
self.page.evaluate('window.keptViewport=
|
| 82 |
self.visit(49855)
|
| 83 |
-
self.assertTrue(self.page.evaluate('keptViewport===
|
| 84 |
self.begin_restore()
|
| 85 |
self.wait_cached(49855)
|
| 86 |
self.page.evaluate('releaseWindow()')
|
|
@@ -141,8 +141,8 @@ class RecentSearchPageTests(unittest.TestCase):
|
|
| 141 |
result = self.page.evaluate('''async () => {
|
| 142 |
const data=cloneSearchData({results:STATE.results.slice(49800,49900),page:499,page_size:100,total:STATE.total,generation:'regular'});
|
| 143 |
const results=STATE.results.map(cloneSearchResult),view={...displayedSearchView,results,window:null};
|
| 144 |
-
|
| 145 |
-
|
| 146 |
const entry=await readRecentSearchPage(originalWindowKey,499,{...resultWindow,generation:'regular'});
|
| 147 |
return entry && {generation:entry.generation,id:entry.results[50].ID};
|
| 148 |
}''')
|
|
@@ -169,11 +169,11 @@ class RecentSearchPageTests(unittest.TestCase):
|
|
| 169 |
self.prepare_pages()
|
| 170 |
checks = self.page.evaluate('''async () => {
|
| 171 |
const key=getSearchViewKey(),expected=resultWindow;
|
| 172 |
-
|
| 173 |
const entry=await readRecentSearchPage(key,251,expected);
|
| 174 |
const good=entry?.results[50].ID==='25050';
|
| 175 |
const other=await readRecentSearchPage(key+'other',251,expected);
|
| 176 |
-
entry.savedAt=Date.now()-
|
| 177 |
const expired=await readRecentSearchPage(key,251,expected);
|
| 178 |
entry.savedAt=Date.now();entry.results.pop();
|
| 179 |
const partial=await readRecentSearchPage(key,251,expected);
|
|
@@ -184,14 +184,14 @@ class RecentSearchPageTests(unittest.TestCase):
|
|
| 184 |
def test_page_cache_is_bounded_and_oversized_pages_keep_all_live_results(self):
|
| 185 |
self.fixture.persist_viewport()
|
| 186 |
result = self.page.evaluate('''async () => {
|
| 187 |
-
const position=
|
| 188 |
-
for(let i=0;i<35;i++)
|
| 189 |
-
await new Promise(resolve=>{const tx=
|
| 190 |
-
const count=await new Promise(resolve=>{const request=
|
| 191 |
const oversizedKey=JSON.stringify({...JSON.parse(view.key),query:'oversized'});
|
| 192 |
for(let i=49800;i<49900;i++)STATE.results[i]={...STATE.results[i],Metadata:'x'.repeat(4000)};
|
| 193 |
-
|
| 194 |
-
return {count,memory:
|
| 195 |
}''')
|
| 196 |
self.assertEqual(result, {'count':32, 'memory':32, 'oversized':False, 'live':100})
|
| 197 |
|
|
@@ -200,23 +200,23 @@ class RecentSearchPageTests(unittest.TestCase):
|
|
| 200 |
const now=Date.now(),clock=Date.now;Date.now=()=>now;
|
| 201 |
const name='recent-pages';
|
| 202 |
try {
|
| 203 |
-
const tx=
|
| 204 |
store.clear();
|
| 205 |
for(let i=0;i<40;i++)store.put({id:['prune',i],savedAt:now});
|
| 206 |
-
store.put({id:['expired',0],savedAt:now-
|
| 207 |
-
|
| 208 |
await new Promise((resolve,reject)=>{tx.oncomplete=resolve;tx.onabort=reject});
|
| 209 |
const entries=await new Promise(resolve=>{
|
| 210 |
-
const request=
|
| 211 |
request.onsuccess=()=>resolve(request.result);
|
| 212 |
});
|
| 213 |
-
const tx2=
|
| 214 |
-
s.clear();s.put({id:['boundary',0],savedAt:now-
|
| 215 |
-
s.put({id:['expired',0],savedAt:now-
|
| 216 |
-
|
| 217 |
await new Promise((resolve,reject)=>{tx2.oncomplete=resolve;tx2.onabort=reject});
|
| 218 |
const boundary=await new Promise(resolve=>{
|
| 219 |
-
const r=
|
| 220 |
});
|
| 221 |
return {ids:entries.map(entry=>entry.id[1]),boundary};
|
| 222 |
} finally {Date.now=clock;}
|
|
@@ -232,9 +232,9 @@ class RecentSearchPageTests(unittest.TestCase):
|
|
| 232 |
};
|
| 233 |
try {
|
| 234 |
const view=displayedSearchView,key=JSON.stringify({...JSON.parse(view.key),query:'batch-write'});
|
| 235 |
-
|
| 236 |
-
await new Promise(resolve=>{const tx=
|
| 237 |
-
return {writes,pages:[499,500].map(page=>
|
| 238 |
} finally {IDBDatabase.prototype.transaction=transaction;}
|
| 239 |
}''')
|
| 240 |
self.assertEqual(result, {'writes':1,'pages':[100,100]})
|
|
|
|
| 34 |
|
| 35 |
def flush(self):
|
| 36 |
self.page.evaluate('''() => new Promise(resolve=>{
|
| 37 |
+
const tx=positionStorage.database.transaction(['positions','viewports','recent-pages']);tx.oncomplete=resolve;
|
| 38 |
})''')
|
| 39 |
|
| 40 |
def visit(self, index):
|
|
|
|
| 51 |
def begin_restore(self):
|
| 52 |
self.page.evaluate("STATE.query='paging-other';doSearch()")
|
| 53 |
self.page.wait_for_function('!STATE.isLoading')
|
| 54 |
+
self.page.evaluate("searchViewSnapshots.clear();positionPersistence.viewports.clear();positionPersistence.recentPages.clear();windowCalls=[];windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")
|
| 55 |
self.page.wait_for_function('positionRestore?.preview && !!window.releaseWindow')
|
| 56 |
|
| 57 |
def wait_cached(self, index):
|
|
|
|
| 69 |
TextEncoder.prototype.encode=function(...args){counts.encodes++;return encode.apply(this,args)};
|
| 70 |
try {
|
| 71 |
for(let offset=1;offset<=20;offset++) {setResultScrollTop(getVirtualOffset(49850)+offset);saveSearchPosition()}
|
| 72 |
+
await new Promise(resolve=>{const tx=positionStorage.database.transaction(['positions','viewports','recent-pages']);tx.oncomplete=resolve});
|
| 73 |
+
return {...counts,offset:positionPersistence.positions.get(originalWindowKey).offset};
|
| 74 |
} finally {IDBObjectStore.prototype.put=put;TextEncoder.prototype.encode=encode}
|
| 75 |
}''')
|
| 76 |
self.assertAlmostEqual(result.pop('offset'), 20, delta=1)
|
|
|
|
| 78 |
|
| 79 |
def test_new_index_reuses_covering_viewport_and_restores_latest_offset(self):
|
| 80 |
self.fixture.persist_viewport()
|
| 81 |
+
self.page.evaluate('window.keptViewport=positionPersistence.viewports.get(originalWindowKey)')
|
| 82 |
self.visit(49855)
|
| 83 |
+
self.assertTrue(self.page.evaluate('keptViewport===positionPersistence.viewports.get(originalWindowKey)'))
|
| 84 |
self.begin_restore()
|
| 85 |
self.wait_cached(49855)
|
| 86 |
self.page.evaluate('releaseWindow()')
|
|
|
|
| 141 |
result = self.page.evaluate('''async () => {
|
| 142 |
const data=cloneSearchData({results:STATE.results.slice(49800,49900),page:499,page_size:100,total:STATE.total,generation:'regular'});
|
| 143 |
const results=STATE.results.map(cloneSearchResult),view={...displayedSearchView,results,window:null};
|
| 144 |
+
positionPersistence.saveRecentPages(positionPersistence.positions.get(originalWindowKey),view,49850);
|
| 145 |
+
positionPersistence.recentPages.clear();
|
| 146 |
const entry=await readRecentSearchPage(originalWindowKey,499,{...resultWindow,generation:'regular'});
|
| 147 |
return entry && {generation:entry.generation,id:entry.results[50].ID};
|
| 148 |
}''')
|
|
|
|
| 169 |
self.prepare_pages()
|
| 170 |
checks = self.page.evaluate('''async () => {
|
| 171 |
const key=getSearchViewKey(),expected=resultWindow;
|
| 172 |
+
positionPersistence.recentPages.clear();
|
| 173 |
const entry=await readRecentSearchPage(key,251,expected);
|
| 174 |
const good=entry?.results[50].ID==='25050';
|
| 175 |
const other=await readRecentSearchPage(key+'other',251,expected);
|
| 176 |
+
entry.savedAt=Date.now()-VoiceOfMLPositionPolicy.RECENT_PAGE_TTL-1;
|
| 177 |
const expired=await readRecentSearchPage(key,251,expected);
|
| 178 |
entry.savedAt=Date.now();entry.results.pop();
|
| 179 |
const partial=await readRecentSearchPage(key,251,expected);
|
|
|
|
| 184 |
def test_page_cache_is_bounded_and_oversized_pages_keep_all_live_results(self):
|
| 185 |
self.fixture.persist_viewport()
|
| 186 |
result = self.page.evaluate('''async () => {
|
| 187 |
+
const position=positionPersistence.positions.get(originalWindowKey), view=displayedSearchView;
|
| 188 |
+
for(let i=0;i<35;i++)positionPersistence.saveRecentPages(position,{...view,key:JSON.stringify({...JSON.parse(view.key),query:'bounded-'+i})},position.index);
|
| 189 |
+
await new Promise(resolve=>{const tx=positionStorage.database.transaction('recent-pages');tx.oncomplete=resolve});
|
| 190 |
+
const count=await new Promise(resolve=>{const request=positionStorage.database.transaction('recent-pages').objectStore('recent-pages').count();request.onsuccess=()=>resolve(request.result)});
|
| 191 |
const oversizedKey=JSON.stringify({...JSON.parse(view.key),query:'oversized'});
|
| 192 |
for(let i=49800;i<49900;i++)STATE.results[i]={...STATE.results[i],Metadata:'x'.repeat(4000)};
|
| 193 |
+
positionPersistence.saveRecentPages(position,{...view,key:oversizedKey},position.index);
|
| 194 |
+
return {count,memory:positionPersistence.recentPages.size,oversized:positionPersistence.recentPages.has(JSON.stringify([oversizedKey,499])),live:STATE.results.slice(49800,49900).length};
|
| 195 |
}''')
|
| 196 |
self.assertEqual(result, {'count':32, 'memory':32, 'oversized':False, 'live':100})
|
| 197 |
|
|
|
|
| 200 |
const now=Date.now(),clock=Date.now;Date.now=()=>now;
|
| 201 |
const name='recent-pages';
|
| 202 |
try {
|
| 203 |
+
const tx=positionStorage.database.transaction(name,'readwrite'),store=tx.objectStore(name);
|
| 204 |
store.clear();
|
| 205 |
for(let i=0;i<40;i++)store.put({id:['prune',i],savedAt:now});
|
| 206 |
+
store.put({id:['expired',0],savedAt:now-VoiceOfMLPositionPolicy.RECENT_PAGE_TTL-1});
|
| 207 |
+
VoiceOfMLPositionStorage.pruneContent(store,32,VoiceOfMLPositionPolicy.RECENT_PAGE_TTL);
|
| 208 |
await new Promise((resolve,reject)=>{tx.oncomplete=resolve;tx.onabort=reject});
|
| 209 |
const entries=await new Promise(resolve=>{
|
| 210 |
+
const request=positionStorage.database.transaction(name).objectStore(name).getAll();
|
| 211 |
request.onsuccess=()=>resolve(request.result);
|
| 212 |
});
|
| 213 |
+
const tx2=positionStorage.database.transaction(name,'readwrite'),s=tx2.objectStore(name);
|
| 214 |
+
s.clear();s.put({id:['boundary',0],savedAt:now-VoiceOfMLPositionPolicy.RECENT_PAGE_TTL});
|
| 215 |
+
s.put({id:['expired',0],savedAt:now-VoiceOfMLPositionPolicy.RECENT_PAGE_TTL-1});
|
| 216 |
+
VoiceOfMLPositionStorage.pruneContent(s,32,VoiceOfMLPositionPolicy.RECENT_PAGE_TTL);
|
| 217 |
await new Promise((resolve,reject)=>{tx2.oncomplete=resolve;tx2.onabort=reject});
|
| 218 |
const boundary=await new Promise(resolve=>{
|
| 219 |
+
const r=positionStorage.database.transaction(name).objectStore(name).getAll();r.onsuccess=()=>resolve(r.result.map(e=>e.id[0]));
|
| 220 |
});
|
| 221 |
return {ids:entries.map(entry=>entry.id[1]),boundary};
|
| 222 |
} finally {Date.now=clock;}
|
|
|
|
| 232 |
};
|
| 233 |
try {
|
| 234 |
const view=displayedSearchView,key=JSON.stringify({...JSON.parse(view.key),query:'batch-write'});
|
| 235 |
+
positionPersistence.saveRecentPages({index:49895},{...view,key},49905);
|
| 236 |
+
await new Promise(resolve=>{const tx=positionStorage.database.transaction('recent-pages');tx.oncomplete=resolve});
|
| 237 |
+
return {writes,pages:[499,500].map(page=>positionPersistence.recentPages.get(JSON.stringify([key,page]))?.results.length)};
|
| 238 |
} finally {IDBDatabase.prototype.transaction=transaction;}
|
| 239 |
}''')
|
| 240 |
self.assertEqual(result, {'writes':1,'pages':[100,100]})
|
tests/search/browser/test_search_positions.py
CHANGED
|
@@ -22,10 +22,10 @@ class SearchPositionTests(unittest.TestCase):
|
|
| 22 |
self.page.evaluate('maybeLoadNextPage(false,true)')
|
| 23 |
self.page.wait_for_function('STATE._loadedPage>=2 && !STATE.isLoading')
|
| 24 |
self.page.evaluate('DOM.resultsContainer.scrollTop=getVirtualOffset(125)+17')
|
| 25 |
-
self.page.wait_for_function('
|
| 26 |
-
self.saved = self.page.evaluate('
|
| 27 |
self.page.evaluate('''() => new Promise(resolve => {
|
| 28 |
-
const tx=
|
| 29 |
tx.objectStore('positions').get(getSearchViewKey()); tx.oncomplete=resolve;
|
| 30 |
})''')
|
| 31 |
|
|
@@ -59,11 +59,11 @@ class SearchPositionTests(unittest.TestCase):
|
|
| 59 |
});
|
| 60 |
}''', self.saved)
|
| 61 |
self.page.goto(self.fixture.origin + '/?q=paging-original')
|
| 62 |
-
self.page.wait_for_function('
|
| 63 |
self.assertEqual(self.page.evaluate('findVirtualIndex(getResultScrollTop())'), 0)
|
| 64 |
self.page.evaluate('setResultScrollTop(getVirtualOffset(25)+10);saveSearchPosition()')
|
| 65 |
-
self.page.wait_for_function('
|
| 66 |
-
self.saved = self.page.evaluate('
|
| 67 |
self.page.reload(wait_until='domcontentloaded')
|
| 68 |
self.assert_position()
|
| 69 |
|
|
@@ -108,7 +108,7 @@ class SearchPositionTests(unittest.TestCase):
|
|
| 108 |
self.page.evaluate("STATE.query='paging-latest'; doSearch(); releaseRestore()")
|
| 109 |
self.page.wait_for_function("STATE.query==='paging-latest' && !STATE.isLoading && !positionRestore")
|
| 110 |
self.assertEqual(self.page.evaluate('displayedSearchView.key'), self.page.evaluate('getSearchViewKey()'))
|
| 111 |
-
self.assertEqual(self.page.evaluate('
|
| 112 |
self.assertEqual(self.fixture.errors, [])
|
| 113 |
|
| 114 |
def test_rebuild_failure_keeps_position_and_retry_succeeds(self):
|
|
@@ -127,15 +127,15 @@ class SearchPositionTests(unittest.TestCase):
|
|
| 127 |
|
| 128 |
def test_expiry_and_count_prune_positions_independently(self):
|
| 129 |
result = self.page.evaluate('''async () => {
|
| 130 |
-
const original=
|
| 131 |
await new Promise(resolve=>{
|
| 132 |
-
const tx=
|
| 133 |
for(let i=0;i<505;i++) store.put({...original,key:'test-'+i,savedAt:Date.now()-i*1000});
|
| 134 |
-
store.put({...original,key:'expired',savedAt:Date.now()-
|
| 135 |
tx.oncomplete=resolve;
|
| 136 |
});
|
| 137 |
-
|
| 138 |
-
return {count:
|
| 139 |
}''')
|
| 140 |
self.assertEqual(result, {'count': 500, 'expired': False, 'oldest': False})
|
| 141 |
|
|
@@ -252,10 +252,9 @@ class SearchPositionTests(unittest.TestCase):
|
|
| 252 |
const first=saveSearchViewSnapshot(), results=first.results;
|
| 253 |
let scans=0; const cursor=IDBIndex.prototype.openCursor;
|
| 254 |
IDBIndex.prototype.openCursor=function(...args){scans++; return cursor.apply(this,args)};
|
| 255 |
-
lastPositionPruneAt=Date.now();
|
| 256 |
try {
|
| 257 |
for(let i=0;i<20;i++) saveSearchViewSnapshot();
|
| 258 |
-
const tx=
|
| 259 |
await new Promise(resolve=>{tx.oncomplete=resolve});
|
| 260 |
return {same:searchViewSnapshots.get(getSearchViewKey()).results===results,scans};
|
| 261 |
} finally {IDBIndex.prototype.openCursor=cursor;}
|
|
@@ -321,8 +320,8 @@ class SearchPositionTests(unittest.TestCase):
|
|
| 321 |
self.begin_rebuild('''() => {
|
| 322 |
prefetchNextPage=()=>{}; // Measure the restore-critical set, independently of lookahead.
|
| 323 |
pagingTotal=800;searchResponseCache.clear();
|
| 324 |
-
const originalKey=[...
|
| 325 |
-
|
| 326 |
const original=fetchPositionPage;window.restoreCalls=[];window.restorePeak=0;let active=0;
|
| 327 |
fetchPositionPage=async (...args)=>{
|
| 328 |
restoreCalls.push(args[1]);active++;restorePeak=Math.max(restorePeak,active);
|
|
@@ -342,8 +341,8 @@ class SearchPositionTests(unittest.TestCase):
|
|
| 342 |
self.begin_rebuild('''() => {
|
| 343 |
prefetchNextPage=()=>{};
|
| 344 |
pagingTotal=400;searchResponseCache.clear();
|
| 345 |
-
const key=[...
|
| 346 |
-
|
| 347 |
const original=fetchPositionPage;window.restoreCalls=[];window.failPage=true;
|
| 348 |
fetchPositionPage=async (...args)=>{
|
| 349 |
restoreCalls.push(args[1]);
|
|
@@ -363,8 +362,8 @@ class SearchPositionTests(unittest.TestCase):
|
|
| 363 |
def test_parallel_generation_mismatch_discards_entire_buffer(self):
|
| 364 |
self.begin_rebuild('''() => {
|
| 365 |
pagingTotal=400;searchResponseCache.clear();
|
| 366 |
-
const key=[...
|
| 367 |
-
|
| 368 |
const original=fetchPositionPage;window.coherent=false;
|
| 369 |
fetchPositionPage=async (...args)=>({...await original(...args),generation:coherent||args[1]===3?'new':'old'});
|
| 370 |
}''')
|
|
|
|
| 22 |
self.page.evaluate('maybeLoadNextPage(false,true)')
|
| 23 |
self.page.wait_for_function('STATE._loadedPage>=2 && !STATE.isLoading')
|
| 24 |
self.page.evaluate('DOM.resultsContainer.scrollTop=getVirtualOffset(125)+17')
|
| 25 |
+
self.page.wait_for_function('positionPersistence.positions.get(getSearchViewKey())?.index===125')
|
| 26 |
+
self.saved = self.page.evaluate('positionPersistence.positions.get(getSearchViewKey())')
|
| 27 |
self.page.evaluate('''() => new Promise(resolve => {
|
| 28 |
+
const tx=positionStorage.database.transaction('positions');
|
| 29 |
tx.objectStore('positions').get(getSearchViewKey()); tx.oncomplete=resolve;
|
| 30 |
})''')
|
| 31 |
|
|
|
|
| 59 |
});
|
| 60 |
}''', self.saved)
|
| 61 |
self.page.goto(self.fixture.origin + '/?q=paging-original')
|
| 62 |
+
self.page.wait_for_function('positionStorage.database?.version === 4 && !STATE.isLoading')
|
| 63 |
self.assertEqual(self.page.evaluate('findVirtualIndex(getResultScrollTop())'), 0)
|
| 64 |
self.page.evaluate('setResultScrollTop(getVirtualOffset(25)+10);saveSearchPosition()')
|
| 65 |
+
self.page.wait_for_function('positionPersistence.positions.get(getSearchViewKey())?.index === 25')
|
| 66 |
+
self.saved = self.page.evaluate('positionPersistence.positions.get(getSearchViewKey())')
|
| 67 |
self.page.reload(wait_until='domcontentloaded')
|
| 68 |
self.assert_position()
|
| 69 |
|
|
|
|
| 108 |
self.page.evaluate("STATE.query='paging-latest'; doSearch(); releaseRestore()")
|
| 109 |
self.page.wait_for_function("STATE.query==='paging-latest' && !STATE.isLoading && !positionRestore")
|
| 110 |
self.assertEqual(self.page.evaluate('displayedSearchView.key'), self.page.evaluate('getSearchViewKey()'))
|
| 111 |
+
self.assertEqual(self.page.evaluate('positionPersistence.positions.get(' + repr(self.saved['key']) + ').anchorId'), self.saved['anchorId'])
|
| 112 |
self.assertEqual(self.fixture.errors, [])
|
| 113 |
|
| 114 |
def test_rebuild_failure_keeps_position_and_retry_succeeds(self):
|
|
|
|
| 127 |
|
| 128 |
def test_expiry_and_count_prune_positions_independently(self):
|
| 129 |
result = self.page.evaluate('''async () => {
|
| 130 |
+
const original=positionPersistence.positions.get(getSearchViewKey());
|
| 131 |
await new Promise(resolve=>{
|
| 132 |
+
const tx=positionStorage.database.transaction('positions','readwrite'),store=tx.objectStore('positions');
|
| 133 |
for(let i=0;i<505;i++) store.put({...original,key:'test-'+i,savedAt:Date.now()-i*1000});
|
| 134 |
+
store.put({...original,key:'expired',savedAt:Date.now()-VoiceOfMLPositionPolicy.POSITION_TTL-1});
|
| 135 |
tx.oncomplete=resolve;
|
| 136 |
});
|
| 137 |
+
positionPersistence.positions.clear(); positionStorage.database.close(); await initSearchPositions();
|
| 138 |
+
return {count:positionPersistence.positions.size,expired:positionPersistence.positions.has('expired'),oldest:positionPersistence.positions.has('test-504')};
|
| 139 |
}''')
|
| 140 |
self.assertEqual(result, {'count': 500, 'expired': False, 'oldest': False})
|
| 141 |
|
|
|
|
| 252 |
const first=saveSearchViewSnapshot(), results=first.results;
|
| 253 |
let scans=0; const cursor=IDBIndex.prototype.openCursor;
|
| 254 |
IDBIndex.prototype.openCursor=function(...args){scans++; return cursor.apply(this,args)};
|
|
|
|
| 255 |
try {
|
| 256 |
for(let i=0;i<20;i++) saveSearchViewSnapshot();
|
| 257 |
+
const tx=positionStorage.database.transaction('positions');
|
| 258 |
await new Promise(resolve=>{tx.oncomplete=resolve});
|
| 259 |
return {same:searchViewSnapshots.get(getSearchViewKey()).results===results,scans};
|
| 260 |
} finally {IDBIndex.prototype.openCursor=cursor;}
|
|
|
|
| 320 |
self.begin_rebuild('''() => {
|
| 321 |
prefetchNextPage=()=>{}; // Measure the restore-critical set, independently of lookahead.
|
| 322 |
pagingTotal=800;searchResponseCache.clear();
|
| 323 |
+
const originalKey=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
|
| 324 |
+
positionPersistence.positions.get(originalKey).loadedPage=8;
|
| 325 |
const original=fetchPositionPage;window.restoreCalls=[];window.restorePeak=0;let active=0;
|
| 326 |
fetchPositionPage=async (...args)=>{
|
| 327 |
restoreCalls.push(args[1]);active++;restorePeak=Math.max(restorePeak,active);
|
|
|
|
| 341 |
self.begin_rebuild('''() => {
|
| 342 |
prefetchNextPage=()=>{};
|
| 343 |
pagingTotal=400;searchResponseCache.clear();
|
| 344 |
+
const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
|
| 345 |
+
positionPersistence.positions.get(key).loadedPage=4;
|
| 346 |
const original=fetchPositionPage;window.restoreCalls=[];window.failPage=true;
|
| 347 |
fetchPositionPage=async (...args)=>{
|
| 348 |
restoreCalls.push(args[1]);
|
|
|
|
| 362 |
def test_parallel_generation_mismatch_discards_entire_buffer(self):
|
| 363 |
self.begin_rebuild('''() => {
|
| 364 |
pagingTotal=400;searchResponseCache.clear();
|
| 365 |
+
const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
|
| 366 |
+
positionPersistence.positions.get(key).loadedPage=4;
|
| 367 |
const original=fetchPositionPage;window.coherent=false;
|
| 368 |
fetchPositionPage=async (...args)=>({...await original(...args),generation:coherent||args[1]===3?'new':'old'});
|
| 369 |
}''')
|
tests/search/browser/test_search_session_browser.py
CHANGED
|
@@ -118,19 +118,19 @@ class SearchSessionBrowserTests(unittest.TestCase):
|
|
| 118 |
self.page.route(self.origin + '/', lambda route: route.fulfill(
|
| 119 |
content_type='text/html', body=(support.ROOT / 'static/index.html').read_text()))
|
| 120 |
self.page.goto(self.origin + '/', wait_until='domcontentloaded')
|
| 121 |
-
self.page.wait_for_function('!!
|
| 122 |
result = self.page.evaluate('''async () => {
|
| 123 |
-
|
| 124 |
const request=indexedDB.open('voice-search-positions',4);
|
| 125 |
const blocker=await new Promise((resolve,reject)=>{request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error)});
|
| 126 |
const deletion=indexedDB.deleteDatabase('voice-search-positions');
|
| 127 |
let deleted=false; deletion.onsuccess=()=>{deleted=true};
|
| 128 |
await initSearchPositions();
|
| 129 |
-
const openedBefore=!!
|
| 130 |
blocker.close();
|
| 131 |
for(let i=0;i<50&&!deleted;i++) await new Promise(resolve=>setTimeout(resolve,20));
|
| 132 |
await new Promise(resolve=>setTimeout(resolve,100));
|
| 133 |
-
return {openedBefore,deleted,openedAfter:!!
|
| 134 |
}''')
|
| 135 |
self.assertEqual(result, {'openedBefore':False, 'deleted':True, 'openedAfter':False})
|
| 136 |
|
|
|
|
| 118 |
self.page.route(self.origin + '/', lambda route: route.fulfill(
|
| 119 |
content_type='text/html', body=(support.ROOT / 'static/index.html').read_text()))
|
| 120 |
self.page.goto(self.origin + '/', wait_until='domcontentloaded')
|
| 121 |
+
self.page.wait_for_function('!!positionStorage.database', timeout=8000)
|
| 122 |
result = self.page.evaluate('''async () => {
|
| 123 |
+
positionStorage.close();
|
| 124 |
const request=indexedDB.open('voice-search-positions',4);
|
| 125 |
const blocker=await new Promise((resolve,reject)=>{request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error)});
|
| 126 |
const deletion=indexedDB.deleteDatabase('voice-search-positions');
|
| 127 |
let deleted=false; deletion.onsuccess=()=>{deleted=true};
|
| 128 |
await initSearchPositions();
|
| 129 |
+
const openedBefore=!!positionStorage.database;
|
| 130 |
blocker.close();
|
| 131 |
for(let i=0;i<50&&!deleted;i++) await new Promise(resolve=>setTimeout(resolve,20));
|
| 132 |
await new Promise(resolve=>setTimeout(resolve,100));
|
| 133 |
+
return {openedBefore,deleted,openedAfter:!!positionStorage.database};
|
| 134 |
}''')
|
| 135 |
self.assertEqual(result, {'openedBefore':False, 'deleted':True, 'openedAfter':False})
|
| 136 |
|
tests/search/build/test_search_record_path_build.mjs
CHANGED
|
@@ -52,7 +52,8 @@ assert.equal(APP_DEPENDENCIES.filter(name => name === viewKeyName).length, 1);
|
|
| 52 |
assert.equal(APP_DEPENDENCIES.filter(name => name === recoveryName).length, 1);
|
| 53 |
assert.equal(APP_DEPENDENCIES.filter(name => name === windowPageName).length, 1, "window page must be composed once");
|
| 54 |
assert.equal(APP_DEPENDENCIES.filter(name => name === sidebarName).length, 1);
|
| 55 |
-
assert.equal(APP_DEPENDENCIES.at(-1),
|
|
|
|
| 56 |
assert.equal((html.match(/<script src="[^"\n]*search\/folder-selection\.js"><\/script>/g) || []).length, 1);
|
| 57 |
assert.ok(html.indexOf(identityName) < html.indexOf(folderSelectionName) && html.indexOf(folderSelectionName) < html.lastIndexOf("app.js"));
|
| 58 |
assert.doesNotMatch(bundled, /<script src="[^"\n]*search\/folder-selection\.js"/);
|
|
|
|
| 52 |
assert.equal(APP_DEPENDENCIES.filter(name => name === recoveryName).length, 1);
|
| 53 |
assert.equal(APP_DEPENDENCIES.filter(name => name === windowPageName).length, 1, "window page must be composed once");
|
| 54 |
assert.equal(APP_DEPENDENCIES.filter(name => name === sidebarName).length, 1);
|
| 55 |
+
assert.equal(APP_DEPENDENCIES.at(-1), "search/sidebar/application/filters.js");
|
| 56 |
+
assert.ok(APP_DEPENDENCIES.indexOf(sidebarName) < APP_DEPENDENCIES.indexOf("search/sidebar/application/filters.js"));
|
| 57 |
assert.equal((html.match(/<script src="[^"\n]*search\/folder-selection\.js"><\/script>/g) || []).length, 1);
|
| 58 |
assert.ok(html.indexOf(identityName) < html.indexOf(folderSelectionName) && html.indexOf(folderSelectionName) < html.lastIndexOf("app.js"));
|
| 59 |
assert.doesNotMatch(bundled, /<script src="[^"\n]*search\/folder-selection\.js"/);
|
tests/search/reader-navigation/test_search_history_races.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import vm from 'node:vm';
|
|
| 6 |
import test from 'node:test';
|
| 7 |
import './host_contracts.mjs';
|
| 8 |
import '../paging/result_window_contracts.mjs';
|
|
|
|
| 9 |
import { installClassicSearchModules } from '../../support/classic_search_modules.js';
|
| 10 |
import { APP_DEPENDENCIES, stripBundledScripts } from '../../../scripts/build/compose_app.mjs';
|
| 11 |
|
|
|
|
| 6 |
import test from 'node:test';
|
| 7 |
import './host_contracts.mjs';
|
| 8 |
import '../paging/result_window_contracts.mjs';
|
| 9 |
+
import '../session/test_positions_persistence.mjs';
|
| 10 |
import { installClassicSearchModules } from '../../support/classic_search_modules.js';
|
| 11 |
import { APP_DEPENDENCIES, stripBundledScripts } from '../../../scripts/build/compose_app.mjs';
|
| 12 |
|
tests/search/session/test_positions_persistence.mjs
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from 'node:assert/strict';
|
| 2 |
+
import {readFileSync} from 'node:fs';
|
| 3 |
+
import vm from 'node:vm';
|
| 4 |
+
import {test} from 'node:test';
|
| 5 |
+
import {indexedDB, IDBKeyRange} from 'fake-indexeddb';
|
| 6 |
+
import {APP_DEPENDENCIES, stripBundledScripts} from '../../../scripts/build/compose_app.mjs';
|
| 7 |
+
import {createRequire} from 'node:module';
|
| 8 |
+
|
| 9 |
+
test('positions modules are composed once and synchronized across shell, resources and worker', () => {
|
| 10 |
+
const read = name => readFileSync(new URL('../../../' + name, import.meta.url), 'utf8');
|
| 11 |
+
const html = read('static/index.html'), worker = read('static/sw.js');
|
| 12 |
+
const resources = createRequire(import.meta.url)('../../../static/reader-resources.js');
|
| 13 |
+
for (const name of ['search/positions/domain/policy.js', 'search/positions/infrastructure/indexed-db.js',
|
| 14 |
+
'search/positions/application/persistence.js']) {
|
| 15 |
+
assert.equal(APP_DEPENDENCIES.filter(path => path === name).length, 1);
|
| 16 |
+
assert.equal(html.split(name).length - 1, 1);
|
| 17 |
+
assert.ok(html.indexOf(name) < html.lastIndexOf('app.js'));
|
| 18 |
+
assert.equal(stripBundledScripts(html).includes(name), false);
|
| 19 |
+
assert.equal(worker.split(name).length - 1, 1);
|
| 20 |
+
for (const site of ['github', 'hf']) assert.equal(resources.buildFiles(site).filter(path => path === name).length, 1);
|
| 21 |
+
}
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
function fixture(overrides = {}) {
|
| 25 |
+
const context = vm.createContext({indexedDB, IDBKeyRange, setTimeout, clearTimeout,
|
| 26 |
+
TextEncoder, AbortController, ...overrides});
|
| 27 |
+
for (const file of ['search-session.js', 'domain/search-window-page.js',
|
| 28 |
+
'positions/domain/policy.js', 'positions/infrastructure/indexed-db.js', 'positions/application/persistence.js']) {
|
| 29 |
+
vm.runInContext(readFileSync(new URL('../../../static/search/' + file, import.meta.url), 'utf8'), context);
|
| 30 |
+
}
|
| 31 |
+
const storage = context.VoiceOfMLPositionStorage.create();
|
| 32 |
+
const controller = context.VoiceOfMLSearchPositions.create({storage, cloneResult: structuredClone, metadata: () => undefined});
|
| 33 |
+
return {context, storage, controller};
|
| 34 |
+
}
|
| 35 |
+
function fakeDatabase() {
|
| 36 |
+
let transaction;
|
| 37 |
+
const db = {close() {}, objectStoreNames: {contains: () => true}, transaction() {
|
| 38 |
+
const request = {};
|
| 39 |
+
transaction = {objectStore: () => ({get: () => request, getAll: () => request}), request, abort() {}};
|
| 40 |
+
return transaction;
|
| 41 |
+
}};
|
| 42 |
+
const opening = {};
|
| 43 |
+
const f = fixture({indexedDB: {open: () => opening}});
|
| 44 |
+
const initializing = f.storage.init(() => {});
|
| 45 |
+
opening.result = db; opening.onsuccess();
|
| 46 |
+
transaction.request.result = []; transaction.request.onsuccess(); transaction.oncomplete();
|
| 47 |
+
return {...f, initializing, transaction: () => transaction};
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
test('read success remains provisional until transaction completes; abort and timeout discard it', async () => {
|
| 51 |
+
const f = fakeDatabase(); await f.initializing;
|
| 52 |
+
let settled = false;
|
| 53 |
+
const read = f.storage.read('viewports', 'key').then(value => {settled = true; return value;});
|
| 54 |
+
let tx = f.transaction(); tx.request.result = {key: 'key'}; tx.request.onsuccess();
|
| 55 |
+
await Promise.resolve(); assert.equal(settled, false);
|
| 56 |
+
tx.onabort(); assert.equal(await read, null);
|
| 57 |
+
const completed = f.storage.read('viewports', 'key');
|
| 58 |
+
tx = f.transaction(); tx.request.result = {key: 'key'}; tx.request.onsuccess(); tx.oncomplete();
|
| 59 |
+
assert.deepEqual(await completed, {key: 'key'});
|
| 60 |
+
const timedOut = f.storage.read('viewports', 'key', 1);
|
| 61 |
+
tx = f.transaction(); assert.equal(await timedOut, null);
|
| 62 |
+
tx.request.result = {key: 'late'}; tx.request.onsuccess(); tx.oncomplete();
|
| 63 |
+
assert.equal(await timedOut, null);
|
| 64 |
+
const controller = new AbortController();
|
| 65 |
+
const aborted = f.storage.read('recent-pages', ['key', 1], 100, controller.signal);
|
| 66 |
+
tx = f.transaction(); controller.abort(); assert.equal(await aborted, null);
|
| 67 |
+
tx.request.result = {key: 'late'}; tx.request.onsuccess(); tx.oncomplete();
|
| 68 |
+
assert.equal(await aborted, null);
|
| 69 |
+
f.storage.close();
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
test('initialization publishes only committed data and retains a newer in-memory save', async () => {
|
| 73 |
+
const f = fixture(); await f.controller.init();
|
| 74 |
+
const key = JSON.stringify({pageSize: 100});
|
| 75 |
+
const old = {version: 1, key, index: 1, offset: 3, anchorId: 'old', loadedPage: 1, savedAt: Date.now()};
|
| 76 |
+
const tx = f.storage.database.transaction('positions', 'readwrite');
|
| 77 |
+
tx.objectStore('positions').put(old);
|
| 78 |
+
await new Promise(resolve => {tx.oncomplete = resolve;});
|
| 79 |
+
const loading = f.controller.init();
|
| 80 |
+
const fresh = {...old, index: 2, anchorId: 'fresh', savedAt: Date.now() + 1};
|
| 81 |
+
f.controller.save(fresh, () => {});
|
| 82 |
+
await loading;
|
| 83 |
+
assert.equal(f.controller.getPosition(key), fresh);
|
| 84 |
+
f.storage.close();
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
test('startup deadline releases at 1500ms while current connection hydrates on commit at 1600ms', async () => {
|
| 88 |
+
let clock = 0, timerId = 0;
|
| 89 |
+
const timers = new Map(), opening = {}, read = {};
|
| 90 |
+
const transaction = {objectStore: () => ({getAll: () => read}), abort() {}};
|
| 91 |
+
const db = {close() {}, transaction: () => transaction};
|
| 92 |
+
const f = fixture({indexedDB: {open: () => opening},
|
| 93 |
+
setTimeout(fn, delay) {timers.set(++timerId, {fn, at: clock + delay}); return timerId;},
|
| 94 |
+
clearTimeout(id) {timers.delete(id);}});
|
| 95 |
+
let released = false;
|
| 96 |
+
const loading = f.controller.init().then(() => {released = true;});
|
| 97 |
+
clock = 1000; opening.result = db; opening.onsuccess();
|
| 98 |
+
const saved = key => ({version: 1, key, index: 1, offset: 0, anchorId: 'disk', loadedPage: 1, savedAt: Date.now()});
|
| 99 |
+
clock = 1100; read.result = [saved('late'), saved('newer')]; read.onsuccess();
|
| 100 |
+
assert.equal(f.controller.getPosition('late'), undefined);
|
| 101 |
+
clock = 1500;
|
| 102 |
+
for (const [id, timer] of timers) if (timer.at <= clock) {timers.delete(id); timer.fn();}
|
| 103 |
+
await loading; assert.equal(released, true);
|
| 104 |
+
// Memory changes while the startup caller proceeds must win over hydration.
|
| 105 |
+
const fresh = {...saved('newer'), index: 2, anchorId: 'memory'};
|
| 106 |
+
f.controller.save(fresh, () => {});
|
| 107 |
+
clock = 1600; transaction.oncomplete(); await Promise.resolve();
|
| 108 |
+
assert.equal(f.controller.getPosition('late').anchorId, 'disk');
|
| 109 |
+
assert.equal(f.controller.getPosition('newer'), fresh);
|
| 110 |
+
f.storage.close();
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
test('malformed viewport rows and recent-page holes fail validation without throwing', () => {
|
| 114 |
+
const {context} = fixture();
|
| 115 |
+
const policy = context.VoiceOfMLPositionPolicy;
|
| 116 |
+
const position = {key: 'key', index: 0, anchorId: 'anchor'};
|
| 117 |
+
for (const records of [null, [null], [{}], [[0, null, 50]], [[0, {id: 'anchor'}, -1]]]) {
|
| 118 |
+
assert.equal(policy.validViewport({key: 'key', total: 1, savedAt: Date.now(), records}, position, record => record.id), false);
|
| 119 |
+
}
|
| 120 |
+
const expected = {generation: 'A', total: 1, query: {pageSize: 100}};
|
| 121 |
+
const page = {key: 'key', page: 1, page_size: 100, generation: 'A', total: 1, savedAt: Date.now(), results: [{File: 'a'}]};
|
| 122 |
+
assert.equal(policy.validRecentPage(page, 'key', 1, expected), true);
|
| 123 |
+
assert.equal(policy.validRecentPage({...page, results: new Array(1)}, 'key', 1, expected), false);
|
| 124 |
+
assert.equal(policy.validRecentPage({...page, generation: 'B'}, 'key', 1, expected), false);
|
| 125 |
+
assert.equal(policy.validRecentPage({...page, savedAt: undefined}, 'key', 1, expected), false);
|
| 126 |
+
});
|
| 127 |
+
|
| 128 |
+
test('scheduled saves coalesce and cancellation leaves no delayed flush', () => {
|
| 129 |
+
const timers = new Map(); let id = 0, calls = 0;
|
| 130 |
+
const f = fixture({setTimeout: fn => {timers.set(++id, fn); return id;}, clearTimeout: id => timers.delete(id)});
|
| 131 |
+
f.controller.scheduleSave(() => calls++); f.controller.scheduleSave(() => calls++);
|
| 132 |
+
assert.equal(timers.size, 1);
|
| 133 |
+
f.controller.cancelSave(); assert.equal(timers.size, 0);
|
| 134 |
+
f.controller.scheduleSave(() => calls++);
|
| 135 |
+
for (const callback of timers.values()) callback();
|
| 136 |
+
assert.equal(calls, 1);
|
| 137 |
+
});
|
tests/support/classic_search_modules.js
CHANGED
|
@@ -5,7 +5,9 @@ const fs = require("fs");
|
|
| 5 |
const path = require("path");
|
| 6 |
const vm = require("vm");
|
| 7 |
|
| 8 |
-
const MODULES = ["static/search/
|
|
|
|
|
|
|
| 9 |
"static/search/reader-host/presentation/return-position.js", "static/search/reader-host/application/host.js",
|
| 10 |
"static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js",
|
| 11 |
"static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"];
|
|
|
|
| 5 |
const path = require("path");
|
| 6 |
const vm = require("vm");
|
| 7 |
|
| 8 |
+
const MODULES = ["static/search/search-session.js", "static/search/domain/search-window-page.js",
|
| 9 |
+
"static/search/positions/domain/policy.js", "static/search/positions/infrastructure/indexed-db.js", "static/search/positions/application/persistence.js",
|
| 10 |
+
"static/search/folder-selection.js", "static/search/domain/height-index.js",
|
| 11 |
"static/search/reader-host/presentation/return-position.js", "static/search/reader-host/application/host.js",
|
| 12 |
"static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js",
|
| 13 |
"static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"];
|
typings/reader-globals.d.ts
CHANGED
|
@@ -450,6 +450,7 @@ declare var VoiceOfMLReaderChapters: ReaderChaptersApi;
|
|
| 450 |
declare var VoiceOfMLReaderVirtual: ReaderVirtualApi;
|
| 451 |
|
| 452 |
interface SearchSessionApi {
|
|
|
|
| 453 |
createSearchSession(options: {canPersist(): boolean; canRestore(target?: URL): boolean}): {
|
| 454 |
openSearchSessionDB(): Promise<IDBDatabase>;
|
| 455 |
persistSearchSession(): Promise<void>;
|
|
|
|
| 450 |
declare var VoiceOfMLReaderVirtual: ReaderVirtualApi;
|
| 451 |
|
| 452 |
interface SearchSessionApi {
|
| 453 |
+
watchTransaction(transaction: IDBTransaction): {result: Promise<boolean>; finished: Promise<void>; fail(): void};
|
| 454 |
createSearchSession(options: {canPersist(): boolean; canRestore(target?: URL): boolean}): {
|
| 455 |
openSearchSessionDB(): Promise<IDBDatabase>;
|
| 456 |
persistSearchSession(): Promise<void>;
|
typings/search-positions.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
interface SearchPosition {
|
| 2 |
+
version: number; key: string; index: number; offset: number; anchorId: string; loadedPage: number; savedAt: number;
|
| 3 |
+
}
|
| 4 |
+
interface SearchPositionViewport {
|
| 5 |
+
key: string; savedAt: number; anchorId: string; index: number; total: number;
|
| 6 |
+
generation: string | undefined; estimatedHeight: number; measurementKey: string;
|
| 7 |
+
records: [number, unknown, number][];
|
| 8 |
+
}
|
| 9 |
+
interface SearchRecentPage extends VoiceOfMLSearchWindowPageData {
|
| 10 |
+
id: [string, number]; key: string; savedAt: number;
|
| 11 |
+
}
|
| 12 |
+
interface SearchPositionView {
|
| 13 |
+
key: string; total: number; results: unknown[];
|
| 14 |
+
window?: {generation?: string | undefined; total: number; pages: Set<number>} | null | undefined;
|
| 15 |
+
}
|
| 16 |
+
interface SearchPositionGeometry {
|
| 17 |
+
visibleEnd: number; pageSize: number; measurementKey: string; estimatedHeight: number;
|
| 18 |
+
heightAt(index: number): number;
|
| 19 |
+
}
|
| 20 |
+
interface SearchPositionStorage {
|
| 21 |
+
readonly database: IDBDatabase | null;
|
| 22 |
+
close(): void;
|
| 23 |
+
init(accept: (values: SearchPosition[]) => void): Promise<void>;
|
| 24 |
+
read(name: string, key: IDBValidKey, timeout?: number, signal?: AbortSignal | null): Promise<unknown>;
|
| 25 |
+
writeContent(name: string, values: object[], limit: number, ttl: number): void;
|
| 26 |
+
writePosition(position: SearchPosition, prune: boolean): void;
|
| 27 |
+
}
|
| 28 |
+
interface SearchPositionPersistence {
|
| 29 |
+
readonly positions: ReadonlyMap<string, SearchPosition>;
|
| 30 |
+
readonly viewports: ReadonlyMap<string, SearchPositionViewport>;
|
| 31 |
+
readonly recentPages: ReadonlyMap<string, SearchRecentPage>;
|
| 32 |
+
init(): Promise<void>;
|
| 33 |
+
getPosition(key: string): SearchPosition | undefined;
|
| 34 |
+
save(position: SearchPosition, capture: () => void): SearchPosition;
|
| 35 |
+
saveViewport(position: SearchPosition, view: SearchPositionView, geometry: SearchPositionGeometry): void;
|
| 36 |
+
saveRecentPages(position: SearchPosition, view: SearchPositionView, visibleEnd: number): void;
|
| 37 |
+
readViewport(key: string): Promise<SearchPositionViewport | null>;
|
| 38 |
+
readRecentPage(key: string, page: number, expected: VoiceOfMLSearchWindowExpected & {query: {pageSize: number}}, timeout?: number, signal?: AbortSignal | null): Promise<SearchRecentPage | null>;
|
| 39 |
+
scheduleSave(save: () => void): void; cancelSave(): void;
|
| 40 |
+
}
|
| 41 |
+
declare var VoiceOfMLPositionPolicy: {
|
| 42 |
+
POSITION_MAX: number; POSITION_TTL: number; VIEWPORT_MAX: number; VIEWPORT_BYTES_MAX: number;
|
| 43 |
+
RECENT_PAGE_MAX: number; RECENT_PAGE_BYTES_MAX: number; RECENT_PAGE_TTL: number;
|
| 44 |
+
validPosition(value: unknown): value is SearchPosition;
|
| 45 |
+
validViewport(value: unknown, position: SearchPosition | null | undefined, stableId: (record: unknown) => string): value is SearchPositionViewport;
|
| 46 |
+
validRecentPage(value: unknown, key: string, page: number, expected: VoiceOfMLSearchWindowExpected & {query: {pageSize: number}}): value is SearchRecentPage;
|
| 47 |
+
};
|
| 48 |
+
declare var VoiceOfMLPositionStorage: {
|
| 49 |
+
create(): SearchPositionStorage;
|
| 50 |
+
pruneContent(store: IDBObjectStore, limit: number, ttl: number): void;
|
| 51 |
+
};
|
| 52 |
+
declare var VoiceOfMLSearchPositions: {
|
| 53 |
+
create(deps: {storage: SearchPositionStorage; cloneResult(record: unknown): unknown;
|
| 54 |
+
metadata(record: unknown): {generation?: string | undefined; total: number} | undefined}): SearchPositionPersistence;
|
| 55 |
+
};
|