vomebook commited on
Commit ·
8f2e8ae
1
Parent(s): f4d7828
Layer Reader document transport and host navigation
Browse files- backend/app.py +49 -378
- backend/reader/document/__init__.py +1 -0
- backend/reader/document/application/__init__.py +1 -0
- backend/reader/document/application/ranges.py +127 -0
- backend/reader/document/domain/__init__.py +1 -0
- backend/reader/document/domain/policy.py +36 -0
- backend/reader/document/http/__init__.py +1 -0
- backend/reader/document/http/transport.py +331 -0
- config/types/jsconfig.check.json +3 -0
- config/types/jsconfig.search-exact.json +3 -0
- config/types/jsconfig.strict.json +3 -0
- eslint.config.mjs +1 -1
- pyrightconfig.strict.json +7 -0
- scripts/build/check_reader_release.mjs +1 -0
- scripts/build/compose_app.mjs +1 -0
- static/app.js +79 -274
- static/index.html +2 -0
- static/reader-resources.js +1 -0
- static/search/reader-host/application/host.js +191 -0
- static/search/reader-host/presentation/return-position.js +120 -0
- static/sw.js +2 -0
- tests/gates/test_static_contract.py +9 -4
- tests/reader/backend/test_reader_range_flights.py +150 -0
- tests/search/reader-navigation/host_contracts.mjs +119 -0
- tests/search/reader-navigation/test_search_history_races.mjs +7 -0
- tests/support/classic_search_modules.js +1 -0
- typings/search-reader-host.d.ts +53 -0
backend/app.py
CHANGED
|
@@ -3,7 +3,6 @@
|
|
| 3 |
import asyncio
|
| 4 |
import gzip
|
| 5 |
import hashlib
|
| 6 |
-
import inspect
|
| 7 |
import json
|
| 8 |
import random
|
| 9 |
import re
|
|
@@ -62,9 +61,24 @@ from backend.search_words import (build_vocab_by_len as _build_vocab_by_len, bui
|
|
| 62 |
from backend.search_matching import (compile_exact_matcher as compile_exact_matcher,
|
| 63 |
split_exact_terms as split_exact_terms, edit_distance as edit_distance,
|
| 64 |
could_be_fuzzy as could_be_fuzzy, is_fuzzy_match as is_fuzzy_match)
|
| 65 |
-
from backend.proxy_streams import
|
|
|
|
|
|
|
| 66 |
from backend.reader_range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,
|
| 67 |
requested_range_bounds as _requested_range_bounds)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
from backend.search_execution import SearchBusy, SearchExecutor, check_search_cancelled
|
| 69 |
from backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnect
|
| 70 |
from backend.search.application.cached import (
|
|
@@ -135,10 +149,6 @@ JsonObject = dict[str, object]
|
|
| 135 |
# Index postings are built as lists and published as packed arrays.
|
| 136 |
IndexPostings = MutableSequence[int]
|
| 137 |
CacheKey = tuple[int, str, str]
|
| 138 |
-
# (target URL, Range header, byte limit, media type) and its cached 206 body.
|
| 139 |
-
RangeKey = tuple[str, str, int | None, str | None]
|
| 140 |
-
RangeCacheEntry = tuple[float, bytes, dict[str, str]]
|
| 141 |
-
RangeFlightKey = tuple[RangeKey, Hashable, str | None]
|
| 142 |
_T = TypeVar("_T")
|
| 143 |
|
| 144 |
|
|
@@ -1538,15 +1548,6 @@ def reader_bucket_source_url(path: str) -> str:
|
|
| 1538 |
READER_BUSY_HEADERS = {"Cache-Control": "no-store", "Retry-After": "1"}
|
| 1539 |
|
| 1540 |
|
| 1541 |
-
class ReaderStreamOptions(TypedDict):
|
| 1542 |
-
"""Transport policy shared by every subscriber of one range flight."""
|
| 1543 |
-
url_validator: Callable[[str], str]
|
| 1544 |
-
cache_control: str | None
|
| 1545 |
-
max_bytes: int | None
|
| 1546 |
-
media_type: str | None
|
| 1547 |
-
validation_scope: Hashable | None
|
| 1548 |
-
|
| 1549 |
-
|
| 1550 |
def validate_reader_bucket_redirect_url(url: str, source_url: str) -> str:
|
| 1551 |
return _validate_reader_bucket_redirect_url(url, source_url,
|
| 1552 |
lambda target, source: validate_fixed_source_redirect_url(target, source))
|
|
@@ -1863,15 +1864,7 @@ async def api_reader_content(request: Request, url: Optional[str] = Query(defaul
|
|
| 1863 |
|
| 1864 |
|
| 1865 |
def reader_document_browser_headers(target_url: str, headers: dict[str, str], status: int) -> dict[str, str]:
|
| 1866 |
-
|
| 1867 |
-
headers.get("Content-Type", "").split(";", 1)[0].strip().lower() == "application/pdf"
|
| 1868 |
-
or urlparse(target_url).path.lower().endswith(".pdf")
|
| 1869 |
-
)
|
| 1870 |
-
if status == 206 and is_pdf:
|
| 1871 |
-
# Keep browser partial bodies separate from the bounded server cache.
|
| 1872 |
-
# The request-side PDF policy bypasses Chromium's same-URL cache lock.
|
| 1873 |
-
return {**headers, "Cache-Control": "no-store"}
|
| 1874 |
-
return headers
|
| 1875 |
|
| 1876 |
|
| 1877 |
async def stream_reader_document(
|
|
@@ -1886,52 +1879,7 @@ async def stream_reader_document(
|
|
| 1886 |
max_bytes=max_bytes, media_type=media_type, validation_scope=validation_scope,
|
| 1887 |
expected_sha256=expected_sha256, expected_bytes=expected_bytes,
|
| 1888 |
)
|
| 1889 |
-
|
| 1890 |
-
return await open_stream()
|
| 1891 |
-
|
| 1892 |
-
stop_watching = asyncio.Event()
|
| 1893 |
-
|
| 1894 |
-
async def disconnected():
|
| 1895 |
-
while not stop_watching.is_set():
|
| 1896 |
-
if await request.is_disconnected():
|
| 1897 |
-
return
|
| 1898 |
-
if not stop_watching.is_set():
|
| 1899 |
-
await asyncio.sleep(0.1)
|
| 1900 |
-
|
| 1901 |
-
# StreamingResponse handles disconnects after headers; own the wait for
|
| 1902 |
-
# the upstream slot and headers too, so abandoned books cannot occupy it.
|
| 1903 |
-
transport = asyncio.create_task(open_stream())
|
| 1904 |
-
watcher = asyncio.create_task(disconnected())
|
| 1905 |
-
selected: Response | None = None
|
| 1906 |
-
try:
|
| 1907 |
-
try:
|
| 1908 |
-
await asyncio.wait((transport, watcher), return_when=asyncio.FIRST_COMPLETED)
|
| 1909 |
-
if transport.done():
|
| 1910 |
-
selected = transport.result()
|
| 1911 |
-
else:
|
| 1912 |
-
raise asyncio.CancelledError()
|
| 1913 |
-
finally:
|
| 1914 |
-
stop_watching.set()
|
| 1915 |
-
watcher.cancel()
|
| 1916 |
-
if not transport.done():
|
| 1917 |
-
transport.cancel()
|
| 1918 |
-
await asyncio.gather(transport, watcher, return_exceptions=True)
|
| 1919 |
-
return selected
|
| 1920 |
-
except BaseException:
|
| 1921 |
-
# Headers may have arrived before cancellation, but the ASGI response
|
| 1922 |
-
# is not owned by the caller until this coroutine actually returns.
|
| 1923 |
-
if transport.done() and not transport.cancelled() and transport.exception() is None:
|
| 1924 |
-
response = transport.result()
|
| 1925 |
-
if isinstance(response, OwnedStreamingResponse):
|
| 1926 |
-
try:
|
| 1927 |
-
cleanup_result = response.cleanup()
|
| 1928 |
-
if inspect.isawaitable(cleanup_result):
|
| 1929 |
-
await cleanup_result
|
| 1930 |
-
finally:
|
| 1931 |
-
close = getattr(response.body_iterator, "aclose", None)
|
| 1932 |
-
if close is not None:
|
| 1933 |
-
await close()
|
| 1934 |
-
raise
|
| 1935 |
|
| 1936 |
|
| 1937 |
async def _stream_reader_document(
|
|
@@ -1941,219 +1889,29 @@ async def _stream_reader_document(
|
|
| 1941 |
_share_range: bool = True,
|
| 1942 |
expected_sha256: str | None = None, expected_bytes: int | None = None,
|
| 1943 |
) -> Response:
|
| 1944 |
-
|
| 1945 |
-
|
| 1946 |
-
|
| 1947 |
-
|
| 1948 |
-
|
| 1949 |
-
|
| 1950 |
-
|
| 1951 |
-
|
| 1952 |
-
|
| 1953 |
-
|
| 1954 |
-
|
| 1955 |
-
|
| 1956 |
-
|
| 1957 |
-
|
| 1958 |
-
|
| 1959 |
-
|
| 1960 |
-
|
| 1961 |
-
|
| 1962 |
-
|
| 1963 |
-
|
| 1964 |
-
|
| 1965 |
-
|
| 1966 |
-
|
| 1967 |
-
and scope_parts[1] == target_url)
|
| 1968 |
-
cache_policy_safe = ((url_validator is validate_reader_redirect_url and validation_scope is None
|
| 1969 |
-
and cache_control is None) or bucket_cache_policy)
|
| 1970 |
-
range_key: RangeKey | None = (
|
| 1971 |
-
(target_url, range_header, max_bytes, media_type)
|
| 1972 |
-
if request.method == "GET" and range_header and not has_conditionals and expected_sha256 is None
|
| 1973 |
-
else None
|
| 1974 |
-
)
|
| 1975 |
-
if range_key:
|
| 1976 |
-
# A cache hit must not bypass the caller's current source policy.
|
| 1977 |
-
# A validator may normalize the target; the cache key and redirects
|
| 1978 |
-
# are derived from the normalized URL for this request.
|
| 1979 |
-
try:
|
| 1980 |
-
target_url = url_validator(target_url)
|
| 1981 |
-
except Exception as exc:
|
| 1982 |
-
print(f"阅读代理异常: {exc}")
|
| 1983 |
-
return JSONResponse({"error": str(exc) or "上游阅读文件加载失败"}, status_code=502)
|
| 1984 |
-
range_key = (target_url, range_key[1], max_bytes, media_type)
|
| 1985 |
-
if cache_policy_safe:
|
| 1986 |
-
if not hasattr(app.state, "reader_range_cache"):
|
| 1987 |
-
app.state.reader_range_cache = cast("OrderedDict[RangeKey, RangeCacheEntry]", OrderedDict())
|
| 1988 |
-
app.state.reader_range_cache_bytes = 0
|
| 1989 |
-
cached = app.state.reader_range_cache.get(range_key)
|
| 1990 |
-
if cached:
|
| 1991 |
-
cached_at, payload, cached_headers = cached
|
| 1992 |
-
if time.monotonic() - cached_at < READER_RANGE_CACHE_TTL_SECONDS:
|
| 1993 |
-
app.state.reader_range_cache.move_to_end(range_key)
|
| 1994 |
-
return Response(content=payload, status_code=206,
|
| 1995 |
-
headers=reader_proxy_timing(
|
| 1996 |
-
reader_document_browser_headers(target_url, cached_headers, 206), cache="hit"))
|
| 1997 |
-
app.state.reader_range_cache.pop(range_key, None)
|
| 1998 |
-
app.state.reader_range_cache_bytes -= len(payload)
|
| 1999 |
-
covered = reader_cached_subrange(range_key)
|
| 2000 |
-
if covered is not None:
|
| 2001 |
-
payload, cached_headers = covered
|
| 2002 |
-
return Response(content=payload, status_code=206, headers=reader_proxy_timing(
|
| 2003 |
-
reader_document_browser_headers(target_url, cached_headers, 206), cache="slice"))
|
| 2004 |
-
requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_header or "")
|
| 2005 |
-
if (_share_range and requested and int(requested[1]) <= int(requested[2])
|
| 2006 |
-
and int(requested[2]) - int(requested[1]) + 1 <= READER_RANGE_CACHE_MAX_ITEM_BYTES
|
| 2007 |
-
and (urlparse(target_url).path.lower().endswith(".pdf") or media_type == "application/pdf")):
|
| 2008 |
-
return await shared_reader_range_response(request, target_url, range_key, ReaderStreamOptions(
|
| 2009 |
-
url_validator=url_validator, cache_control=cache_control,
|
| 2010 |
-
max_bytes=max_bytes, media_type=media_type, validation_scope=cast(Hashable | None, validation_scope)))
|
| 2011 |
-
semaphore = app.state.upstream_semaphore
|
| 2012 |
-
queued_at = time.monotonic()
|
| 2013 |
-
await semaphore.acquire()
|
| 2014 |
-
acquired_at = time.monotonic()
|
| 2015 |
-
lease = UpstreamLease(semaphore)
|
| 2016 |
-
try:
|
| 2017 |
-
upstream = lease.response = await open_download_response(
|
| 2018 |
-
app.state.http_session,
|
| 2019 |
-
target_url,
|
| 2020 |
-
# A fixed 180-second total can truncate a valid multi-gigabyte PDF
|
| 2021 |
-
# on a slow connection; retain connect and idle-read timeouts.
|
| 2022 |
-
aiohttp.ClientTimeout(total=None if is_media_stream or is_pdf else 180, connect=15, sock_read=60),
|
| 2023 |
-
method=request.method,
|
| 2024 |
-
request_headers=forwarded_headers,
|
| 2025 |
-
url_validator=url_validator,
|
| 2026 |
-
auto_decompress=False,
|
| 2027 |
-
)
|
| 2028 |
-
headers_at = time.monotonic()
|
| 2029 |
-
# Range offsets and document limits describe identity bytes, not compressed wire bytes.
|
| 2030 |
-
if upstream.headers.get("Content-Encoding", "identity").strip().lower() != "identity":
|
| 2031 |
-
return JSONResponse({"error": "上游阅读文件编码无效"}, status_code=502)
|
| 2032 |
-
headers = {name: upstream.headers[name] for name in READER_UPSTREAM_RESPONSE_HEADERS if name in upstream.headers}
|
| 2033 |
-
headers.update(READER_ISOLATION_HEADERS)
|
| 2034 |
-
headers["Cache-Control"] = cache_control or headers.get("Cache-Control", "public, max-age=300")
|
| 2035 |
-
# Gecko treats any Content-Encoding header as compressed media and
|
| 2036 |
-
# disables length/range seeking. GZipMiddleware already excludes media.
|
| 2037 |
-
if is_media_stream:
|
| 2038 |
-
headers.pop("Content-Encoding", None)
|
| 2039 |
-
elif reader_body_allows_compression(target_url, request, upstream.status):
|
| 2040 |
-
# GZip negotiates the representation; do not advertise an identity
|
| 2041 |
-
# strong validator as byte-equivalent to the encoded response.
|
| 2042 |
-
if headers.get("ETag", "").startswith('"'):
|
| 2043 |
-
headers["ETag"] = "W/" + headers["ETag"]
|
| 2044 |
-
else:
|
| 2045 |
-
headers["Content-Encoding"] = "identity"
|
| 2046 |
-
if media_type:
|
| 2047 |
-
headers["Content-Type"] = media_type
|
| 2048 |
-
status = upstream.status
|
| 2049 |
-
headers = reader_document_browser_headers(target_url, headers, status)
|
| 2050 |
-
headers = reader_proxy_timing(headers, cache="miss", queued=acquired_at - queued_at,
|
| 2051 |
-
upstream=headers_at - acquired_at)
|
| 2052 |
-
declared_length = upstream.headers.get("Content-Length")
|
| 2053 |
-
length = None
|
| 2054 |
-
if declared_length is not None:
|
| 2055 |
-
try:
|
| 2056 |
-
length = int(declared_length)
|
| 2057 |
-
except (TypeError, ValueError):
|
| 2058 |
-
return JSONResponse({"error": "上游阅读文件长度无效"}, status_code=502)
|
| 2059 |
-
if length < 0 or (max_bytes is not None and length > max_bytes):
|
| 2060 |
-
return JSONResponse({"error": "阅读文件过大"}, status_code=413)
|
| 2061 |
-
content_range = upstream.headers.get("Content-Range")
|
| 2062 |
-
full_requested_range = False
|
| 2063 |
-
if expected_sha256 is not None:
|
| 2064 |
-
if status != 200 or length != expected_bytes:
|
| 2065 |
-
return JSONResponse({'error': '阅读页图长度不匹配'}, status_code=502,
|
| 2066 |
-
headers={'Cache-Control': 'no-store'})
|
| 2067 |
-
if status == 206:
|
| 2068 |
-
match = re.fullmatch(r"bytes\s+([0-9]{1,20})-([0-9]{1,20})/([0-9]{1,20})", str(content_range or ""))
|
| 2069 |
-
if not match:
|
| 2070 |
-
return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)
|
| 2071 |
-
range_start, range_end, total_length = (int(value) for value in match.groups())
|
| 2072 |
-
if (range_start > range_end or range_end >= total_length
|
| 2073 |
-
or (length is not None and length != range_end - range_start + 1)):
|
| 2074 |
-
return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)
|
| 2075 |
-
if total_limit is not None and total_length > total_limit:
|
| 2076 |
-
return JSONResponse({"error": "阅读文件过大"}, status_code=413)
|
| 2077 |
-
if not range_header:
|
| 2078 |
-
return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)
|
| 2079 |
-
bounds = _requested_range_bounds(range_header, total_length)
|
| 2080 |
-
# A 206 may stop early. Forward that prefix but never cache it
|
| 2081 |
-
# as the complete request; a wrong start would corrupt offsets.
|
| 2082 |
-
if bounds is not None:
|
| 2083 |
-
if range_start != bounds[0] or range_end > bounds[1]:
|
| 2084 |
-
return JSONResponse({"error": "上游阅读文���范围无效"}, status_code=502)
|
| 2085 |
-
full_requested_range = (range_start, range_end) == bounds
|
| 2086 |
-
elif re.fullmatch(r"bytes=[0-9]{0,20}-[0-9]{0,20}", range_header):
|
| 2087 |
-
return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)
|
| 2088 |
-
elif status == 416:
|
| 2089 |
-
match = re.fullmatch(r"bytes\s+\*/([0-9]{1,20})", str(content_range or ""))
|
| 2090 |
-
if match and total_limit is not None and int(match.group(1)) > total_limit:
|
| 2091 |
-
return JSONResponse({"error": "阅读文件过大"}, status_code=413)
|
| 2092 |
-
if request.method == "HEAD" or status == 304:
|
| 2093 |
-
return Response(status_code=status, headers=headers)
|
| 2094 |
-
if status not in (200, 206, 416):
|
| 2095 |
-
return JSONResponse({"error": f"上游阅读文件加载失败: HTTP {status}"}, status_code=status)
|
| 2096 |
-
|
| 2097 |
-
async def stream_reader_content():
|
| 2098 |
-
total = 0
|
| 2099 |
-
chunks: list[bytes] = []
|
| 2100 |
-
checksum = hashlib.sha256() if expected_sha256 else None
|
| 2101 |
-
tail = b''
|
| 2102 |
-
cacheable = bool(
|
| 2103 |
-
cache_policy_safe and range_key and status == 206 and full_requested_range and length is not None
|
| 2104 |
-
and length <= READER_RANGE_CACHE_MAX_ITEM_BYTES
|
| 2105 |
-
)
|
| 2106 |
-
try:
|
| 2107 |
-
async for chunk in upstream.content.iter_chunked(65536):
|
| 2108 |
-
total += len(chunk)
|
| 2109 |
-
if max_bytes is not None and total > max_bytes:
|
| 2110 |
-
raise ReaderDocumentLimitError("阅读文件过大")
|
| 2111 |
-
if cacheable:
|
| 2112 |
-
chunks.append(chunk)
|
| 2113 |
-
if checksum is not None:
|
| 2114 |
-
checksum.update(chunk)
|
| 2115 |
-
if expected_bytes is None or total > expected_bytes:
|
| 2116 |
-
raise ValueError('reading image exceeds its pinned size')
|
| 2117 |
-
# Stream previews while retaining the completion marker.
|
| 2118 |
-
# Once the pinned size is reached, send the final chunk
|
| 2119 |
-
# after verification as one piece. A one-byte final
|
| 2120 |
-
# refinement can trigger another native image decode.
|
| 2121 |
-
pending = tail + chunk
|
| 2122 |
-
if total == expected_bytes:
|
| 2123 |
-
tail = pending
|
| 2124 |
-
elif len(pending) > 1:
|
| 2125 |
-
yield pending[:-1]
|
| 2126 |
-
tail = pending[-1:]
|
| 2127 |
-
else:
|
| 2128 |
-
tail = pending
|
| 2129 |
-
else:
|
| 2130 |
-
yield chunk
|
| 2131 |
-
if checksum is not None:
|
| 2132 |
-
if total != expected_bytes or checksum.hexdigest() != expected_sha256:
|
| 2133 |
-
raise ValueError('reading image checksum mismatch')
|
| 2134 |
-
yield tail
|
| 2135 |
-
if cacheable and total == length:
|
| 2136 |
-
payload = b"".join(chunks)
|
| 2137 |
-
cache = app.state.reader_range_cache
|
| 2138 |
-
previous = cache.pop(range_key, None)
|
| 2139 |
-
if previous:
|
| 2140 |
-
app.state.reader_range_cache_bytes -= len(previous[1])
|
| 2141 |
-
cache[range_key] = (time.monotonic(), payload, headers)
|
| 2142 |
-
app.state.reader_range_cache_bytes += len(payload)
|
| 2143 |
-
while (app.state.reader_range_cache_bytes > READER_RANGE_CACHE_MAX_BYTES
|
| 2144 |
-
or len(cache) > READER_RANGE_CACHE_MAX_ENTRIES):
|
| 2145 |
-
_, (_, evicted, _) = cache.popitem(last=False)
|
| 2146 |
-
app.state.reader_range_cache_bytes -= len(evicted)
|
| 2147 |
-
finally:
|
| 2148 |
-
lease.close()
|
| 2149 |
-
|
| 2150 |
-
return lease.streaming_response(stream_reader_content(), status_code=status, headers=headers)
|
| 2151 |
-
except Exception as exc:
|
| 2152 |
-
print(f"阅读代理异常: {exc}")
|
| 2153 |
-
return JSONResponse({"error": str(exc) or "上游阅读文件加载失败"}, status_code=502)
|
| 2154 |
-
finally:
|
| 2155 |
-
if not lease.transferred:
|
| 2156 |
-
lease.close()
|
| 2157 |
|
| 2158 |
|
| 2159 |
@app.api_route("/api/reader-cdn", methods=["GET", "HEAD"])
|
|
@@ -2427,13 +2185,6 @@ async def serve_spa(rest_of_path: str):
|
|
| 2427 |
return HTMLResponse(inject_initial_payload(index_path.read_text(encoding="utf-8"), repo_short))
|
| 2428 |
return PlainTextResponse("Frontend shell unavailable", status_code=503)
|
| 2429 |
|
| 2430 |
-
def reader_proxy_timing(headers: Mapping[str, str], *, cache: str, queued: float = 0, upstream: float = 0) -> dict[str, str]:
|
| 2431 |
-
return {**headers, "Server-Timing": (
|
| 2432 |
-
f'reader_cache;desc="{cache}", reader_queue;dur={queued * 1000:.2f}, '
|
| 2433 |
-
f'reader_headers;dur={upstream * 1000:.2f}'
|
| 2434 |
-
)}
|
| 2435 |
-
|
| 2436 |
-
|
| 2437 |
def reader_cached_subrange(range_key: RangeKey) -> tuple[bytes, dict[str, str]] | None:
|
| 2438 |
return _cached_reader_subrange(
|
| 2439 |
range_key, lambda: cast(_RangeCacheState, app.state),
|
|
@@ -2442,95 +2193,15 @@ def reader_cached_subrange(range_key: RangeKey) -> tuple[bytes, dict[str, str]]
|
|
| 2442 |
)
|
| 2443 |
|
| 2444 |
async def shutdown_reader_range_flights() -> None:
|
| 2445 |
-
|
| 2446 |
-
closing = list(owners)
|
| 2447 |
-
results = await asyncio.gather(*(flight.close() for flight in closing), return_exceptions=True)
|
| 2448 |
-
errors: list[BaseException] = []
|
| 2449 |
-
flights: dict[RangeFlightKey, SharedRangeFlight] = getattr(app.state, "reader_range_flights", {})
|
| 2450 |
-
for flight, result in zip(closing, results):
|
| 2451 |
-
if isinstance(result, BaseException):
|
| 2452 |
-
owners.add(flight) # Retain failed cleanup ownership for diagnosis/retry.
|
| 2453 |
-
errors.append(result)
|
| 2454 |
-
else:
|
| 2455 |
-
owners.discard(flight)
|
| 2456 |
-
for key in list(flights):
|
| 2457 |
-
if flights[key] is flight:
|
| 2458 |
-
flights.pop(key)
|
| 2459 |
-
if errors:
|
| 2460 |
-
raise BaseExceptionGroup("Reader range flight close failures", errors)
|
| 2461 |
|
| 2462 |
|
| 2463 |
async def shared_reader_range_response(request: Request, target_url: str, range_key: RangeKey,
|
| 2464 |
options: ReaderStreamOptions) -> Response:
|
| 2465 |
-
|
| 2466 |
-
|
| 2467 |
-
|
| 2468 |
-
|
| 2469 |
-
|
| 2470 |
-
|
| 2471 |
-
|
| 2472 |
-
policy = options["validation_scope"] if options["validation_scope"] is not None else options["url_validator"]
|
| 2473 |
-
key: RangeFlightKey = (range_key, policy, options["cache_control"])
|
| 2474 |
-
flight = flights.get(key)
|
| 2475 |
-
joined = flight is not None
|
| 2476 |
-
if flight is None:
|
| 2477 |
-
if len(flights) >= READER_RANGE_MAX_FLIGHTS:
|
| 2478 |
-
return await _stream_reader_document(request, target_url, _share_range=False, **options)
|
| 2479 |
-
|
| 2480 |
-
def finished(owner: SharedRangeFlight) -> None:
|
| 2481 |
-
if flights.get(key) is owner:
|
| 2482 |
-
flights.pop(key, None)
|
| 2483 |
-
if owner.done and owner.close_error is None:
|
| 2484 |
-
owners.discard(owner)
|
| 2485 |
-
|
| 2486 |
-
flight = SharedRangeFlight(
|
| 2487 |
-
lambda: _stream_reader_document(request, target_url, _share_range=False, **options),
|
| 2488 |
-
READER_RANGE_CACHE_MAX_ITEM_BYTES, finished)
|
| 2489 |
-
flights[key] = flight
|
| 2490 |
-
owners.add(flight)
|
| 2491 |
-
subscription = flight.subscribe()
|
| 2492 |
-
shared_at = time.monotonic()
|
| 2493 |
-
transferred = False
|
| 2494 |
-
selected: Response | None = None
|
| 2495 |
-
try:
|
| 2496 |
-
try:
|
| 2497 |
-
if not await asyncio.shield(flight.ready):
|
| 2498 |
-
selected = flight.take_response()
|
| 2499 |
-
if selected is None:
|
| 2500 |
-
selected = await _stream_reader_document(request, target_url, _share_range=False, **options)
|
| 2501 |
-
else:
|
| 2502 |
-
headers = dict(flight.headers)
|
| 2503 |
-
if joined:
|
| 2504 |
-
headers["server-timing"] += f', reader_shared;dur={(time.monotonic() - shared_at) * 1000:.2f};desc="joined"'
|
| 2505 |
-
selected = OwnedStreamingResponse(subscription.stream(), cleanup=subscription.release,
|
| 2506 |
-
status_code=206, headers=headers)
|
| 2507 |
-
transferred = True
|
| 2508 |
-
finally:
|
| 2509 |
-
if not transferred:
|
| 2510 |
-
await subscription.release()
|
| 2511 |
-
return selected
|
| 2512 |
-
except BaseException:
|
| 2513 |
-
# A selected declined/fallback response is still ours while release
|
| 2514 |
-
# awaits. Cancellation there must not lose its upstream lease.
|
| 2515 |
-
if selected is not None:
|
| 2516 |
-
cleanup_owner = SharedRangeFlight(lambda: asyncio.sleep(0, result=cast(Response, selected)),
|
| 2517 |
-
READER_RANGE_CACHE_MAX_ITEM_BYTES, owners.discard)
|
| 2518 |
-
cleanup_owner.response = selected
|
| 2519 |
-
owners.add(cleanup_owner)
|
| 2520 |
-
cleanup = asyncio.create_task(cleanup_owner.close())
|
| 2521 |
-
while not cleanup.done():
|
| 2522 |
-
try:
|
| 2523 |
-
await asyncio.shield(cleanup)
|
| 2524 |
-
except asyncio.CancelledError:
|
| 2525 |
-
continue
|
| 2526 |
-
except BaseException:
|
| 2527 |
-
break
|
| 2528 |
-
try:
|
| 2529 |
-
cleanup.result()
|
| 2530 |
-
except BaseException as error:
|
| 2531 |
-
asyncio.get_running_loop().call_exception_handler({
|
| 2532 |
-
"message": "Reader response cleanup failed during interrupted handoff",
|
| 2533 |
-
"exception": error,
|
| 2534 |
-
"task": cleanup,
|
| 2535 |
-
})
|
| 2536 |
-
raise
|
|
|
|
| 3 |
import asyncio
|
| 4 |
import gzip
|
| 5 |
import hashlib
|
|
|
|
| 6 |
import json
|
| 7 |
import random
|
| 8 |
import re
|
|
|
|
| 61 |
from backend.search_matching import (compile_exact_matcher as compile_exact_matcher,
|
| 62 |
split_exact_terms as split_exact_terms, edit_distance as edit_distance,
|
| 63 |
could_be_fuzzy as could_be_fuzzy, is_fuzzy_match as is_fuzzy_match)
|
| 64 |
+
from backend.proxy_streams import (
|
| 65 |
+
OwnedStreamingResponse as OwnedStreamingResponse, SharedRangeFlight as SharedRangeFlight, UpstreamLease,
|
| 66 |
+
)
|
| 67 |
from backend.reader_range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,
|
| 68 |
requested_range_bounds as _requested_range_bounds)
|
| 69 |
+
from backend.reader.document.domain.policy import (
|
| 70 |
+
RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry, RangeFlightKey as RangeFlightKey,
|
| 71 |
+
ReaderStreamOptions as ReaderStreamOptions,
|
| 72 |
+
reader_document_browser_headers as _reader_document_browser_headers, reader_proxy_timing as reader_proxy_timing,
|
| 73 |
+
)
|
| 74 |
+
from backend.reader.document.http.transport import (
|
| 75 |
+
DocumentState, DocumentDependencies, stream_with_disconnect as _stream_with_disconnect,
|
| 76 |
+
stream_document as _document_transport,
|
| 77 |
+
)
|
| 78 |
+
from backend.reader.document.application.ranges import (
|
| 79 |
+
RangeFlightState, RangeDependencies, shutdown_range_flights as _shutdown_range_flights,
|
| 80 |
+
shared_range_response as _shared_range_response,
|
| 81 |
+
)
|
| 82 |
from backend.search_execution import SearchBusy, SearchExecutor, check_search_cancelled
|
| 83 |
from backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnect
|
| 84 |
from backend.search.application.cached import (
|
|
|
|
| 149 |
# Index postings are built as lists and published as packed arrays.
|
| 150 |
IndexPostings = MutableSequence[int]
|
| 151 |
CacheKey = tuple[int, str, str]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
_T = TypeVar("_T")
|
| 153 |
|
| 154 |
|
|
|
|
| 1548 |
READER_BUSY_HEADERS = {"Cache-Control": "no-store", "Retry-After": "1"}
|
| 1549 |
|
| 1550 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1551 |
def validate_reader_bucket_redirect_url(url: str, source_url: str) -> str:
|
| 1552 |
return _validate_reader_bucket_redirect_url(url, source_url,
|
| 1553 |
lambda target, source: validate_fixed_source_redirect_url(target, source))
|
|
|
|
| 1864 |
|
| 1865 |
|
| 1866 |
def reader_document_browser_headers(target_url: str, headers: dict[str, str], status: int) -> dict[str, str]:
|
| 1867 |
+
return _reader_document_browser_headers(target_url, headers, status, lambda url: urlparse(url).path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1868 |
|
| 1869 |
|
| 1870 |
async def stream_reader_document(
|
|
|
|
| 1879 |
max_bytes=max_bytes, media_type=media_type, validation_scope=validation_scope,
|
| 1880 |
expected_sha256=expected_sha256, expected_bytes=expected_bytes,
|
| 1881 |
)
|
| 1882 |
+
return await _stream_with_disconnect(request, open_stream)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1883 |
|
| 1884 |
|
| 1885 |
async def _stream_reader_document(
|
|
|
|
| 1889 |
_share_range: bool = True,
|
| 1890 |
expected_sha256: str | None = None, expected_bytes: int | None = None,
|
| 1891 |
) -> Response:
|
| 1892 |
+
return await _document_transport(request, target_url, DocumentDependencies(
|
| 1893 |
+
state=lambda: cast(DocumentState, app.state),
|
| 1894 |
+
open_response=lambda: open_download_response,
|
| 1895 |
+
redirect_validator=lambda: validate_reader_redirect_url,
|
| 1896 |
+
bucket_validator=lambda: validate_reader_bucket_redirect_url,
|
| 1897 |
+
shared_response=lambda: shared_reader_range_response,
|
| 1898 |
+
cached_subrange=lambda key: reader_cached_subrange(key),
|
| 1899 |
+
range_bounds=lambda header, total: _requested_range_bounds(header, total),
|
| 1900 |
+
browser_headers=lambda url, headers, status: reader_document_browser_headers(url, headers, status),
|
| 1901 |
+
timing=lambda: reader_proxy_timing,
|
| 1902 |
+
allows_compression=lambda url, req, status: reader_body_allows_compression(url, req, status),
|
| 1903 |
+
upstream_headers=lambda: READER_UPSTREAM_RESPONSE_HEADERS,
|
| 1904 |
+
isolation_headers=lambda: READER_ISOLATION_HEADERS,
|
| 1905 |
+
document_max_bytes=lambda: READER_DOCUMENT_MAX_BYTES,
|
| 1906 |
+
cache_ttl=lambda: READER_RANGE_CACHE_TTL_SECONDS,
|
| 1907 |
+
cache_max_item_bytes=lambda: READER_RANGE_CACHE_MAX_ITEM_BYTES,
|
| 1908 |
+
cache_max_bytes=lambda: READER_RANGE_CACHE_MAX_BYTES,
|
| 1909 |
+
cache_max_entries=lambda: READER_RANGE_CACHE_MAX_ENTRIES,
|
| 1910 |
+
limit_error=lambda: ReaderDocumentLimitError,
|
| 1911 |
+
clock=lambda: time.monotonic(),
|
| 1912 |
+
), url_validator=url_validator, cache_control=cache_control,
|
| 1913 |
+
max_bytes=max_bytes, media_type=media_type, validation_scope=validation_scope,
|
| 1914 |
+
_share_range=_share_range, expected_sha256=expected_sha256, expected_bytes=expected_bytes)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1915 |
|
| 1916 |
|
| 1917 |
@app.api_route("/api/reader-cdn", methods=["GET", "HEAD"])
|
|
|
|
| 2185 |
return HTMLResponse(inject_initial_payload(index_path.read_text(encoding="utf-8"), repo_short))
|
| 2186 |
return PlainTextResponse("Frontend shell unavailable", status_code=503)
|
| 2187 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2188 |
def reader_cached_subrange(range_key: RangeKey) -> tuple[bytes, dict[str, str]] | None:
|
| 2189 |
return _cached_reader_subrange(
|
| 2190 |
range_key, lambda: cast(_RangeCacheState, app.state),
|
|
|
|
| 2193 |
)
|
| 2194 |
|
| 2195 |
async def shutdown_reader_range_flights() -> None:
|
| 2196 |
+
await _shutdown_range_flights(lambda: cast(RangeFlightState, app.state))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2197 |
|
| 2198 |
|
| 2199 |
async def shared_reader_range_response(request: Request, target_url: str, range_key: RangeKey,
|
| 2200 |
options: ReaderStreamOptions) -> Response:
|
| 2201 |
+
return await _shared_range_response(request, target_url, range_key, options, RangeDependencies(
|
| 2202 |
+
state=lambda: cast(RangeFlightState, app.state),
|
| 2203 |
+
stream=lambda: _stream_reader_document,
|
| 2204 |
+
max_flights=lambda: READER_RANGE_MAX_FLIGHTS,
|
| 2205 |
+
max_item_bytes=lambda: READER_RANGE_CACHE_MAX_ITEM_BYTES,
|
| 2206 |
+
clock=lambda: time.monotonic(),
|
| 2207 |
+
))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/reader/document/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Reader document transport package."""
|
backend/reader/document/application/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Reader document transport package."""
|
backend/reader/document/application/ranges.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared range admission, subscriber ownership, and worker shutdown."""
|
| 2 |
+
import asyncio
|
| 3 |
+
from collections.abc import Awaitable, Callable, Hashable
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Protocol, cast
|
| 6 |
+
|
| 7 |
+
from fastapi import Request
|
| 8 |
+
from fastapi.responses import Response
|
| 9 |
+
|
| 10 |
+
from backend.proxy_streams import OwnedStreamingResponse, SharedRangeFlight
|
| 11 |
+
from backend.reader.document.domain.policy import RangeFlightKey, RangeKey, ReaderStreamOptions
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class RangeFlightState(Protocol):
|
| 15 |
+
reader_range_flights: dict[RangeFlightKey, SharedRangeFlight]
|
| 16 |
+
reader_range_flight_owners: set[SharedRangeFlight]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class RangeStream(Protocol):
|
| 20 |
+
def __call__(self, request: Request, target_url: str, *,
|
| 21 |
+
url_validator: Callable[[str], str], cache_control: str | None,
|
| 22 |
+
max_bytes: int | None, media_type: str | None, validation_scope: Hashable | None,
|
| 23 |
+
_share_range: bool) -> Awaitable[Response]: ...
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True)
|
| 27 |
+
class RangeDependencies:
|
| 28 |
+
state: Callable[[], RangeFlightState]
|
| 29 |
+
stream: Callable[[], RangeStream]
|
| 30 |
+
max_flights: Callable[[], int]
|
| 31 |
+
max_item_bytes: Callable[[], int]
|
| 32 |
+
clock: Callable[[], float]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
async def shutdown_range_flights(state: Callable[[], RangeFlightState]) -> None:
|
| 36 |
+
owners: set[SharedRangeFlight] = getattr(state(), "reader_range_flight_owners", set())
|
| 37 |
+
closing = list(owners)
|
| 38 |
+
results = await asyncio.gather(*(flight.close() for flight in closing), return_exceptions=True)
|
| 39 |
+
errors: list[BaseException] = []
|
| 40 |
+
flights: dict[RangeFlightKey, SharedRangeFlight] = getattr(state(), "reader_range_flights", {})
|
| 41 |
+
for flight, result in zip(closing, results):
|
| 42 |
+
if isinstance(result, BaseException):
|
| 43 |
+
owners.add(flight) # Retain failed cleanup ownership for diagnosis/retry.
|
| 44 |
+
errors.append(result)
|
| 45 |
+
else:
|
| 46 |
+
owners.discard(flight)
|
| 47 |
+
for key in list(flights):
|
| 48 |
+
if flights[key] is flight:
|
| 49 |
+
flights.pop(key)
|
| 50 |
+
if errors:
|
| 51 |
+
raise BaseExceptionGroup("Reader range flight close failures", errors)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
async def shared_range_response(request: Request, target_url: str, range_key: RangeKey,
|
| 55 |
+
options: ReaderStreamOptions, deps: RangeDependencies) -> Response:
|
| 56 |
+
if not hasattr(deps.state(), "reader_range_flights"):
|
| 57 |
+
new_flights: dict[RangeFlightKey, SharedRangeFlight] = {}
|
| 58 |
+
new_owners: set[SharedRangeFlight] = set()
|
| 59 |
+
deps.state().reader_range_flights = new_flights
|
| 60 |
+
deps.state().reader_range_flight_owners = new_owners
|
| 61 |
+
flights: dict[RangeFlightKey, SharedRangeFlight] = deps.state().reader_range_flights
|
| 62 |
+
owners: set[SharedRangeFlight] = deps.state().reader_range_flight_owners
|
| 63 |
+
policy = options["validation_scope"] if options["validation_scope"] is not None else options["url_validator"]
|
| 64 |
+
key: RangeFlightKey = (range_key, policy, options["cache_control"])
|
| 65 |
+
flight = flights.get(key)
|
| 66 |
+
joined = flight is not None
|
| 67 |
+
if flight is None:
|
| 68 |
+
if len(flights) >= deps.max_flights():
|
| 69 |
+
return await deps.stream()(request, target_url, _share_range=False, **options)
|
| 70 |
+
|
| 71 |
+
def finished(owner: SharedRangeFlight) -> None:
|
| 72 |
+
if flights.get(key) is owner:
|
| 73 |
+
flights.pop(key, None)
|
| 74 |
+
if owner.done and owner.close_error is None:
|
| 75 |
+
owners.discard(owner)
|
| 76 |
+
|
| 77 |
+
flight = SharedRangeFlight(
|
| 78 |
+
lambda: deps.stream()(request, target_url, _share_range=False, **options),
|
| 79 |
+
deps.max_item_bytes(), finished)
|
| 80 |
+
flights[key] = flight
|
| 81 |
+
owners.add(flight)
|
| 82 |
+
subscription = flight.subscribe()
|
| 83 |
+
shared_at = deps.clock()
|
| 84 |
+
transferred = False
|
| 85 |
+
selected: Response | None = None
|
| 86 |
+
try:
|
| 87 |
+
try:
|
| 88 |
+
if not await asyncio.shield(flight.ready):
|
| 89 |
+
selected = flight.take_response()
|
| 90 |
+
if selected is None:
|
| 91 |
+
selected = await deps.stream()(request, target_url, _share_range=False, **options)
|
| 92 |
+
else:
|
| 93 |
+
headers = dict(flight.headers)
|
| 94 |
+
if joined:
|
| 95 |
+
headers["server-timing"] += f', reader_shared;dur={(deps.clock() - shared_at) * 1000:.2f};desc="joined"'
|
| 96 |
+
selected = OwnedStreamingResponse(subscription.stream(), cleanup=subscription.release,
|
| 97 |
+
status_code=206, headers=headers)
|
| 98 |
+
transferred = True
|
| 99 |
+
finally:
|
| 100 |
+
if not transferred:
|
| 101 |
+
await subscription.release()
|
| 102 |
+
return selected
|
| 103 |
+
except BaseException:
|
| 104 |
+
# A selected declined/fallback response is still ours while release
|
| 105 |
+
# awaits. Cancellation there must not lose its upstream lease.
|
| 106 |
+
if selected is not None:
|
| 107 |
+
cleanup_owner = SharedRangeFlight(lambda: asyncio.sleep(0, result=cast(Response, selected)),
|
| 108 |
+
deps.max_item_bytes(), owners.discard)
|
| 109 |
+
cleanup_owner.response = selected
|
| 110 |
+
owners.add(cleanup_owner)
|
| 111 |
+
cleanup = asyncio.create_task(cleanup_owner.close())
|
| 112 |
+
while not cleanup.done():
|
| 113 |
+
try:
|
| 114 |
+
await asyncio.shield(cleanup)
|
| 115 |
+
except asyncio.CancelledError:
|
| 116 |
+
continue
|
| 117 |
+
except BaseException:
|
| 118 |
+
break
|
| 119 |
+
try:
|
| 120 |
+
cleanup.result()
|
| 121 |
+
except BaseException as error:
|
| 122 |
+
asyncio.get_running_loop().call_exception_handler({
|
| 123 |
+
"message": "Reader response cleanup failed during interrupted handoff",
|
| 124 |
+
"exception": error,
|
| 125 |
+
"task": cleanup,
|
| 126 |
+
})
|
| 127 |
+
raise
|
backend/reader/document/domain/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Reader document transport package."""
|
backend/reader/document/domain/policy.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Document transport policy and the identity shared by range subscribers."""
|
| 2 |
+
from collections.abc import Callable, Hashable, Mapping
|
| 3 |
+
from typing import TypedDict
|
| 4 |
+
|
| 5 |
+
from backend.reader_range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry
|
| 6 |
+
|
| 7 |
+
RangeFlightKey = tuple[RangeKey, Hashable, str | None]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ReaderStreamOptions(TypedDict):
|
| 11 |
+
"""Transport policy shared by every subscriber of one range flight."""
|
| 12 |
+
url_validator: Callable[[str], str]
|
| 13 |
+
cache_control: str | None
|
| 14 |
+
max_bytes: int | None
|
| 15 |
+
media_type: str | None
|
| 16 |
+
validation_scope: Hashable | None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def reader_document_browser_headers(target_url: str, headers: dict[str, str], status: int,
|
| 20 |
+
url_path: Callable[[str], str]) -> dict[str, str]:
|
| 21 |
+
is_pdf = (
|
| 22 |
+
headers.get("Content-Type", "").split(";", 1)[0].strip().lower() == "application/pdf"
|
| 23 |
+
or url_path(target_url).lower().endswith(".pdf")
|
| 24 |
+
)
|
| 25 |
+
if status == 206 and is_pdf:
|
| 26 |
+
# Keep browser partial bodies separate from the bounded server cache.
|
| 27 |
+
# The request-side PDF policy bypasses Chromium's same-URL cache lock.
|
| 28 |
+
return {**headers, "Cache-Control": "no-store"}
|
| 29 |
+
return headers
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def reader_proxy_timing(headers: Mapping[str, str], *, cache: str, queued: float = 0, upstream: float = 0) -> dict[str, str]:
|
| 33 |
+
return {**headers, "Server-Timing": (
|
| 34 |
+
f'reader_cache;desc="{cache}", reader_queue;dur={queued * 1000:.2f}, '
|
| 35 |
+
f'reader_headers;dur={upstream * 1000:.2f}'
|
| 36 |
+
)}
|
backend/reader/document/http/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Reader document transport package."""
|
backend/reader/document/http/transport.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Document HTTP transport, byte validation, and the response ownership handoff."""
|
| 2 |
+
import asyncio
|
| 3 |
+
import hashlib
|
| 4 |
+
import inspect
|
| 5 |
+
import re
|
| 6 |
+
from collections import OrderedDict
|
| 7 |
+
from collections.abc import Awaitable, Callable, Coroutine, Hashable, Mapping
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import Protocol, cast
|
| 10 |
+
from urllib.parse import unquote, urlparse
|
| 11 |
+
|
| 12 |
+
import aiohttp
|
| 13 |
+
from fastapi import Request
|
| 14 |
+
from fastapi.responses import JSONResponse, Response
|
| 15 |
+
|
| 16 |
+
from backend.proxy_streams import OwnedStreamingResponse, UpstreamLease
|
| 17 |
+
from backend.reader_range_cache import RangeCacheState
|
| 18 |
+
from backend.reader.document.domain.policy import RangeKey, RangeCacheEntry, ReaderStreamOptions
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class DocumentState(RangeCacheState, Protocol):
|
| 22 |
+
upstream_semaphore: asyncio.Semaphore
|
| 23 |
+
http_session: object
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class OpenResponse(Protocol):
|
| 27 |
+
def __call__(self, session: object, url: str, timeout: aiohttp.ClientTimeout, *,
|
| 28 |
+
method: str, request_headers: dict[str, str], url_validator: Callable[[str], str],
|
| 29 |
+
auto_decompress: bool) -> Awaitable[aiohttp.ClientResponse]: ...
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ProxyTiming(Protocol):
|
| 33 |
+
def __call__(self, headers: Mapping[str, str], *, cache: str,
|
| 34 |
+
queued: float = 0, upstream: float = 0) -> dict[str, str]: ...
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass(frozen=True)
|
| 38 |
+
class DocumentDependencies:
|
| 39 |
+
"""Live transport hooks; request-local policy remains captured by the caller."""
|
| 40 |
+
state: Callable[[], DocumentState]
|
| 41 |
+
open_response: Callable[[], OpenResponse]
|
| 42 |
+
redirect_validator: Callable[[], Callable[[str], str]]
|
| 43 |
+
bucket_validator: Callable[[], Callable[[str, str], str]]
|
| 44 |
+
shared_response: Callable[[], Callable[[Request, str, RangeKey, ReaderStreamOptions], Awaitable[Response]]]
|
| 45 |
+
cached_subrange: Callable[[RangeKey], tuple[bytes, dict[str, str]] | None]
|
| 46 |
+
range_bounds: Callable[[str | None, int], tuple[int, int] | None]
|
| 47 |
+
browser_headers: Callable[[str, dict[str, str], int], dict[str, str]]
|
| 48 |
+
timing: Callable[[], ProxyTiming]
|
| 49 |
+
allows_compression: Callable[[str, Request, int], bool]
|
| 50 |
+
upstream_headers: Callable[[], tuple[str, ...]]
|
| 51 |
+
isolation_headers: Callable[[], Mapping[str, str]]
|
| 52 |
+
document_max_bytes: Callable[[], int]
|
| 53 |
+
cache_ttl: Callable[[], int]
|
| 54 |
+
cache_max_item_bytes: Callable[[], int]
|
| 55 |
+
cache_max_bytes: Callable[[], int]
|
| 56 |
+
cache_max_entries: Callable[[], int]
|
| 57 |
+
limit_error: Callable[[], type[Exception]]
|
| 58 |
+
clock: Callable[[], float]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
async def stream_with_disconnect(request: Request, open_stream: Callable[[], Coroutine[object, object, Response]]) -> Response:
|
| 62 |
+
if not callable(getattr(request, "is_disconnected", None)):
|
| 63 |
+
return await open_stream()
|
| 64 |
+
|
| 65 |
+
stop_watching = asyncio.Event()
|
| 66 |
+
|
| 67 |
+
async def disconnected():
|
| 68 |
+
while not stop_watching.is_set():
|
| 69 |
+
if await request.is_disconnected():
|
| 70 |
+
return
|
| 71 |
+
if not stop_watching.is_set():
|
| 72 |
+
await asyncio.sleep(0.1)
|
| 73 |
+
|
| 74 |
+
# StreamingResponse handles disconnects after headers; own the wait for
|
| 75 |
+
# the upstream slot and headers too, so abandoned books cannot occupy it.
|
| 76 |
+
transport = asyncio.create_task(open_stream())
|
| 77 |
+
watcher = asyncio.create_task(disconnected())
|
| 78 |
+
selected: Response | None = None
|
| 79 |
+
try:
|
| 80 |
+
try:
|
| 81 |
+
await asyncio.wait((transport, watcher), return_when=asyncio.FIRST_COMPLETED)
|
| 82 |
+
if transport.done():
|
| 83 |
+
selected = transport.result()
|
| 84 |
+
else:
|
| 85 |
+
raise asyncio.CancelledError()
|
| 86 |
+
finally:
|
| 87 |
+
stop_watching.set()
|
| 88 |
+
watcher.cancel()
|
| 89 |
+
if not transport.done():
|
| 90 |
+
transport.cancel()
|
| 91 |
+
await asyncio.gather(transport, watcher, return_exceptions=True)
|
| 92 |
+
return selected
|
| 93 |
+
except BaseException:
|
| 94 |
+
# Headers may have arrived before cancellation, but the ASGI response
|
| 95 |
+
# is not owned by the caller until this coroutine actually returns.
|
| 96 |
+
if transport.done() and not transport.cancelled() and transport.exception() is None:
|
| 97 |
+
response = transport.result()
|
| 98 |
+
if isinstance(response, OwnedStreamingResponse):
|
| 99 |
+
try:
|
| 100 |
+
cleanup_result = response.cleanup()
|
| 101 |
+
if inspect.isawaitable(cleanup_result):
|
| 102 |
+
await cleanup_result
|
| 103 |
+
finally:
|
| 104 |
+
close = getattr(response.body_iterator, "aclose", None)
|
| 105 |
+
if close is not None:
|
| 106 |
+
await close()
|
| 107 |
+
raise
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
async def stream_document(
|
| 111 |
+
request: Request, target_url: str, deps: DocumentDependencies, *,
|
| 112 |
+
url_validator: Callable[[str], str], cache_control: str | None = None,
|
| 113 |
+
max_bytes: int | None = None, media_type: str | None = None, validation_scope: Hashable | None = None,
|
| 114 |
+
_share_range: bool = True,
|
| 115 |
+
expected_sha256: str | None = None, expected_bytes: int | None = None,
|
| 116 |
+
) -> Response:
|
| 117 |
+
# Native media is streamed, not parsed or buffered as a complete document.
|
| 118 |
+
# Bound transport memory and idle time instead of rejecting large recordings.
|
| 119 |
+
is_media_stream = bool(media_type and media_type.startswith(("audio/", "video/")))
|
| 120 |
+
is_pdf = media_type == "application/pdf" or unquote(urlparse(target_url).path).lower().endswith(".pdf")
|
| 121 |
+
if max_bytes is None and not is_media_stream:
|
| 122 |
+
max_bytes = deps.document_max_bytes()
|
| 123 |
+
forwarded_headers = {
|
| 124 |
+
name: request.headers[name]
|
| 125 |
+
for name in ("Range", "If-Range", "If-None-Match", "If-Modified-Since")
|
| 126 |
+
if name in request.headers
|
| 127 |
+
}
|
| 128 |
+
range_header = forwarded_headers.get("Range")
|
| 129 |
+
total_limit = max_bytes
|
| 130 |
+
# Conditional requests must reach the origin: a cached partial body cannot
|
| 131 |
+
# represent a 200/304 decision made against a different validator.
|
| 132 |
+
has_conditionals = any(
|
| 133 |
+
name in forwarded_headers for name in ("If-Range", "If-None-Match", "If-Modified-Since")
|
| 134 |
+
)
|
| 135 |
+
# The bounded cache does not record the redirect chain. Reuse is safe
|
| 136 |
+
# only for the standard Reader policy and the explicitly scoped bucket
|
| 137 |
+
# policy; arbitrary custom policies must revalidate each network response.
|
| 138 |
+
scope_parts = cast(tuple[object, ...], validation_scope) if isinstance(validation_scope, tuple) else ()
|
| 139 |
+
bucket_cache_policy = (len(scope_parts) == 2 and scope_parts[0] is deps.bucket_validator()
|
| 140 |
+
and scope_parts[1] == target_url)
|
| 141 |
+
cache_policy_safe = ((url_validator is deps.redirect_validator() and validation_scope is None
|
| 142 |
+
and cache_control is None) or bucket_cache_policy)
|
| 143 |
+
range_key: RangeKey | None = (
|
| 144 |
+
(target_url, range_header, max_bytes, media_type)
|
| 145 |
+
if request.method == "GET" and range_header and not has_conditionals and expected_sha256 is None
|
| 146 |
+
else None
|
| 147 |
+
)
|
| 148 |
+
if range_key:
|
| 149 |
+
# A cache hit must not bypass the caller's current source policy.
|
| 150 |
+
# A validator may normalize the target; the cache key and redirects
|
| 151 |
+
# are derived from the normalized URL for this request.
|
| 152 |
+
try:
|
| 153 |
+
target_url = url_validator(target_url)
|
| 154 |
+
except Exception as exc:
|
| 155 |
+
print(f"阅读代理异常: {exc}")
|
| 156 |
+
return JSONResponse({"error": str(exc) or "上游阅读文件加载失败"}, status_code=502)
|
| 157 |
+
range_key = (target_url, range_key[1], max_bytes, media_type)
|
| 158 |
+
if cache_policy_safe:
|
| 159 |
+
if not hasattr(deps.state(), "reader_range_cache"):
|
| 160 |
+
deps.state().reader_range_cache = cast("OrderedDict[RangeKey, RangeCacheEntry]", OrderedDict())
|
| 161 |
+
deps.state().reader_range_cache_bytes = 0
|
| 162 |
+
cached = deps.state().reader_range_cache.get(range_key)
|
| 163 |
+
if cached:
|
| 164 |
+
cached_at, payload, cached_headers = cached
|
| 165 |
+
if deps.clock() - cached_at < deps.cache_ttl():
|
| 166 |
+
deps.state().reader_range_cache.move_to_end(range_key)
|
| 167 |
+
return Response(content=payload, status_code=206,
|
| 168 |
+
headers=deps.timing()(
|
| 169 |
+
deps.browser_headers(target_url, cached_headers, 206), cache="hit"))
|
| 170 |
+
deps.state().reader_range_cache.pop(range_key, None)
|
| 171 |
+
deps.state().reader_range_cache_bytes -= len(payload)
|
| 172 |
+
covered = deps.cached_subrange(range_key)
|
| 173 |
+
if covered is not None:
|
| 174 |
+
payload, cached_headers = covered
|
| 175 |
+
return Response(content=payload, status_code=206, headers=deps.timing()(
|
| 176 |
+
deps.browser_headers(target_url, cached_headers, 206), cache="slice"))
|
| 177 |
+
requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_header or "")
|
| 178 |
+
if (_share_range and requested and int(requested[1]) <= int(requested[2])
|
| 179 |
+
and int(requested[2]) - int(requested[1]) + 1 <= deps.cache_max_item_bytes()
|
| 180 |
+
and (urlparse(target_url).path.lower().endswith(".pdf") or media_type == "application/pdf")):
|
| 181 |
+
return await deps.shared_response()(request, target_url, range_key, ReaderStreamOptions(
|
| 182 |
+
url_validator=url_validator, cache_control=cache_control,
|
| 183 |
+
max_bytes=max_bytes, media_type=media_type, validation_scope=cast(Hashable | None, validation_scope)))
|
| 184 |
+
semaphore = deps.state().upstream_semaphore
|
| 185 |
+
queued_at = deps.clock()
|
| 186 |
+
await semaphore.acquire()
|
| 187 |
+
acquired_at = deps.clock()
|
| 188 |
+
lease = UpstreamLease(semaphore)
|
| 189 |
+
try:
|
| 190 |
+
upstream = lease.response = await deps.open_response()(
|
| 191 |
+
deps.state().http_session,
|
| 192 |
+
target_url,
|
| 193 |
+
# A fixed 180-second total can truncate a valid multi-gigabyte PDF
|
| 194 |
+
# on a slow connection; retain connect and idle-read timeouts.
|
| 195 |
+
aiohttp.ClientTimeout(total=None if is_media_stream or is_pdf else 180, connect=15, sock_read=60),
|
| 196 |
+
method=request.method,
|
| 197 |
+
request_headers=forwarded_headers,
|
| 198 |
+
url_validator=url_validator,
|
| 199 |
+
auto_decompress=False,
|
| 200 |
+
)
|
| 201 |
+
headers_at = deps.clock()
|
| 202 |
+
# Range offsets and document limits describe identity bytes, not compressed wire bytes.
|
| 203 |
+
if upstream.headers.get("Content-Encoding", "identity").strip().lower() != "identity":
|
| 204 |
+
return JSONResponse({"error": "上游阅读文件编码无效"}, status_code=502)
|
| 205 |
+
headers = {name: upstream.headers[name] for name in deps.upstream_headers() if name in upstream.headers}
|
| 206 |
+
headers.update(deps.isolation_headers())
|
| 207 |
+
headers["Cache-Control"] = cache_control or headers.get("Cache-Control", "public, max-age=300")
|
| 208 |
+
# Gecko treats any Content-Encoding header as compressed media and
|
| 209 |
+
# disables length/range seeking. GZipMiddleware already excludes media.
|
| 210 |
+
if is_media_stream:
|
| 211 |
+
headers.pop("Content-Encoding", None)
|
| 212 |
+
elif deps.allows_compression(target_url, request, upstream.status):
|
| 213 |
+
# GZip negotiates the representation; do not advertise an identity
|
| 214 |
+
# strong validator as byte-equivalent to the encoded response.
|
| 215 |
+
if headers.get("ETag", "").startswith('"'):
|
| 216 |
+
headers["ETag"] = "W/" + headers["ETag"]
|
| 217 |
+
else:
|
| 218 |
+
headers["Content-Encoding"] = "identity"
|
| 219 |
+
if media_type:
|
| 220 |
+
headers["Content-Type"] = media_type
|
| 221 |
+
status = upstream.status
|
| 222 |
+
headers = deps.browser_headers(target_url, headers, status)
|
| 223 |
+
headers = deps.timing()(headers, cache="miss", queued=acquired_at - queued_at,
|
| 224 |
+
upstream=headers_at - acquired_at)
|
| 225 |
+
declared_length = upstream.headers.get("Content-Length")
|
| 226 |
+
length = None
|
| 227 |
+
if declared_length is not None:
|
| 228 |
+
try:
|
| 229 |
+
length = int(declared_length)
|
| 230 |
+
except (TypeError, ValueError):
|
| 231 |
+
return JSONResponse({"error": "上游阅读文件长度无效"}, status_code=502)
|
| 232 |
+
if length < 0 or (max_bytes is not None and length > max_bytes):
|
| 233 |
+
return JSONResponse({"error": "阅读文件过大"}, status_code=413)
|
| 234 |
+
content_range = upstream.headers.get("Content-Range")
|
| 235 |
+
full_requested_range = False
|
| 236 |
+
if expected_sha256 is not None:
|
| 237 |
+
if status != 200 or length != expected_bytes:
|
| 238 |
+
return JSONResponse({'error': '阅读页图长度不匹配'}, status_code=502,
|
| 239 |
+
headers={'Cache-Control': 'no-store'})
|
| 240 |
+
if status == 206:
|
| 241 |
+
match = re.fullmatch(r"bytes\s+([0-9]{1,20})-([0-9]{1,20})/([0-9]{1,20})", str(content_range or ""))
|
| 242 |
+
if not match:
|
| 243 |
+
return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)
|
| 244 |
+
range_start, range_end, total_length = (int(value) for value in match.groups())
|
| 245 |
+
if (range_start > range_end or range_end >= total_length
|
| 246 |
+
or (length is not None and length != range_end - range_start + 1)):
|
| 247 |
+
return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)
|
| 248 |
+
if total_limit is not None and total_length > total_limit:
|
| 249 |
+
return JSONResponse({"error": "阅读文件过大"}, status_code=413)
|
| 250 |
+
if not range_header:
|
| 251 |
+
return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)
|
| 252 |
+
bounds = deps.range_bounds(range_header, total_length)
|
| 253 |
+
# A 206 may stop early. Forward that prefix but never cache it
|
| 254 |
+
# as the complete request; a wrong start would corrupt offsets.
|
| 255 |
+
if bounds is not None:
|
| 256 |
+
if range_start != bounds[0] or range_end > bounds[1]:
|
| 257 |
+
return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)
|
| 258 |
+
full_requested_range = (range_start, range_end) == bounds
|
| 259 |
+
elif re.fullmatch(r"bytes=[0-9]{0,20}-[0-9]{0,20}", range_header):
|
| 260 |
+
return JSONResponse({"error": "上游阅读文件范围无效"}, status_code=502)
|
| 261 |
+
elif status == 416:
|
| 262 |
+
match = re.fullmatch(r"bytes\s+\*/([0-9]{1,20})", str(content_range or ""))
|
| 263 |
+
if match and total_limit is not None and int(match.group(1)) > total_limit:
|
| 264 |
+
return JSONResponse({"error": "阅读文件过大"}, status_code=413)
|
| 265 |
+
if request.method == "HEAD" or status == 304:
|
| 266 |
+
return Response(status_code=status, headers=headers)
|
| 267 |
+
if status not in (200, 206, 416):
|
| 268 |
+
return JSONResponse({"error": f"上游阅读文件加载失败: HTTP {status}"}, status_code=status)
|
| 269 |
+
|
| 270 |
+
async def stream_reader_content():
|
| 271 |
+
total = 0
|
| 272 |
+
chunks: list[bytes] = []
|
| 273 |
+
checksum = hashlib.sha256() if expected_sha256 else None
|
| 274 |
+
tail = b''
|
| 275 |
+
cacheable = bool(
|
| 276 |
+
cache_policy_safe and range_key and status == 206 and full_requested_range and length is not None
|
| 277 |
+
and length <= deps.cache_max_item_bytes()
|
| 278 |
+
)
|
| 279 |
+
try:
|
| 280 |
+
async for chunk in upstream.content.iter_chunked(65536):
|
| 281 |
+
total += len(chunk)
|
| 282 |
+
if max_bytes is not None and total > max_bytes:
|
| 283 |
+
raise deps.limit_error()("阅读文件过大")
|
| 284 |
+
if cacheable:
|
| 285 |
+
chunks.append(chunk)
|
| 286 |
+
if checksum is not None:
|
| 287 |
+
checksum.update(chunk)
|
| 288 |
+
if expected_bytes is None or total > expected_bytes:
|
| 289 |
+
raise ValueError('reading image exceeds its pinned size')
|
| 290 |
+
# Stream previews while retaining the completion marker.
|
| 291 |
+
# Once the pinned size is reached, send the final chunk
|
| 292 |
+
# after verification as one piece. A one-byte final
|
| 293 |
+
# refinement can trigger another native image decode.
|
| 294 |
+
pending = tail + chunk
|
| 295 |
+
if total == expected_bytes:
|
| 296 |
+
tail = pending
|
| 297 |
+
elif len(pending) > 1:
|
| 298 |
+
yield pending[:-1]
|
| 299 |
+
tail = pending[-1:]
|
| 300 |
+
else:
|
| 301 |
+
tail = pending
|
| 302 |
+
else:
|
| 303 |
+
yield chunk
|
| 304 |
+
if checksum is not None:
|
| 305 |
+
if total != expected_bytes or checksum.hexdigest() != expected_sha256:
|
| 306 |
+
raise ValueError('reading image checksum mismatch')
|
| 307 |
+
yield tail
|
| 308 |
+
if cacheable and total == length:
|
| 309 |
+
payload = b"".join(chunks)
|
| 310 |
+
cache = deps.state().reader_range_cache
|
| 311 |
+
# cacheable implies a concrete key; retain the original admission decision.
|
| 312 |
+
cache_key = cast(RangeKey, range_key)
|
| 313 |
+
previous = cache.pop(cache_key, None)
|
| 314 |
+
if previous:
|
| 315 |
+
deps.state().reader_range_cache_bytes -= len(previous[1])
|
| 316 |
+
cache[cache_key] = (deps.clock(), payload, headers)
|
| 317 |
+
deps.state().reader_range_cache_bytes += len(payload)
|
| 318 |
+
while (deps.state().reader_range_cache_bytes > deps.cache_max_bytes()
|
| 319 |
+
or len(cache) > deps.cache_max_entries()):
|
| 320 |
+
_, (_, evicted, _) = cache.popitem(last=False)
|
| 321 |
+
deps.state().reader_range_cache_bytes -= len(evicted)
|
| 322 |
+
finally:
|
| 323 |
+
lease.close()
|
| 324 |
+
|
| 325 |
+
return lease.streaming_response(stream_reader_content(), status_code=status, headers=headers)
|
| 326 |
+
except Exception as exc:
|
| 327 |
+
print(f"阅读代理异常: {exc}")
|
| 328 |
+
return JSONResponse({"error": str(exc) or "上游阅读文件加载失败"}, status_code=502)
|
| 329 |
+
finally:
|
| 330 |
+
if not lease.transferred:
|
| 331 |
+
lease.close()
|
config/types/jsconfig.check.json
CHANGED
|
@@ -86,6 +86,9 @@
|
|
| 86 |
"../../static/reader/ui/reader-scroll-anchor.js",
|
| 87 |
"../../static/search/download-controller.js",
|
| 88 |
"../../static/search/reader-navigation.js",
|
|
|
|
|
|
|
|
|
|
| 89 |
"../../static/search/search-session.js",
|
| 90 |
"../../static/search/size-format.js",
|
| 91 |
"../../static/search/record-path.js",
|
|
|
|
| 86 |
"../../static/reader/ui/reader-scroll-anchor.js",
|
| 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",
|
| 93 |
"../../static/search/size-format.js",
|
| 94 |
"../../static/search/record-path.js",
|
config/types/jsconfig.search-exact.json
CHANGED
|
@@ -15,6 +15,9 @@
|
|
| 15 |
"../../typings/search-sidebar.d.ts",
|
| 16 |
"../../static/search/search-session.js",
|
| 17 |
"../../static/search/reader-navigation.js",
|
|
|
|
|
|
|
|
|
|
| 18 |
"../../static/search/download-controller.js",
|
| 19 |
"../../static/search/result-identity.js",
|
| 20 |
"../../static/search/folder-selection.js",
|
|
|
|
| 15 |
"../../typings/search-sidebar.d.ts",
|
| 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",
|
| 22 |
"../../static/search/result-identity.js",
|
| 23 |
"../../static/search/folder-selection.js",
|
config/types/jsconfig.strict.json
CHANGED
|
@@ -68,6 +68,9 @@
|
|
| 68 |
"../../static/reader/pdf/reader-pdf-text-store.mjs",
|
| 69 |
"../../static/search/search-session.js",
|
| 70 |
"../../static/search/reader-navigation.js",
|
|
|
|
|
|
|
|
|
|
| 71 |
"../../static/search/download-controller.js",
|
| 72 |
"../../static/search/size-format.js",
|
| 73 |
"../../static/search/record-path.js",
|
|
|
|
| 68 |
"../../static/reader/pdf/reader-pdf-text-store.mjs",
|
| 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",
|
| 75 |
"../../static/search/size-format.js",
|
| 76 |
"../../static/search/record-path.js",
|
eslint.config.mjs
CHANGED
|
@@ -20,7 +20,7 @@ export default [
|
|
| 20 |
globals: { ...globals.browser, ...globals.serviceworker, ...globals.worker,
|
| 21 |
module: "readonly", require: "readonly",
|
| 22 |
...Object.fromEntries(["VoiceOfMLReaderSecurity", "VoiceOfMLReader", "VoiceOfMLReaderResources",
|
| 23 |
-
"VoiceOfMLReaderStore", "VoiceOfMLReaderChapters", "VoiceOfMLReaderVirtual", "VoiceOfMLReaderNavigation",
|
| 24 |
"VoiceOfMLDownloadController", "VoiceOfMLSearchSession", "VoiceOfMLReaderRequests", "VoiceOfMLReaderRuntime",
|
| 25 |
"VoiceOfMLReaderAdapters", "VoiceOfMLReaderScroll", "DOMPurify", "marked"]
|
| 26 |
.map(name => [name, "readonly"])) }
|
|
|
|
| 20 |
globals: { ...globals.browser, ...globals.serviceworker, ...globals.worker,
|
| 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"])) }
|
pyrightconfig.strict.json
CHANGED
|
@@ -61,6 +61,13 @@
|
|
| 61 |
"backend/reader/bucket/application/resources.py",
|
| 62 |
"backend/reader/bucket/http/__init__.py",
|
| 63 |
"backend/reader/bucket/http/routes.py",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
"backend/app.py"
|
| 65 |
],
|
| 66 |
"pythonVersion": "3.11",
|
|
|
|
| 61 |
"backend/reader/bucket/application/resources.py",
|
| 62 |
"backend/reader/bucket/http/__init__.py",
|
| 63 |
"backend/reader/bucket/http/routes.py",
|
| 64 |
+
"backend/reader/document/__init__.py",
|
| 65 |
+
"backend/reader/document/application/__init__.py",
|
| 66 |
+
"backend/reader/document/application/ranges.py",
|
| 67 |
+
"backend/reader/document/domain/__init__.py",
|
| 68 |
+
"backend/reader/document/domain/policy.py",
|
| 69 |
+
"backend/reader/document/http/__init__.py",
|
| 70 |
+
"backend/reader/document/http/transport.py",
|
| 71 |
"backend/app.py"
|
| 72 |
],
|
| 73 |
"pythonVersion": "3.11",
|
scripts/build/check_reader_release.mjs
CHANGED
|
@@ -271,6 +271,7 @@ function crossCheck(githubRoot, hfRoot) {
|
|
| 271 |
"search/domain/search-window-page.js",
|
| 272 |
"search/presentation/sidebar-render.js",
|
| 273 |
"search/reader-navigation.js",
|
|
|
|
| 274 |
"reader.css",
|
| 275 |
"reader/core/reader-request-manager.js",
|
| 276 |
"reader/formats/reader-chapter-repository.js",
|
|
|
|
| 271 |
"search/domain/search-window-page.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 |
"reader.css",
|
| 276 |
"reader/core/reader-request-manager.js",
|
| 277 |
"reader/formats/reader-chapter-repository.js",
|
scripts/build/compose_app.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { pathToFileURL } from "node:url";
|
|
| 6 |
// Keep classic-script globals for the host; each dependency owns its own scope.
|
| 7 |
export const APP_DEPENDENCIES = Object.freeze([
|
| 8 |
"reader-resources.js", "reader/core/reader-contract.js", "search/reader-navigation.js",
|
|
|
|
| 9 |
"search/search-session.js", "search/download-controller.js", "search/size-format.js", "search/record-path.js",
|
| 10 |
"search/highlight.js", "search/response-cache.js", "search/file-types.js", "search/response-validation.js", "search/result-identity.js",
|
| 11 |
"search/input/domain/ownership.js", "search/input/application/controller.js",
|
|
|
|
| 6 |
// Keep classic-script globals for the host; each dependency owns its own scope.
|
| 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",
|
static/app.js
CHANGED
|
@@ -763,7 +763,7 @@ function saveSearchPosition() {
|
|
| 763 |
const view = displayedSearchView;
|
| 764 |
const target = view && getReturnPositionTarget(view.key);
|
| 765 |
if (target) return target;
|
| 766 |
-
if (!view || positionRestore ||
|
| 767 |
if (STATE.results !== view.results || (STATE.isLoading && view.key !== getSearchViewKey())) return searchPositions.get(view.key) || null;
|
| 768 |
const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);
|
| 769 |
if (!view.results[index]) return searchPositions.get(view.key) || null;
|
|
@@ -893,7 +893,7 @@ function tryRestoreSearchPosition(key, options = {}) {
|
|
| 893 |
for (const [page, data] of task.cachedPages || []) {
|
| 894 |
if (!task.ready.has(page) && data.generation === lookup.generation && data.total === total) task.ready.set(page, data);
|
| 895 |
}
|
| 896 |
-
if (task.preview && !
|
| 897 |
const latest = captureReaderReturnScroll(), record = STATE.results[latest.index];
|
| 898 |
const anchorId = getResultStableId(record);
|
| 899 |
if (anchorId && anchorId !== position.anchorId) {
|
|
@@ -1011,7 +1011,7 @@ async function fetchPositionPageWithRecovery(query, page, signal, anchorId, dema
|
|
| 1011 |
}
|
| 1012 |
|
| 1013 |
function resumeResultRecovery() {
|
| 1014 |
-
if (document.hidden || !navigator.onLine ||
|
| 1015 |
if (positionRestore?.failed && isRecoverableSearchError(positionRestore.error)) {
|
| 1016 |
tryRestoreSearchPosition(positionRestore.key);
|
| 1017 |
return;
|
|
@@ -1424,9 +1424,9 @@ function restoreSearchViewSnapshot(key, restoreScroll = true, preserveRestore =
|
|
| 1424 |
VSCROLL.heightCache = new Map(snapshot.heightCache || []);
|
| 1425 |
for (const [id, value] of snapshot.heightRecords || []) VSCROLL.heightCache.set(id, value);
|
| 1426 |
const restoredScroll = restoreScroll && snapshot.scroll ? { ...snapshot.scroll, route: location.href, viewKey: key } : null;
|
| 1427 |
-
|
| 1428 |
resetVirtualScrollState();
|
| 1429 |
-
|
| 1430 |
renderResults(false);
|
| 1431 |
updateStatusBar();
|
| 1432 |
updateLoadInfo();
|
|
@@ -2289,287 +2289,92 @@ function getReaderLink(rec, returnUrl = location.href, cacheMetadata = true) {
|
|
| 2289 |
return readerUrl;
|
| 2290 |
}
|
| 2291 |
|
| 2292 |
-
|
| 2293 |
-
|
| 2294 |
-
|
| 2295 |
-
|
| 2296 |
-
|
| 2297 |
-
|
| 2298 |
-
|
| 2299 |
-
|
| 2300 |
-
|
| 2301 |
-
|
| 2302 |
-
|
| 2303 |
-
|
| 2304 |
-
|
| 2305 |
-
|
| 2306 |
-
const
|
| 2307 |
-
|
| 2308 |
-
|
| 2309 |
-
|
| 2310 |
-
|
| 2311 |
-
|
| 2312 |
-
|
| 2313 |
-
|
| 2314 |
-
|
| 2315 |
-
const
|
| 2316 |
-
|
| 2317 |
-
|
| 2318 |
-
|
| 2319 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2320 |
});
|
| 2321 |
-
|
| 2322 |
-
|
| 2323 |
-
|
| 2324 |
-
let readerReturnRestoreActive = false;
|
| 2325 |
function captureReaderReturnScroll() {
|
| 2326 |
-
|
| 2327 |
-
const top = getResultScrollTop();
|
| 2328 |
-
let index = 0;
|
| 2329 |
-
let offset = top;
|
| 2330 |
-
if (STATE.results.length) {
|
| 2331 |
-
ensureHeightTree();
|
| 2332 |
-
index = findVirtualIndex(top);
|
| 2333 |
-
offset = top - getVirtualOffset(index);
|
| 2334 |
-
}
|
| 2335 |
-
const active = document.activeElement;
|
| 2336 |
-
const focus = active instanceof HTMLElement && active.id ? { id: active.id,
|
| 2337 |
-
start: active instanceof HTMLInputElement ? active.selectionStart : null,
|
| 2338 |
-
end: active instanceof HTMLInputElement ? active.selectionEnd : null,
|
| 2339 |
-
direction: active instanceof HTMLInputElement ? active.selectionDirection : null } : null;
|
| 2340 |
-
return { route: location.href, viewKey: getSearchViewKey(), top, index, offset, focus };
|
| 2341 |
}
|
| 2342 |
function readerSearchHandoffReady(saved) {
|
| 2343 |
-
|
| 2344 |
-
// may still be fetching adjacent pages. Keep that validation running.
|
| 2345 |
-
if (STATE.isLoading || !STATE._loadedPage || !STATE.results.length) return false;
|
| 2346 |
-
if (positionRestore && (!positionRestore.preview || positionRestore.key !== saved.viewKey)) return false;
|
| 2347 |
-
const index = Math.min(saved.index, Math.max(0, STATE.total - 1));
|
| 2348 |
-
return !!STATE.results[index];
|
| 2349 |
}
|
| 2350 |
-
|
| 2351 |
function restoreReaderSearchHandoff() {
|
| 2352 |
-
|
| 2353 |
-
try {
|
| 2354 |
-
const handoff = JSON.parse(sessionStorage.getItem("reader-navigation-restore") || "null");
|
| 2355 |
-
sessionStorage.removeItem("reader-navigation-restore");
|
| 2356 |
-
if (!handoff || handoff.returnUrl !== location.href) return;
|
| 2357 |
-
const current = /** @type {{readerUrl?: string; returnScroll?: ReturnType<typeof captureReaderReturnScroll>} | null} */ (readerNavigation.saved());
|
| 2358 |
-
if (!current || current.readerUrl !== handoff.readerUrl) return;
|
| 2359 |
-
const url = readerNavigation.parse(handoff.readerUrl);
|
| 2360 |
-
const token = url.searchParams.get("nav");
|
| 2361 |
-
if (!token || sessionStorage.getItem("reader-return:" + token) !== location.href) return;
|
| 2362 |
-
saved = current.returnScroll;
|
| 2363 |
-
if (!saved || saved.route !== location.href || saved.viewKey !== getSearchViewKey() ||
|
| 2364 |
-
!Number.isInteger(saved.index) || saved.index < 0 || !Number.isFinite(saved.offset) || !Number.isFinite(saved.top)) return;
|
| 2365 |
-
} catch (_) { return; }
|
| 2366 |
-
const route = location.href;
|
| 2367 |
-
let cancelled = false;
|
| 2368 |
-
const cancel = () => { cancelled = true; cleanup(); };
|
| 2369 |
-
const cleanup = () => {
|
| 2370 |
-
for (const type of ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"])
|
| 2371 |
-
document.removeEventListener(type, cancel, true);
|
| 2372 |
-
};
|
| 2373 |
-
for (const type of ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"])
|
| 2374 |
-
document.addEventListener(type, cancel, true);
|
| 2375 |
-
const routeRevision = routeRenderId;
|
| 2376 |
-
const deadline = Date.now() + 30000;
|
| 2377 |
-
const restore = () => {
|
| 2378 |
-
if (cancelled || routeRevision !== routeRenderId || location.href !== route || saved.viewKey !== getSearchViewKey() || Date.now() > deadline) {
|
| 2379 |
-
cleanup(); return;
|
| 2380 |
-
}
|
| 2381 |
-
if (!readerSearchHandoffReady(saved)) { requestAnimationFrame(restore); return; }
|
| 2382 |
-
cleanup();
|
| 2383 |
-
readerReturnScrollState = saved;
|
| 2384 |
-
restoreReaderReturnScroll(false, true);
|
| 2385 |
-
const focus = saved.focus;
|
| 2386 |
-
const element = focus && document.getElementById(focus.id);
|
| 2387 |
-
if (!element || (document.activeElement !== document.body && document.activeElement !== element)) return;
|
| 2388 |
-
element.focus({ preventScroll: true });
|
| 2389 |
-
if (element instanceof HTMLInputElement && Number.isInteger(focus.start) && Number.isInteger(focus.end) &&
|
| 2390 |
-
["forward", "backward", "none"].includes(focus.direction)) {
|
| 2391 |
-
try { element.setSelectionRange(focus.start, focus.end, focus.direction); } catch (_) {}
|
| 2392 |
-
}
|
| 2393 |
-
};
|
| 2394 |
-
requestAnimationFrame(restore);
|
| 2395 |
}
|
| 2396 |
-
|
| 2397 |
function restoreReaderReturnScroll(windowRendered = false, restoreTop = false) {
|
| 2398 |
-
|
| 2399 |
-
if (!saved) return;
|
| 2400 |
-
if (saved.route && saved.route !== location.href) { readerReturnScrollState = null; return; }
|
| 2401 |
-
if (saved.viewKey && saved.viewKey !== getSearchViewKey()) { readerReturnScrollState = null; return; }
|
| 2402 |
-
const generation = ++readerReturnRestoreGeneration;
|
| 2403 |
-
let attempts = 0;
|
| 2404 |
-
const restore = () => {
|
| 2405 |
-
if (generation !== readerReturnRestoreGeneration || saved.viewKey !== getSearchViewKey() || saved.route !== location.href) return;
|
| 2406 |
-
if (!DOM.resultsContainer || !STATE.results.length) {
|
| 2407 |
-
if (++attempts < 20) requestAnimationFrame(restore);
|
| 2408 |
-
return;
|
| 2409 |
-
}
|
| 2410 |
-
ensureHeightTree();
|
| 2411 |
-
const index = Math.min(saved.index, STATE.results.length - 1);
|
| 2412 |
-
const target = Math.max(0, restoreTop ? saved.top : getVirtualOffset(index) + saved.offset);
|
| 2413 |
-
const max = Math.max(0, getVirtualTotalHeight() - DOM.resultsContainer.clientHeight);
|
| 2414 |
-
readerReturnRestoreActive = true;
|
| 2415 |
-
setResultScrollTop(Math.min(target, max));
|
| 2416 |
-
if (!windowRendered) {
|
| 2417 |
-
VSCROLL.renderStart = -1;
|
| 2418 |
-
VSCROLL.renderEnd = -1;
|
| 2419 |
-
}
|
| 2420 |
-
renderVisible();
|
| 2421 |
-
windowRendered = false;
|
| 2422 |
-
updateScrollTrack();
|
| 2423 |
-
readerReturnRestoreActive = false;
|
| 2424 |
-
if (++attempts < 4 && Math.abs(getResultScrollTop() - target) > 1) requestAnimationFrame(restore);
|
| 2425 |
-
else readerReturnScrollState = null;
|
| 2426 |
-
};
|
| 2427 |
-
restore();
|
| 2428 |
-
if (readerReturnScrollState === saved) requestAnimationFrame(() => requestAnimationFrame(restore));
|
| 2429 |
}
|
| 2430 |
function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {
|
| 2431 |
-
|
| 2432 |
-
readerOverlayRevision++;
|
| 2433 |
-
readerClosing = false;
|
| 2434 |
-
readerUiState = "base";
|
| 2435 |
-
readerOverlay = null;
|
| 2436 |
-
const returnFocus = readerNavigation.unmount();
|
| 2437 |
-
if (readerOverlay) return true;
|
| 2438 |
-
if (restoreScroll) {
|
| 2439 |
-
const saved = readerReturnScrollState;
|
| 2440 |
-
const snapshot = readerReturnSnapshot;
|
| 2441 |
-
const source = snapshot && searchSnapshotSources.get(snapshot);
|
| 2442 |
-
const currentView = displayedSearchView;
|
| 2443 |
-
const sameView = snapshot && source && saved?.viewKey === getSearchViewKey() &&
|
| 2444 |
-
currentView?.key === saved.viewKey && currentView.revision === source.revision &&
|
| 2445 |
-
searchViewSnapshots.get(saved.viewKey) === snapshot;
|
| 2446 |
-
const changed = sameView && (STATE.results.length !== snapshot.results.length || STATE._loadedPage !== snapshot.loadedPage);
|
| 2447 |
-
if (changed) {
|
| 2448 |
-
readerReturnScrollState = null;
|
| 2449 |
-
restoreSearchViewSnapshot(saved.viewKey, false);
|
| 2450 |
-
readerReturnScrollState = { ...saved, route: location.href };
|
| 2451 |
-
}
|
| 2452 |
-
restoreReaderReturnScroll();
|
| 2453 |
-
}
|
| 2454 |
-
if (restoreScroll) readerReturnSnapshot = null;
|
| 2455 |
-
if (restoreFocus && returnFocus && returnFocus.isConnected) returnFocus.focus();
|
| 2456 |
-
return true;
|
| 2457 |
}
|
| 2458 |
-
|
| 2459 |
function openReaderOverlay(url, addHistory = true) {
|
| 2460 |
-
|
| 2461 |
-
if (addHistory && !readerReturnScrollState) {
|
| 2462 |
-
readerReturnScrollState = captureReaderReturnScroll();
|
| 2463 |
-
readerReturnSnapshot = saveSearchViewSnapshot(readerReturnScrollState?.viewKey || getSearchViewKey());
|
| 2464 |
-
}
|
| 2465 |
-
readerOverlay = readerNavigation.mount(url);
|
| 2466 |
-
readerUiState = "base";
|
| 2467 |
-
readerClosing = false;
|
| 2468 |
-
if (addHistory) readerNavigation.remember(url, readerReturnScrollState);
|
| 2469 |
}
|
| 2470 |
-
|
| 2471 |
function reconcileSearchDestination() {
|
| 2472 |
-
|
| 2473 |
-
// Only a search destination can be reconciled with the underlying view.
|
| 2474 |
-
if (location.pathname.split("/").filter(Boolean).length > 1 || history.state?.voiceReaderOverlay) return;
|
| 2475 |
-
const changed = location.pathname + location.search !== appliedSearchRoute;
|
| 2476 |
-
const overlay = readerOverlay;
|
| 2477 |
-
// Apply the destination before disposal; preserve an unchanged search owner.
|
| 2478 |
-
if (changed) ROUTER.apply(!!overlay);
|
| 2479 |
-
if (readerOverlay === overlay) closeReaderOverlay();
|
| 2480 |
}
|
| 2481 |
-
|
| 2482 |
function restoreReaderOverlay(state) {
|
| 2483 |
-
|
| 2484 |
-
reconcileSearchDestination();
|
| 2485 |
-
return;
|
| 2486 |
-
}
|
| 2487 |
-
try {
|
| 2488 |
-
const url = readerNavigation.parse(state.readerUrl);
|
| 2489 |
-
const revision = readerOverlayRevision + (readerOverlay ? 1 : 0);
|
| 2490 |
-
closeReaderOverlay(false, false);
|
| 2491 |
-
if (readerOverlayRevision !== revision) return;
|
| 2492 |
-
openReaderOverlay(url, false);
|
| 2493 |
-
} catch (_) {}
|
| 2494 |
}
|
| 2495 |
-
|
| 2496 |
function handleReaderMessage(event) {
|
| 2497 |
-
|
| 2498 |
-
const message = event.data || {};
|
| 2499 |
-
if (message.type === "voice-reader-close") {
|
| 2500 |
-
if (readerClosing) return;
|
| 2501 |
-
readerNavigation.persistProgress(message.progress);
|
| 2502 |
-
readerClosing = true;
|
| 2503 |
-
readerUiState = "base";
|
| 2504 |
-
readerNavigation.dismiss();
|
| 2505 |
-
let returnUrl = "/";
|
| 2506 |
-
try {
|
| 2507 |
-
const target = new URL(new URL(readerOverlay.src, location.origin).searchParams.get("return") || "/", location.origin);
|
| 2508 |
-
if (target.origin === location.origin) returnUrl = target.href;
|
| 2509 |
-
} catch (_) {}
|
| 2510 |
-
// Leave directly when the current entry is not this Reader's own overlay
|
| 2511 |
-
// entry: history.back() would otherwise leave the overlay open or reach an
|
| 2512 |
-
// unrelated page, and readerClosing would ignore every later Back tap.
|
| 2513 |
-
if (!history.state?.voiceReaderOverlay) {
|
| 2514 |
-
history.replaceState(history.state, "", returnUrl);
|
| 2515 |
-
reconcileSearchDestination();
|
| 2516 |
-
return;
|
| 2517 |
-
}
|
| 2518 |
-
const overlay = readerOverlay;
|
| 2519 |
-
history.back();
|
| 2520 |
-
// Back may still arrive: keep its Reader entry intact for Forward.
|
| 2521 |
-
setTimeout(() => {
|
| 2522 |
-
if (!readerClosing || readerOverlay !== overlay) return;
|
| 2523 |
-
readerNavigation.showCloseRecovery(returnUrl);
|
| 2524 |
-
}, 1000);
|
| 2525 |
-
return;
|
| 2526 |
-
}
|
| 2527 |
-
if (message.type === "voice-reader-ui-state") {
|
| 2528 |
-
if (readerClosing) return;
|
| 2529 |
-
if (["base", "panel", "full-search"].includes(message.state)) readerUiState = message.state;
|
| 2530 |
-
return;
|
| 2531 |
-
}
|
| 2532 |
-
if (message.type === "voice-reader-theme") {
|
| 2533 |
-
if (message.theme !== "dark" && message.theme !== "light") return;
|
| 2534 |
-
STATE.isDark = message.theme === "dark";
|
| 2535 |
-
applyTheme();
|
| 2536 |
-
writeSearchPreference("theme", message.theme);
|
| 2537 |
-
return;
|
| 2538 |
-
}
|
| 2539 |
-
if (message.type === "voice-reader-open") {
|
| 2540 |
-
try {
|
| 2541 |
-
readerOverlay = readerNavigation.replace(message.url, readerReturnScrollState);
|
| 2542 |
-
} catch (_) {}
|
| 2543 |
-
return;
|
| 2544 |
-
}
|
| 2545 |
-
if (message.type !== "voice-reader-navigate") return;
|
| 2546 |
-
try {
|
| 2547 |
-
const target = new URL(message.url, location.origin);
|
| 2548 |
-
if (target.origin !== location.origin || target.pathname.split("/").filter(Boolean).length !== 1) return;
|
| 2549 |
-
const mergedTarget = readerNavigation.mergeSearchParams(target, buildSearchURLParams(), {
|
| 2550 |
-
keys: READER_RETURN_SEARCH_KEYS
|
| 2551 |
-
});
|
| 2552 |
-
history.replaceState(null, "", mergedTarget.href);
|
| 2553 |
-
reconcileSearchDestination();
|
| 2554 |
-
} catch (_) {}
|
| 2555 |
}
|
| 2556 |
-
|
| 2557 |
function navigateToReader(rawUrl, returnUrl) {
|
| 2558 |
-
|
| 2559 |
-
try { target = readerNavigation.parse(syncReaderFolderFilter(rawUrl)); }
|
| 2560 |
-
catch (_) { return false; }
|
| 2561 |
-
const open = () => {
|
| 2562 |
-
const url = readerNavigation.prepare(target.href, returnUrl || location.href);
|
| 2563 |
-
openReaderOverlay(url);
|
| 2564 |
-
};
|
| 2565 |
-
if (STATE.isMobile && (STATE.leftSidebarOpen || STATE.rightSidebarOpen)) {
|
| 2566 |
-
STATE.leftSidebarOpen = false;
|
| 2567 |
-
STATE.rightSidebarOpen = false;
|
| 2568 |
-
updateSidebarVisibility();
|
| 2569 |
-
syncStateToURL(true);
|
| 2570 |
-
open();
|
| 2571 |
-
} else open();
|
| 2572 |
-
return true;
|
| 2573 |
}
|
| 2574 |
|
| 2575 |
const warmedReaderAssets = new Set();
|
|
@@ -2972,7 +2777,7 @@ const ROUTER = {
|
|
| 2972 |
if (!sameSearchView) {
|
| 2973 |
if (routeInitialized) searchInputController.invalidateVisit();
|
| 2974 |
cancelPendingSearchControls();
|
| 2975 |
-
|
| 2976 |
if (!cancelActiveSearch()) return;
|
| 2977 |
}
|
| 2978 |
const owner = searchId;
|
|
@@ -3032,7 +2837,7 @@ const ROUTER = {
|
|
| 3032 |
};
|
| 3033 |
|
| 3034 |
function syncStateToURL(replace = true) {
|
| 3035 |
-
if (
|
| 3036 |
const params = buildSearchURLParams();
|
| 3037 |
if (STATE.mode === "global") {
|
| 3038 |
STATE.filterRepos.forEach(r => {
|
|
@@ -3467,8 +3272,8 @@ function renderResults(animate = false) {
|
|
| 3467 |
VSCROLL.renderStart = 0;
|
| 3468 |
VSCROLL.renderEnd = 0;
|
| 3469 |
pendingResultEntrance = animate;
|
| 3470 |
-
if (
|
| 3471 |
-
setResultScrollTop(getVirtualOffset(
|
| 3472 |
restoreReaderReturnScroll(true);
|
| 3473 |
} else renderVisible();
|
| 3474 |
}
|
|
@@ -4586,7 +4391,7 @@ function readPagingView() {
|
|
| 4586 |
generation: searchRequestId, loadedPage: STATE._loadedPage, page: STATE.page,
|
| 4587 |
resultCount: STATE.results.length, hasMore: STATE.hasMore, loading: STATE.isLoading,
|
| 4588 |
suspended: !!snapshotCloneTask || !!positionRestore,
|
| 4589 |
-
inactive: document.hidden || !!
|
| 4590 |
scrollTop: getResultScrollTop(), loadedHeight: getVirtualTotalHeight(),
|
| 4591 |
viewportHeight: DOM.resultsContainer ? DOM.resultsContainer.clientHeight : 0,
|
| 4592 |
appendScrollTop: STATE._pagingAppendScrollTop
|
|
@@ -4692,7 +4497,7 @@ function setupInfiniteScroll() {
|
|
| 4692 |
DOM.resultsContainer.addEventListener("scrollend", () => scheduleBottomLoad(), { passive: true });
|
| 4693 |
DOM.resultsContainer.addEventListener("scroll", () => {
|
| 4694 |
updateCurrentResultPosition();
|
| 4695 |
-
|
| 4696 |
if (!VSCROLL.isDraggingThumb) ensureVirtualViewportCovered();
|
| 4697 |
scheduleVirtualRender(true);
|
| 4698 |
}, { passive: true });
|
|
@@ -4856,7 +4661,7 @@ function applyTheme() {
|
|
| 4856 |
DOM.themeBtn.setAttribute('aria-label', STATE.isDark ? '切换到浅色主题' : '切换到深色主题');
|
| 4857 |
if (STATE.isDark) { document.body.classList.remove("light"); DOM.themeIconLight.style.display = "none"; DOM.themeIconDark.style.display = ""; }
|
| 4858 |
else { document.body.classList.add("light"); DOM.themeIconLight.style.display = ""; DOM.themeIconDark.style.display = "none"; }
|
| 4859 |
-
if (
|
| 4860 |
}
|
| 4861 |
|
| 4862 |
function toggleMobile() { STATE.isMobile = !STATE.isMobile; applyMobileMode(); writeSearchPreference("mobileMode", STATE.isMobile ? "mobile" : "desktop"); }
|
|
@@ -4960,7 +4765,7 @@ function setupKeyboard() {
|
|
| 4960 |
DOM.resultsContainer.focus({ preventScroll: true });
|
| 4961 |
});
|
| 4962 |
document.addEventListener("keydown", (e) => {
|
| 4963 |
-
if (e.defaultPrevented || e.isComposing || searchComposing || e.keyCode === 229 ||
|
| 4964 |
const target = e.target instanceof Element ? e.target : document.activeElement;
|
| 4965 |
if (e.key === 'Escape' && target.closest('.sidebar')) {
|
| 4966 |
e.preventDefault();
|
|
|
|
| 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 searchPositions.get(view.key) || null;
|
| 768 |
const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);
|
| 769 |
if (!view.results[index]) return searchPositions.get(view.key) || null;
|
|
|
|
| 893 |
for (const [page, data] of task.cachedPages || []) {
|
| 894 |
if (!task.ready.has(page) && data.generation === lookup.generation && data.total === total) task.ready.set(page, data);
|
| 895 |
}
|
| 896 |
+
if (task.preview && !readerHost.overlay) {
|
| 897 |
const latest = captureReaderReturnScroll(), record = STATE.results[latest.index];
|
| 898 |
const anchorId = getResultStableId(record);
|
| 899 |
if (anchorId && anchorId !== position.anchorId) {
|
|
|
|
| 1011 |
}
|
| 1012 |
|
| 1013 |
function resumeResultRecovery() {
|
| 1014 |
+
if (document.hidden || !navigator.onLine || readerHost.overlay) return;
|
| 1015 |
if (positionRestore?.failed && isRecoverableSearchError(positionRestore.error)) {
|
| 1016 |
tryRestoreSearchPosition(positionRestore.key);
|
| 1017 |
return;
|
|
|
|
| 1424 |
VSCROLL.heightCache = new Map(snapshot.heightCache || []);
|
| 1425 |
for (const [id, value] of snapshot.heightRecords || []) VSCROLL.heightCache.set(id, value);
|
| 1426 |
const restoredScroll = restoreScroll && snapshot.scroll ? { ...snapshot.scroll, route: location.href, viewKey: key } : null;
|
| 1427 |
+
readerReturnPosition.setScroll(null);
|
| 1428 |
resetVirtualScrollState();
|
| 1429 |
+
readerReturnPosition.setScroll(restoredScroll);
|
| 1430 |
renderResults(false);
|
| 1431 |
updateStatusBar();
|
| 1432 |
updateLoadInfo();
|
|
|
|
| 2289 |
return readerUrl;
|
| 2290 |
}
|
| 2291 |
|
| 2292 |
+
// Reader host owns overlay and return-position state. Effects resolve live host hooks.
|
| 2293 |
+
const readerReturnPosition = VoiceOfMLReaderReturn.create({
|
| 2294 |
+
readView: () => ({ hasContainer: !!DOM.resultsContainer, containerHeight: DOM.resultsContainer?.clientHeight || 0,
|
| 2295 |
+
resultCount: STATE.results.length, total: STATE.total, loading: STATE.isLoading, loadedPage: STATE._loadedPage,
|
| 2296 |
+
positionRestore: positionRestore && { preview: positionRestore.preview, key: positionRestore.key }, routeRevision: routeRenderId }),
|
| 2297 |
+
hasResult: index => !!STATE.results[index], getViewKey: () => getSearchViewKey(),
|
| 2298 |
+
getTop: () => getResultScrollTop(), setTop: top => setResultScrollTop(top),
|
| 2299 |
+
ensureHeights: () => ensureHeightTree(), findIndex: top => findVirtualIndex(top),
|
| 2300 |
+
getOffset: index => getVirtualOffset(index), getTotalHeight: () => getVirtualTotalHeight(),
|
| 2301 |
+
invalidateWindow: () => { VSCROLL.renderStart = -1; VSCROLL.renderEnd = -1; },
|
| 2302 |
+
renderVisible: () => renderVisible(), updateTrack: () => updateScrollTrack(),
|
| 2303 |
+
handoffReady: saved => readerSearchHandoffReady(saved),
|
| 2304 |
+
restoreScroll: (rendered, top) => restoreReaderReturnScroll(rendered, top)
|
| 2305 |
+
});
|
| 2306 |
+
const readerHost = VoiceOfMLReaderHost.create({
|
| 2307 |
+
hashRoute: false, position: readerReturnPosition,
|
| 2308 |
+
createNavigation: options => VoiceOfMLReaderNavigation.createNavigation("/static/reader.html", options),
|
| 2309 |
+
buildParams: () => buildSearchURLParams(),
|
| 2310 |
+
readQuery: () => DOM.searchInput ? DOM.searchInput.value : STATE.query,
|
| 2311 |
+
currentParams: () => buildSearchURLParams(),
|
| 2312 |
+
getViewKey: () => getSearchViewKey(), captureScroll: () => captureReaderReturnScroll(),
|
| 2313 |
+
restoreScroll: () => restoreReaderReturnScroll(), saveSnapshot: key => saveSearchViewSnapshot(key),
|
| 2314 |
+
snapshotChanged: (snapshot, key) => {
|
| 2315 |
+
const source = searchSnapshotSources.get(snapshot), current = displayedSearchView;
|
| 2316 |
+
return key === getSearchViewKey() && !!source && !!current && current.key === key &&
|
| 2317 |
+
current.revision === source.revision && searchViewSnapshots.get(key) === snapshot &&
|
| 2318 |
+
(STATE.results.length !== snapshot.results.length || STATE._loadedPage !== snapshot.loadedPage);
|
| 2319 |
+
},
|
| 2320 |
+
restoreSnapshot: key => restoreSearchViewSnapshot(key, false),
|
| 2321 |
+
routeChanged: () => location.pathname + location.search !== appliedSearchRoute,
|
| 2322 |
+
applyRoute: preserve => ROUTER.apply(preserve),
|
| 2323 |
+
closeMobileSidebars: () => {
|
| 2324 |
+
if (STATE.isMobile && (STATE.leftSidebarOpen || STATE.rightSidebarOpen)) {
|
| 2325 |
+
STATE.leftSidebarOpen = false;
|
| 2326 |
+
STATE.rightSidebarOpen = false;
|
| 2327 |
+
updateSidebarVisibility();
|
| 2328 |
+
syncStateToURL(true);
|
| 2329 |
+
}
|
| 2330 |
+
},
|
| 2331 |
+
applyTheme: theme => { STATE.isDark = theme === "dark"; applyTheme(); writeSearchPreference("theme", theme); },
|
| 2332 |
+
navigate: url => navigateToReader(url), handleMessage: event => handleReaderMessage(event),
|
| 2333 |
+
syncFolder: url => syncReaderFolderFilter(url), normalizeReturn: url => url,
|
| 2334 |
+
openOverlay: (url, addHistory) => openReaderOverlay(url, addHistory),
|
| 2335 |
+
closeOverlay: (focus, scroll) => closeReaderOverlay(focus, scroll), reconcile: () => reconcileSearchDestination()
|
| 2336 |
+
});
|
| 2337 |
+
const readerNavigation = readerHost.navigation;
|
| 2338 |
+
const READER_RETURN_SEARCH_KEYS = readerHost.keys;
|
| 2339 |
+
// Read-only compatibility projections for existing browser diagnostics.
|
| 2340 |
+
Object.defineProperties(window, {
|
| 2341 |
+
readerOverlay: { get: () => readerHost.overlay },
|
| 2342 |
+
readerClosing: { get: () => readerHost.closing },
|
| 2343 |
+
readerUiState: { get: () => readerHost.uiState },
|
| 2344 |
+
readerReturnSnapshot: { get: () => readerHost.returnSnapshot }
|
| 2345 |
});
|
| 2346 |
+
function syncReaderFolderFilter(rawUrl) {
|
| 2347 |
+
return readerHost.syncReaderFolderFilter(rawUrl);
|
| 2348 |
+
}
|
|
|
|
| 2349 |
function captureReaderReturnScroll() {
|
| 2350 |
+
return readerReturnPosition.capture();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2351 |
}
|
| 2352 |
function readerSearchHandoffReady(saved) {
|
| 2353 |
+
return readerReturnPosition.ready(saved);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2354 |
}
|
|
|
|
| 2355 |
function restoreReaderSearchHandoff() {
|
| 2356 |
+
readerReturnPosition.restoreHandoff(readerNavigation);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2357 |
}
|
|
|
|
| 2358 |
function restoreReaderReturnScroll(windowRendered = false, restoreTop = false) {
|
| 2359 |
+
readerReturnPosition.restore(windowRendered, restoreTop);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2360 |
}
|
| 2361 |
function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {
|
| 2362 |
+
return readerHost.closeReaderOverlay(restoreFocus, restoreScroll);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2363 |
}
|
|
|
|
| 2364 |
function openReaderOverlay(url, addHistory = true) {
|
| 2365 |
+
readerHost.openReaderOverlay(url, addHistory);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2366 |
}
|
|
|
|
| 2367 |
function reconcileSearchDestination() {
|
| 2368 |
+
readerHost.reconcileSearchDestination();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2369 |
}
|
|
|
|
| 2370 |
function restoreReaderOverlay(state) {
|
| 2371 |
+
readerHost.restoreReaderOverlay(state);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2372 |
}
|
|
|
|
| 2373 |
function handleReaderMessage(event) {
|
| 2374 |
+
readerHost.handleReaderMessage(event);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2375 |
}
|
|
|
|
| 2376 |
function navigateToReader(rawUrl, returnUrl) {
|
| 2377 |
+
return readerHost.navigateToReader(rawUrl, returnUrl);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2378 |
}
|
| 2379 |
|
| 2380 |
const warmedReaderAssets = new Set();
|
|
|
|
| 2777 |
if (!sameSearchView) {
|
| 2778 |
if (routeInitialized) searchInputController.invalidateVisit();
|
| 2779 |
cancelPendingSearchControls();
|
| 2780 |
+
readerReturnPosition.invalidate();
|
| 2781 |
if (!cancelActiveSearch()) return;
|
| 2782 |
}
|
| 2783 |
const owner = searchId;
|
|
|
|
| 2837 |
};
|
| 2838 |
|
| 2839 |
function syncStateToURL(replace = true) {
|
| 2840 |
+
if (readerHost.overlay) return;
|
| 2841 |
const params = buildSearchURLParams();
|
| 2842 |
if (STATE.mode === "global") {
|
| 2843 |
STATE.filterRepos.forEach(r => {
|
|
|
|
| 3272 |
VSCROLL.renderStart = 0;
|
| 3273 |
VSCROLL.renderEnd = 0;
|
| 3274 |
pendingResultEntrance = animate;
|
| 3275 |
+
if (readerReturnPosition.scroll && !readerHost.overlay) {
|
| 3276 |
+
setResultScrollTop(getVirtualOffset(readerReturnPosition.scroll.index) + readerReturnPosition.scroll.offset, true);
|
| 3277 |
restoreReaderReturnScroll(true);
|
| 3278 |
} else renderVisible();
|
| 3279 |
}
|
|
|
|
| 4391 |
generation: searchRequestId, loadedPage: STATE._loadedPage, page: STATE.page,
|
| 4392 |
resultCount: STATE.results.length, hasMore: STATE.hasMore, loading: STATE.isLoading,
|
| 4393 |
suspended: !!snapshotCloneTask || !!positionRestore,
|
| 4394 |
+
inactive: document.hidden || !!readerHost.overlay, dragging: VSCROLL.isDraggingThumb,
|
| 4395 |
scrollTop: getResultScrollTop(), loadedHeight: getVirtualTotalHeight(),
|
| 4396 |
viewportHeight: DOM.resultsContainer ? DOM.resultsContainer.clientHeight : 0,
|
| 4397 |
appendScrollTop: STATE._pagingAppendScrollTop
|
|
|
|
| 4497 |
DOM.resultsContainer.addEventListener("scrollend", () => scheduleBottomLoad(), { passive: true });
|
| 4498 |
DOM.resultsContainer.addEventListener("scroll", () => {
|
| 4499 |
updateCurrentResultPosition();
|
| 4500 |
+
readerReturnPosition.cancelOnScroll();
|
| 4501 |
if (!VSCROLL.isDraggingThumb) ensureVirtualViewportCovered();
|
| 4502 |
scheduleVirtualRender(true);
|
| 4503 |
}, { passive: true });
|
|
|
|
| 4661 |
DOM.themeBtn.setAttribute('aria-label', STATE.isDark ? '切换到浅色主题' : '切换到深色主题');
|
| 4662 |
if (STATE.isDark) { document.body.classList.remove("light"); DOM.themeIconLight.style.display = "none"; DOM.themeIconDark.style.display = ""; }
|
| 4663 |
else { document.body.classList.add("light"); DOM.themeIconLight.style.display = ""; DOM.themeIconDark.style.display = "none"; }
|
| 4664 |
+
if (readerHost.overlay && readerHost.overlay.contentWindow) readerHost.overlay.contentWindow.postMessage({ type: "voice-reader-theme-state", theme: STATE.isDark ? "dark" : "light" }, location.origin);
|
| 4665 |
}
|
| 4666 |
|
| 4667 |
function toggleMobile() { STATE.isMobile = !STATE.isMobile; applyMobileMode(); writeSearchPreference("mobileMode", STATE.isMobile ? "mobile" : "desktop"); }
|
|
|
|
| 4765 |
DOM.resultsContainer.focus({ preventScroll: true });
|
| 4766 |
});
|
| 4767 |
document.addEventListener("keydown", (e) => {
|
| 4768 |
+
if (e.defaultPrevented || e.isComposing || searchComposing || e.keyCode === 229 || readerHost.overlay) return;
|
| 4769 |
const target = e.target instanceof Element ? e.target : document.activeElement;
|
| 4770 |
if (e.key === 'Escape' && target.closest('.sidebar')) {
|
| 4771 |
e.preventDefault();
|
static/index.html
CHANGED
|
@@ -338,6 +338,8 @@ if ("serviceWorker" in navigator) {
|
|
| 338 |
<script src="/static/reader-resources.js"></script>
|
| 339 |
<script src="/static/reader/core/reader-contract.js"></script>
|
| 340 |
<script src="/static/search/reader-navigation.js"></script>
|
|
|
|
|
|
|
| 341 |
<script src="/static/search/search-session.js"></script>
|
| 342 |
<script src="/static/search/download-controller.js"></script>
|
| 343 |
<script src="/static/search/size-format.js"></script>
|
|
|
|
| 338 |
<script src="/static/reader-resources.js"></script>
|
| 339 |
<script src="/static/reader/core/reader-contract.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/search-session.js"></script>
|
| 344 |
<script src="/static/search/download-controller.js"></script>
|
| 345 |
<script src="/static/search/size-format.js"></script>
|
static/reader-resources.js
CHANGED
|
@@ -127,6 +127,7 @@
|
|
| 127 |
"reader/search/reader-chapter-search.mjs",
|
| 128 |
"reader/core/reader-contract.js",
|
| 129 |
"search/reader-navigation.js",
|
|
|
|
| 130 |
"reader/core/reader-store.js",
|
| 131 |
"reader/core/reader-request-manager.js",
|
| 132 |
"reader/formats/reader-chapter-repository.js",
|
|
|
|
| 127 |
"reader/search/reader-chapter-search.mjs",
|
| 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",
|
static/search/reader-host/application/host.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Coordinates the search/Reader handoff; reader-navigation owns iframe/history mechanics.
|
| 2 |
+
(function () {
|
| 3 |
+
/** @param {ReaderHostDependencies} deps */
|
| 4 |
+
function create(deps) {
|
| 5 |
+
const position = deps.position;
|
| 6 |
+
/** @type {HTMLIFrameElement | null} */
|
| 7 |
+
let overlay = null;
|
| 8 |
+
let revision = 0, closing = false, uiState = "base";
|
| 9 |
+
/** @type {ReaderHostSnapshot | null} */
|
| 10 |
+
let snapshot = null;
|
| 11 |
+
const keys = Object.freeze([
|
| 12 |
+
"q", "min_size", "max_size", "ext", "history", "mirror", "sort",
|
| 13 |
+
"search_folders", "exact", ...(deps.hashRoute ? ["local"] : []), "sidebar", "filters", "wide"
|
| 14 |
+
]);
|
| 15 |
+
const navigation = deps.createNavigation({
|
| 16 |
+
resume: url => deps.navigate(url),
|
| 17 |
+
close: () => { if (overlay) deps.handleMessage({ origin: location.origin,
|
| 18 |
+
source: overlay.contentWindow, data: { type: "voice-reader-close" } }); }
|
| 19 |
+
});
|
| 20 |
+
function currentReaderSearchParams() {
|
| 21 |
+
const params = deps.buildParams();
|
| 22 |
+
if (deps.hashRoute) {
|
| 23 |
+
const query = deps.readQuery().trim();
|
| 24 |
+
if (query) params.set("q", query);
|
| 25 |
+
}
|
| 26 |
+
return params;
|
| 27 |
+
}
|
| 28 |
+
/** @param {string} rawUrl */
|
| 29 |
+
function normalizeReaderReturnUrl(rawUrl) {
|
| 30 |
+
if (!deps.hashRoute) return rawUrl;
|
| 31 |
+
try {
|
| 32 |
+
const target = new URL(rawUrl || "/search/", location.origin);
|
| 33 |
+
if (target.origin === location.origin && target.pathname === "/") return new URL("/search/", location.origin).href;
|
| 34 |
+
return target.href;
|
| 35 |
+
} catch (_) { return new URL("/search/", location.origin).href; }
|
| 36 |
+
}
|
| 37 |
+
/** @param {URL} target */
|
| 38 |
+
function merge(target) {
|
| 39 |
+
return navigation.mergeSearchParams(target, deps.currentParams(), { hashRoute: deps.hashRoute, keys });
|
| 40 |
+
}
|
| 41 |
+
/** @param {string} rawUrl */
|
| 42 |
+
function syncReaderFolderFilter(rawUrl) {
|
| 43 |
+
try {
|
| 44 |
+
const readerUrl = new URL(rawUrl, location.origin);
|
| 45 |
+
const raw = readerUrl.searchParams.get("folder_url");
|
| 46 |
+
if (!raw) return readerUrl.href;
|
| 47 |
+
readerUrl.searchParams.set("folder_url", merge(new URL(raw, location.origin)).href);
|
| 48 |
+
return readerUrl.href;
|
| 49 |
+
} catch (_) { return rawUrl; }
|
| 50 |
+
}
|
| 51 |
+
function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {
|
| 52 |
+
if (deps.hashRoute) { restoreFocus = restoreFocus !== false; restoreScroll = restoreScroll !== false; }
|
| 53 |
+
if (!overlay) return false;
|
| 54 |
+
revision++;
|
| 55 |
+
closing = false;
|
| 56 |
+
uiState = "base";
|
| 57 |
+
overlay = null;
|
| 58 |
+
const returnFocus = navigation.unmount();
|
| 59 |
+
if (overlay) return true;
|
| 60 |
+
if (restoreScroll) {
|
| 61 |
+
const saved = position.scroll;
|
| 62 |
+
if (saved && snapshot && deps.snapshotChanged(snapshot, saved.viewKey)) {
|
| 63 |
+
position.setScroll(null);
|
| 64 |
+
deps.restoreSnapshot(saved.viewKey);
|
| 65 |
+
position.setScroll({ ...saved, route: location.href });
|
| 66 |
+
}
|
| 67 |
+
deps.restoreScroll();
|
| 68 |
+
snapshot = null;
|
| 69 |
+
}
|
| 70 |
+
if (restoreFocus && returnFocus && returnFocus.isConnected) returnFocus.focus();
|
| 71 |
+
return true;
|
| 72 |
+
}
|
| 73 |
+
/** @param {URL} url @param {boolean} [addHistory] */
|
| 74 |
+
function openReaderOverlay(url, addHistory = true) {
|
| 75 |
+
if (deps.hashRoute) addHistory = addHistory !== false;
|
| 76 |
+
revision++;
|
| 77 |
+
if (addHistory && !position.scroll) {
|
| 78 |
+
const saved = deps.captureScroll();
|
| 79 |
+
position.setScroll(saved);
|
| 80 |
+
snapshot = deps.saveSnapshot(saved?.viewKey || deps.getViewKey());
|
| 81 |
+
}
|
| 82 |
+
overlay = navigation.mount(url);
|
| 83 |
+
uiState = "base";
|
| 84 |
+
closing = false;
|
| 85 |
+
if (addHistory) navigation.remember(url, /** @type {object} */ (position.scroll));
|
| 86 |
+
}
|
| 87 |
+
function reconcileSearchDestination() {
|
| 88 |
+
if ((deps.hashRoute ? location.pathname !== "/search/" : location.pathname.split("/").filter(Boolean).length > 1) || history.state?.voiceReaderOverlay) return;
|
| 89 |
+
const previous = overlay, owner = revision;
|
| 90 |
+
// Apply the destination before disposal can synchronously start new work.
|
| 91 |
+
if (deps.routeChanged()) deps.applyRoute(deps.hashRoute || !!previous);
|
| 92 |
+
if (overlay !== previous || (deps.hashRoute && revision !== owner)) return;
|
| 93 |
+
deps.closeOverlay();
|
| 94 |
+
}
|
| 95 |
+
/** @param {{voiceReaderOverlay?: boolean; readerUrl?: string} | null} state */
|
| 96 |
+
function restoreReaderOverlay(state) {
|
| 97 |
+
if (!state || !state.voiceReaderOverlay || !state.readerUrl) {
|
| 98 |
+
deps.reconcile(); return;
|
| 99 |
+
}
|
| 100 |
+
try {
|
| 101 |
+
const url = navigation.parse(state.readerUrl);
|
| 102 |
+
const owner = revision + (overlay ? 1 : 0);
|
| 103 |
+
deps.closeOverlay(false, false);
|
| 104 |
+
if (revision !== owner) return;
|
| 105 |
+
deps.openOverlay(url, false);
|
| 106 |
+
} catch (_) {}
|
| 107 |
+
}
|
| 108 |
+
/** @param {ReaderHostMessage} event */
|
| 109 |
+
function handleReaderMessage(event) {
|
| 110 |
+
if (!navigation.accepts(/** @type {MessageEvent} */ (event))) return;
|
| 111 |
+
const message = event.data || {};
|
| 112 |
+
if (message.type === "voice-reader-close") {
|
| 113 |
+
if (closing) return;
|
| 114 |
+
navigation.persistProgress(message.progress);
|
| 115 |
+
closing = true;
|
| 116 |
+
uiState = "base";
|
| 117 |
+
navigation.dismiss();
|
| 118 |
+
let returnUrl = deps.hashRoute ? "/search/" : "/";
|
| 119 |
+
try {
|
| 120 |
+
const target = new URL(new URL(/** @type {HTMLIFrameElement} */ (overlay).src, location.origin).searchParams.get("return") || returnUrl, location.origin);
|
| 121 |
+
if (target.origin === location.origin && (!deps.hashRoute || target.pathname === "/search/")) returnUrl = target.href;
|
| 122 |
+
else if (deps.hashRoute) returnUrl = new URL("/search/", location.origin).href;
|
| 123 |
+
} catch (_) {}
|
| 124 |
+
if (!history.state?.voiceReaderOverlay) {
|
| 125 |
+
const returnFocus = navigation.returnFocus;
|
| 126 |
+
history.replaceState(history.state, "", returnUrl);
|
| 127 |
+
deps.reconcile();
|
| 128 |
+
if (deps.hashRoute && returnFocus && returnFocus.isConnected) returnFocus.focus();
|
| 129 |
+
return;
|
| 130 |
+
}
|
| 131 |
+
const previous = overlay;
|
| 132 |
+
history.back();
|
| 133 |
+
// A delayed Back still owns its Reader entry for Forward.
|
| 134 |
+
setTimeout(() => {
|
| 135 |
+
if (!closing || overlay !== previous) return;
|
| 136 |
+
navigation.showCloseRecovery(returnUrl);
|
| 137 |
+
}, 1000);
|
| 138 |
+
return;
|
| 139 |
+
}
|
| 140 |
+
if (message.type === "voice-reader-ui-state") {
|
| 141 |
+
if (closing) return;
|
| 142 |
+
if (typeof message.state === "string" && ["base", "panel", "full-search"].includes(message.state)) uiState = message.state;
|
| 143 |
+
return;
|
| 144 |
+
}
|
| 145 |
+
if (message.type === "voice-reader-theme") {
|
| 146 |
+
if (message.theme !== "dark" && message.theme !== "light") return;
|
| 147 |
+
deps.applyTheme(message.theme);
|
| 148 |
+
return;
|
| 149 |
+
}
|
| 150 |
+
if (message.type === "voice-reader-open") {
|
| 151 |
+
try { overlay = navigation.replace(/** @type {string} */ (message.url), /** @type {object} */ (position.scroll)); } catch (_) {}
|
| 152 |
+
return;
|
| 153 |
+
}
|
| 154 |
+
if (message.type !== "voice-reader-navigate") return;
|
| 155 |
+
try {
|
| 156 |
+
const target = new URL(/** @type {string} */ (message.url), location.origin);
|
| 157 |
+
if (target.origin !== location.origin || (deps.hashRoute ? target.pathname !== "/search/" : target.pathname.split("/").filter(Boolean).length !== 1)) return;
|
| 158 |
+
history.replaceState(null, "", merge(target).href);
|
| 159 |
+
deps.reconcile();
|
| 160 |
+
} catch (_) {}
|
| 161 |
+
}
|
| 162 |
+
/** @param {string} rawUrl @param {string} [returnUrl] */
|
| 163 |
+
function navigateToReader(rawUrl, returnUrl) {
|
| 164 |
+
let target;
|
| 165 |
+
try { target = navigation.parse(deps.syncFolder(rawUrl)); }
|
| 166 |
+
catch (_) { return false; }
|
| 167 |
+
deps.closeMobileSidebars();
|
| 168 |
+
const url = navigation.prepare(target.href, deps.normalizeReturn(returnUrl || location.href));
|
| 169 |
+
deps.openOverlay(url);
|
| 170 |
+
return true;
|
| 171 |
+
}
|
| 172 |
+
function restoreReaderFromSession() {
|
| 173 |
+
if (overlay) return;
|
| 174 |
+
try {
|
| 175 |
+
const saved = /** @type {{shareUrl?: string; readerUrl?: string; returnScroll?: ReaderReturnPosition} | null} */ (navigation.saved());
|
| 176 |
+
if (!saved || saved.shareUrl !== location.href || !saved.readerUrl) return;
|
| 177 |
+
const url = navigation.parse(saved.readerUrl);
|
| 178 |
+
position.setScroll(saved.returnScroll || null);
|
| 179 |
+
history.replaceState({ voiceReaderOverlay: true, readerUrl: url.href }, "", saved.shareUrl);
|
| 180 |
+
deps.openOverlay(url, false);
|
| 181 |
+
} catch (_) {}
|
| 182 |
+
}
|
| 183 |
+
return Object.freeze({ navigation, keys, currentReaderSearchParams, normalizeReaderReturnUrl, syncReaderFolderFilter,
|
| 184 |
+
closeReaderOverlay, openReaderOverlay, reconcileSearchDestination, restoreReaderOverlay,
|
| 185 |
+
handleReaderMessage, navigateToReader, restoreReaderFromSession,
|
| 186 |
+
get overlay() { return overlay; }, get closing() { return closing; },
|
| 187 |
+
get uiState() { return uiState; }, get returnSnapshot() { return snapshot; }
|
| 188 |
+
});
|
| 189 |
+
}
|
| 190 |
+
globalThis.VoiceOfMLReaderHost = Object.freeze({ create });
|
| 191 |
+
})();
|
static/search/reader-host/presentation/return-position.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Search geometry and focus handoff. The search host supplies only viewport operations.
|
| 2 |
+
(function () {
|
| 3 |
+
/** @param {ReaderReturnDependencies} deps */
|
| 4 |
+
function create(deps) {
|
| 5 |
+
/** @type {ReaderReturnPosition | null} */
|
| 6 |
+
let scroll = null;
|
| 7 |
+
let generation = 0, active = false;
|
| 8 |
+
function captureReaderReturnScroll() {
|
| 9 |
+
const view = deps.readView();
|
| 10 |
+
if (!view.hasContainer) return null;
|
| 11 |
+
const top = deps.getTop();
|
| 12 |
+
let index = 0, offset = top;
|
| 13 |
+
if (view.resultCount) {
|
| 14 |
+
deps.ensureHeights();
|
| 15 |
+
index = deps.findIndex(top);
|
| 16 |
+
offset = top - deps.getOffset(index);
|
| 17 |
+
}
|
| 18 |
+
const element = document.activeElement;
|
| 19 |
+
const focus = element instanceof HTMLElement && element.id ? { id: element.id,
|
| 20 |
+
start: element instanceof HTMLInputElement ? element.selectionStart : null,
|
| 21 |
+
end: element instanceof HTMLInputElement ? element.selectionEnd : null,
|
| 22 |
+
direction: element instanceof HTMLInputElement ? element.selectionDirection : null } : null;
|
| 23 |
+
return { route: location.href, viewKey: deps.getViewKey(), top, index, offset, focus };
|
| 24 |
+
}
|
| 25 |
+
/** @param {ReaderReturnPosition} saved */
|
| 26 |
+
function readerSearchHandoffReady(saved) {
|
| 27 |
+
const view = deps.readView();
|
| 28 |
+
// A usable preview keeps ownership of its adjacent-page validation.
|
| 29 |
+
if (view.loading || !view.loadedPage || !view.resultCount) return false;
|
| 30 |
+
if (view.positionRestore && (!view.positionRestore.preview || view.positionRestore.key !== saved.viewKey)) return false;
|
| 31 |
+
return deps.hasResult(Math.min(saved.index, Math.max(0, view.total - 1)));
|
| 32 |
+
}
|
| 33 |
+
function restoreReaderReturnScroll(windowRendered = false, restoreTop = false) {
|
| 34 |
+
if (!scroll) return;
|
| 35 |
+
const saved = scroll;
|
| 36 |
+
if (saved.route && saved.route !== location.href) { scroll = null; return; }
|
| 37 |
+
if (saved.viewKey && saved.viewKey !== deps.getViewKey()) { scroll = null; return; }
|
| 38 |
+
const owner = ++generation;
|
| 39 |
+
let attempts = 0;
|
| 40 |
+
function restore() {
|
| 41 |
+
if (owner !== generation || saved.viewKey !== deps.getViewKey() || saved.route !== location.href) return;
|
| 42 |
+
const view = deps.readView();
|
| 43 |
+
if (!view.hasContainer || !view.resultCount) {
|
| 44 |
+
if (++attempts < 20) requestAnimationFrame(restore);
|
| 45 |
+
return;
|
| 46 |
+
}
|
| 47 |
+
deps.ensureHeights();
|
| 48 |
+
const index = Math.min(saved.index, view.resultCount - 1);
|
| 49 |
+
const target = Math.max(0, restoreTop ? saved.top : deps.getOffset(index) + saved.offset);
|
| 50 |
+
const max = Math.max(0, deps.getTotalHeight() - view.containerHeight);
|
| 51 |
+
active = true;
|
| 52 |
+
deps.setTop(Math.min(target, max));
|
| 53 |
+
if (!windowRendered) deps.invalidateWindow();
|
| 54 |
+
deps.renderVisible();
|
| 55 |
+
windowRendered = false;
|
| 56 |
+
deps.updateTrack();
|
| 57 |
+
active = false;
|
| 58 |
+
if (++attempts < 4 && Math.abs(deps.getTop() - target) > 1) requestAnimationFrame(restore);
|
| 59 |
+
else scroll = null;
|
| 60 |
+
}
|
| 61 |
+
restore();
|
| 62 |
+
if (scroll === saved) requestAnimationFrame(() => requestAnimationFrame(restore));
|
| 63 |
+
}
|
| 64 |
+
/** @param {ReturnType<SearchReaderNavigationApi['createNavigation']>} navigation */
|
| 65 |
+
function restoreReaderSearchHandoff(navigation) {
|
| 66 |
+
/** @type {ReaderReturnPosition | null | undefined} */
|
| 67 |
+
let saved;
|
| 68 |
+
try {
|
| 69 |
+
const handoff = JSON.parse(sessionStorage.getItem("reader-navigation-restore") || "null");
|
| 70 |
+
sessionStorage.removeItem("reader-navigation-restore");
|
| 71 |
+
if (!handoff || handoff.returnUrl !== location.href) return;
|
| 72 |
+
const current = /** @type {{readerUrl?: string; returnScroll?: ReaderReturnPosition} | null} */ (navigation.saved());
|
| 73 |
+
if (!current || current.readerUrl !== handoff.readerUrl) return;
|
| 74 |
+
const url = navigation.parse(handoff.readerUrl);
|
| 75 |
+
const token = url.searchParams.get("nav");
|
| 76 |
+
if (!token || sessionStorage.getItem("reader-return:" + token) !== location.href) return;
|
| 77 |
+
saved = current.returnScroll;
|
| 78 |
+
if (!saved || saved.route !== location.href || saved.viewKey !== deps.getViewKey() ||
|
| 79 |
+
!Number.isInteger(saved.index) || saved.index < 0 || !Number.isFinite(saved.offset) || !Number.isFinite(saved.top)) return;
|
| 80 |
+
} catch (_) { return; }
|
| 81 |
+
const position = saved;
|
| 82 |
+
const route = location.href;
|
| 83 |
+
let cancelled = false;
|
| 84 |
+
const cancel = () => { cancelled = true; cleanup(); };
|
| 85 |
+
const events = ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"];
|
| 86 |
+
const cleanup = () => { for (const type of events) document.removeEventListener(type, cancel, true); };
|
| 87 |
+
for (const type of events) document.addEventListener(type, cancel, true);
|
| 88 |
+
const revision = deps.readView().routeRevision;
|
| 89 |
+
const deadline = Date.now() + 30000;
|
| 90 |
+
const restore = () => {
|
| 91 |
+
if (cancelled || revision !== deps.readView().routeRevision || location.href !== route || position.viewKey !== deps.getViewKey() || Date.now() > deadline) {
|
| 92 |
+
cleanup(); return;
|
| 93 |
+
}
|
| 94 |
+
if (!deps.handoffReady(position)) { requestAnimationFrame(restore); return; }
|
| 95 |
+
cleanup();
|
| 96 |
+
scroll = position;
|
| 97 |
+
deps.restoreScroll(false, true);
|
| 98 |
+
const focus = position.focus;
|
| 99 |
+
const element = focus && document.getElementById(focus.id);
|
| 100 |
+
if (!element || (document.activeElement !== document.body && document.activeElement !== element)) return;
|
| 101 |
+
element.focus({ preventScroll: true });
|
| 102 |
+
if (element instanceof HTMLInputElement && Number.isInteger(focus.start) && Number.isInteger(focus.end) &&
|
| 103 |
+
focus.direction && ["forward", "backward", "none"].includes(focus.direction)) {
|
| 104 |
+
try { element.setSelectionRange(focus.start, focus.end, focus.direction); } catch (_) {}
|
| 105 |
+
}
|
| 106 |
+
};
|
| 107 |
+
requestAnimationFrame(restore);
|
| 108 |
+
}
|
| 109 |
+
return Object.freeze({
|
| 110 |
+
capture: captureReaderReturnScroll, ready: readerSearchHandoffReady,
|
| 111 |
+
restore: restoreReaderReturnScroll, restoreHandoff: restoreReaderSearchHandoff,
|
| 112 |
+
get scroll() { return scroll; },
|
| 113 |
+
/** @param {ReaderReturnPosition | null} value */
|
| 114 |
+
setScroll(value) { scroll = value; },
|
| 115 |
+
invalidate() { generation++; },
|
| 116 |
+
cancelOnScroll() { if (scroll && !active) { generation++; scroll = null; } }
|
| 117 |
+
});
|
| 118 |
+
}
|
| 119 |
+
globalThis.VoiceOfMLReaderReturn = Object.freeze({ create });
|
| 120 |
+
})();
|
static/sw.js
CHANGED
|
@@ -94,6 +94,8 @@ const PRECACHE_URLS = [
|
|
| 94 |
"/static/reader-resources.js",
|
| 95 |
"/static/reader/core/reader-contract.js",
|
| 96 |
"/static/search/reader-navigation.js",
|
|
|
|
|
|
|
| 97 |
"/static/search/input/domain/ownership.js",
|
| 98 |
"/static/search/input/application/controller.js",
|
| 99 |
"/static/search/sidebar/presentation/filter-list.js",
|
|
|
|
| 94 |
"/static/reader-resources.js",
|
| 95 |
"/static/reader/core/reader-contract.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/input/domain/ownership.js",
|
| 100 |
"/static/search/input/application/controller.js",
|
| 101 |
"/static/search/sidebar/presentation/filter-list.js",
|
tests/gates/test_static_contract.py
CHANGED
|
@@ -582,7 +582,9 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected');
|
|
| 582 |
self.assertIn('.reader-panel-tabs', reader_css)
|
| 583 |
self.assertIn('function syncCurrentPageFromMarker', reader)
|
| 584 |
self.assertNotIn('reader-docx-page', reader)
|
| 585 |
-
self.assertIn('message.type === "voice-reader-open"',
|
|
|
|
|
|
|
| 586 |
self.assertNotIn('loadFoliateDocument', reader)
|
| 587 |
self.assertIn('async function renderFoliate', reader)
|
| 588 |
foliate = (ROOT / "static/reader/formats/reader-foliate-format.mjs").read_text(encoding="utf-8")
|
|
@@ -973,11 +975,14 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected');
|
|
| 973 |
"function restoreReaderReturnScroll",
|
| 974 |
"viewKey: \"\"",
|
| 975 |
"heightCache: new Map()",
|
| 976 |
-
"
|
| 977 |
-
"if (saved.viewKey && saved.viewKey !== getSearchViewKey())",
|
| 978 |
-
"if (readerReturnScrollState && !readerReturnRestoreActive)",
|
| 979 |
):
|
| 980 |
self.assertIn(value, self.js)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 981 |
self.assertIn("searchWithInitialFallback();", self.js)
|
| 982 |
self.assertIn("validSearchViewport(viewport, position)", self.js)
|
| 983 |
self.assertIn("return searchWithInitialFallbackFresh(intent);", self.js)
|
|
|
|
| 582 |
self.assertIn('.reader-panel-tabs', reader_css)
|
| 583 |
self.assertIn('function syncCurrentPageFromMarker', reader)
|
| 584 |
self.assertNotIn('reader-docx-page', reader)
|
| 585 |
+
self.assertIn('message.type === "voice-reader-open"',
|
| 586 |
+
(ROOT / "static/search/reader-host/application/host.js").read_text())
|
| 587 |
+
self.assertIn('readerHost.handleReaderMessage(event)', self.js)
|
| 588 |
self.assertNotIn('loadFoliateDocument', reader)
|
| 589 |
self.assertIn('async function renderFoliate', reader)
|
| 590 |
foliate = (ROOT / "static/reader/formats/reader-foliate-format.mjs").read_text(encoding="utf-8")
|
|
|
|
| 975 |
"function restoreReaderReturnScroll",
|
| 976 |
"viewKey: \"\"",
|
| 977 |
"heightCache: new Map()",
|
| 978 |
+
"readerReturnPosition.cancelOnScroll()",
|
|
|
|
|
|
|
| 979 |
):
|
| 980 |
self.assertIn(value, self.js)
|
| 981 |
+
host = (ROOT / "static/search/reader-host/application/host.js").read_text()
|
| 982 |
+
position = (ROOT / "static/search/reader-host/presentation/return-position.js").read_text()
|
| 983 |
+
self.assertIn("navigation.remember(url, /** @type {object} */ (position.scroll))", host)
|
| 984 |
+
self.assertIn("if (saved.viewKey && saved.viewKey !== deps.getViewKey())", position)
|
| 985 |
+
self.assertIn("if (scroll && !active) { generation++; scroll = null; }", position)
|
| 986 |
self.assertIn("searchWithInitialFallback();", self.js)
|
| 987 |
self.assertIn("validSearchViewport(viewport, position)", self.js)
|
| 988 |
self.assertIn("return searchWithInitialFallbackFresh(intent);", self.js)
|
tests/reader/backend/test_reader_range_flights.py
CHANGED
|
@@ -2,6 +2,7 @@
|
|
| 2 |
import asyncio
|
| 3 |
import unittest
|
| 4 |
from types import SimpleNamespace
|
|
|
|
| 5 |
|
| 6 |
from backend import app
|
| 7 |
from tests.proxy.test_async_proxy import FakeResponse, FakeSession
|
|
@@ -249,6 +250,155 @@ class ReaderRangeFlightTests(unittest.IsolatedAsyncioTestCase):
|
|
| 249 |
self.assertEqual(len(session.urls),2)
|
| 250 |
self.assertEqual([first.status_code,second.status_code],[304,304])
|
| 251 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
async def test_shutdown_stops_active_shared_body_and_releases_pool(self):
|
| 253 |
upstream = GatedResponse()
|
| 254 |
app.app.state.http_session = FakeSession([upstream])
|
|
|
|
| 2 |
import asyncio
|
| 3 |
import unittest
|
| 4 |
from types import SimpleNamespace
|
| 5 |
+
from unittest.mock import AsyncMock, Mock, patch
|
| 6 |
|
| 7 |
from backend import app
|
| 8 |
from tests.proxy.test_async_proxy import FakeResponse, FakeSession
|
|
|
|
| 250 |
self.assertEqual(len(session.urls),2)
|
| 251 |
self.assertEqual([first.status_code,second.status_code],[304,304])
|
| 252 |
|
| 253 |
+
async def test_queued_document_resolves_opener_and_session_after_admission(self):
|
| 254 |
+
entered = asyncio.Event()
|
| 255 |
+
class Gate(asyncio.Semaphore):
|
| 256 |
+
async def acquire(self):
|
| 257 |
+
entered.set()
|
| 258 |
+
return await super().acquire()
|
| 259 |
+
semaphore = app.app.state.upstream_semaphore = Gate(0)
|
| 260 |
+
upstream = FakeResponse(200, {'Content-Length': '4'}, (b'abcd',))
|
| 261 |
+
request = SimpleNamespace(method='GET', headers={})
|
| 262 |
+
with patch.object(app, 'open_download_response', AsyncMock()) as stale:
|
| 263 |
+
pending = asyncio.create_task(app._stream_reader_document(request, URL))
|
| 264 |
+
await asyncio.wait_for(entered.wait(), 1)
|
| 265 |
+
session = app.app.state.http_session = object()
|
| 266 |
+
with patch.object(app, 'open_download_response', AsyncMock(return_value=upstream)) as current:
|
| 267 |
+
semaphore.release()
|
| 268 |
+
response = await asyncio.wait_for(pending, 1)
|
| 269 |
+
self.assertIs(current.call_args.args[0], session)
|
| 270 |
+
self.assertIs(current.call_args.kwargs['url_validator'], app.validate_reader_redirect_url)
|
| 271 |
+
stale.assert_not_called()
|
| 272 |
+
self.assertEqual(await self.drain(response), b'abcd')
|
| 273 |
+
self.assertTrue(upstream.released)
|
| 274 |
+
self.assertEqual(semaphore._value, 1)
|
| 275 |
+
|
| 276 |
+
async def test_suspended_headers_resolve_compression_isolation_and_response_hooks(self):
|
| 277 |
+
entered, resume = asyncio.Event(), asyncio.Event()
|
| 278 |
+
upstream = FakeResponse(200, {'Content-Length': '4', 'ETag': '"strong"'}, (b'abcd',))
|
| 279 |
+
app.app.state.http_session = object()
|
| 280 |
+
async def opener(*_args, **_kwargs):
|
| 281 |
+
entered.set()
|
| 282 |
+
await resume.wait()
|
| 283 |
+
return upstream
|
| 284 |
+
with patch.object(app, 'open_download_response', opener):
|
| 285 |
+
pending = asyncio.create_task(app._stream_reader_document(SimpleNamespace(method='GET', headers={}), URL))
|
| 286 |
+
await asyncio.wait_for(entered.wait(), 1)
|
| 287 |
+
original_browser, original_timing = app.reader_document_browser_headers, app.reader_proxy_timing
|
| 288 |
+
with patch.object(app, 'READER_ISOLATION_HEADERS', {'X-Live-Isolation': 'yes'}), \
|
| 289 |
+
patch.object(app, 'READER_UPSTREAM_RESPONSE_HEADERS', ('Content-Length', 'ETag')), \
|
| 290 |
+
patch.object(app, 'reader_body_allows_compression', return_value=True) as compression, \
|
| 291 |
+
patch.object(app, 'reader_document_browser_headers', wraps=original_browser) as browser, \
|
| 292 |
+
patch.object(app, 'reader_proxy_timing', wraps=original_timing) as timing:
|
| 293 |
+
resume.set()
|
| 294 |
+
response = await asyncio.wait_for(pending, 1)
|
| 295 |
+
self.assertEqual(response.headers['etag'], 'W/"strong"')
|
| 296 |
+
self.assertEqual(response.headers['x-live-isolation'], 'yes')
|
| 297 |
+
self.assertNotIn('content-encoding', response.headers)
|
| 298 |
+
self.assertIn('reader_cache;desc="miss"', response.headers['server-timing'])
|
| 299 |
+
compression.assert_called_once()
|
| 300 |
+
browser.assert_called_once()
|
| 301 |
+
timing.assert_called_once()
|
| 302 |
+
self.assertEqual(await self.drain(response), b'abcd')
|
| 303 |
+
self.assertTrue(upstream.released)
|
| 304 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 2)
|
| 305 |
+
|
| 306 |
+
async def test_body_limit_keeps_captured_cap_and_resolves_live_error_hook(self):
|
| 307 |
+
upstream = GatedResponse()
|
| 308 |
+
upstream.status = 200
|
| 309 |
+
upstream.headers = {}
|
| 310 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 311 |
+
with patch.object(app, 'READER_DOCUMENT_MAX_BYTES', 3):
|
| 312 |
+
response = await app._stream_reader_document(SimpleNamespace(method='GET', headers={}), URL)
|
| 313 |
+
self.assertEqual(await anext(response.body_iterator), b'ab')
|
| 314 |
+
class CurrentLimitError(ValueError):
|
| 315 |
+
pass
|
| 316 |
+
with patch.object(app, 'READER_DOCUMENT_MAX_BYTES', 100), \
|
| 317 |
+
patch.object(app, 'ReaderDocumentLimitError', CurrentLimitError):
|
| 318 |
+
upstream.resume.set()
|
| 319 |
+
with self.assertRaisesRegex(CurrentLimitError, '阅读文件过大'):
|
| 320 |
+
await self.drain(response)
|
| 321 |
+
self.assertEqual(upstream.release_count, 1)
|
| 322 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 2)
|
| 323 |
+
self.assertFalse(app.app.state.reader_range_cache)
|
| 324 |
+
|
| 325 |
+
async def test_cache_admission_at_iteration_and_eviction_after_suspended_body(self):
|
| 326 |
+
for stage in ('admission', 'completion'):
|
| 327 |
+
with self.subTest(stage=stage):
|
| 328 |
+
upstream = GatedResponse()
|
| 329 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 330 |
+
response = await app._stream_reader_document(
|
| 331 |
+
SimpleNamespace(method='GET', headers={'Range': 'bytes=0-3'}), URL, _share_range=False)
|
| 332 |
+
if stage == 'admission':
|
| 333 |
+
with patch.object(app, 'READER_RANGE_CACHE_MAX_ITEM_BYTES', 3):
|
| 334 |
+
self.assertEqual(await anext(response.body_iterator), b'ab')
|
| 335 |
+
upstream.resume.set()
|
| 336 |
+
self.assertEqual(await self.drain(response), b'cd')
|
| 337 |
+
else:
|
| 338 |
+
self.assertEqual(await anext(response.body_iterator), b'ab')
|
| 339 |
+
# Publication follows the live cache and budget after the await.
|
| 340 |
+
cache = app.app.state.reader_range_cache = app.OrderedDict()
|
| 341 |
+
app.app.state.reader_range_cache_bytes = 0
|
| 342 |
+
with patch.object(app, 'READER_RANGE_CACHE_MAX_BYTES', 3):
|
| 343 |
+
upstream.resume.set()
|
| 344 |
+
self.assertEqual(await self.drain(response), b'cd')
|
| 345 |
+
self.assertIs(app.app.state.reader_range_cache, cache)
|
| 346 |
+
self.assertEqual(upstream.release_count, 1)
|
| 347 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 2)
|
| 348 |
+
self.assertFalse(app.app.state.reader_range_cache)
|
| 349 |
+
self.assertEqual(app.app.state.reader_range_cache_bytes, 0)
|
| 350 |
+
|
| 351 |
+
async def test_replaced_validator_identity_cannot_authorize_old_policy_cache(self):
|
| 352 |
+
key = (URL, 'bytes=0-3', app.READER_DOCUMENT_MAX_BYTES, None)
|
| 353 |
+
headers = {'Content-Length': '4', 'Content-Range': 'bytes 0-3/10'}
|
| 354 |
+
app.app.state.reader_range_cache[key] = (app.time.monotonic(), b'old!', headers)
|
| 355 |
+
app.app.state.reader_range_cache_bytes = 4
|
| 356 |
+
original = app.validate_reader_redirect_url
|
| 357 |
+
# Defaults capture the original function; policy checks must see the live function.
|
| 358 |
+
with patch.object(app, 'validate_reader_redirect_url', lambda value: original(value)):
|
| 359 |
+
upstream = GatedResponse()
|
| 360 |
+
session = app.app.state.http_session = FakeSession([upstream])
|
| 361 |
+
response = await self.open()
|
| 362 |
+
upstream.resume.set()
|
| 363 |
+
self.assertEqual(await self.drain(response), b'abcd')
|
| 364 |
+
self.assertEqual(len(session.urls), 1)
|
| 365 |
+
self.assertEqual(app.app.state.reader_range_cache[key][1], b'old!')
|
| 366 |
+
original_bucket = app.validate_reader_bucket_redirect_url
|
| 367 |
+
with patch.object(app, 'validate_reader_bucket_redirect_url', lambda value, _source: value):
|
| 368 |
+
upstream = GatedResponse()
|
| 369 |
+
session = app.app.state.http_session = FakeSession([upstream])
|
| 370 |
+
response = await self.open(url_validator=lambda value: value,
|
| 371 |
+
validation_scope=(original_bucket, URL))
|
| 372 |
+
upstream.resume.set()
|
| 373 |
+
self.assertEqual(await self.drain(response), b'abcd')
|
| 374 |
+
self.assertEqual(len(session.urls), 1)
|
| 375 |
+
self.assertEqual(app.app.state.reader_range_cache[key][1], b'old!')
|
| 376 |
+
|
| 377 |
+
async def test_shared_producer_selects_stream_hook_when_task_starts(self):
|
| 378 |
+
request = SimpleNamespace(method='GET', headers={'Range': 'bytes=0-3'})
|
| 379 |
+
options = app.ReaderStreamOptions(url_validator=app.validate_reader_redirect_url,
|
| 380 |
+
cache_control=None, max_bytes=100, media_type=None, validation_scope=None)
|
| 381 |
+
key = (URL, 'bytes=0-3', 100, None)
|
| 382 |
+
# Replacement happens after flight admission, before its task runs.
|
| 383 |
+
response = app.Response(b'abcd', status_code=206, headers=app.reader_proxy_timing({}, cache='miss'))
|
| 384 |
+
current = AsyncMock(return_value=response)
|
| 385 |
+
stale = Mock(side_effect=AssertionError('captured the stream hook at admission'))
|
| 386 |
+
patcher = patch.object(app, '_stream_reader_document', current)
|
| 387 |
+
def switch_hook():
|
| 388 |
+
patcher.start()
|
| 389 |
+
return 1.0
|
| 390 |
+
with patch.object(app, '_stream_reader_document', stale), \
|
| 391 |
+
patch.object(app, 'time', SimpleNamespace(monotonic=switch_hook)):
|
| 392 |
+
try:
|
| 393 |
+
selected = await app.shared_reader_range_response(request, URL, key, options)
|
| 394 |
+
self.assertEqual(await self.drain(selected), b'abcd')
|
| 395 |
+
current.assert_awaited_once_with(request, URL, _share_range=False, **options)
|
| 396 |
+
stale.assert_not_called()
|
| 397 |
+
finally:
|
| 398 |
+
patcher.stop()
|
| 399 |
+
self.assertFalse(app.app.state.reader_range_flights)
|
| 400 |
+
self.assertFalse(app.app.state.reader_range_flight_owners)
|
| 401 |
+
|
| 402 |
async def test_shutdown_stops_active_shared_body_and_releases_pool(self):
|
| 403 |
upstream = GatedResponse()
|
| 404 |
app.app.state.http_session = FakeSession([upstream])
|
tests/search/reader-navigation/host_contracts.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from 'node:assert/strict';
|
| 2 |
+
import fs from 'node:fs';
|
| 3 |
+
import vm from 'node:vm';
|
| 4 |
+
import test from 'node:test';
|
| 5 |
+
import {APP_DEPENDENCIES, stripBundledScripts} from '../../../scripts/build/compose_app.mjs';
|
| 6 |
+
|
| 7 |
+
const paths = ['search/reader-host/presentation/return-position.js', 'search/reader-host/application/host.js'];
|
| 8 |
+
function context(values = {}) {
|
| 9 |
+
const c = vm.createContext({URL, URLSearchParams, ...values});
|
| 10 |
+
for (const path of paths) vm.runInContext(fs.readFileSync('static/' + path, 'utf8'), c);
|
| 11 |
+
return c;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
test('reader host dependencies are composed, cached and loaded before the app', () => {
|
| 15 |
+
const html = fs.readFileSync('static/index.html', 'utf8'), c = context();
|
| 16 |
+
vm.runInContext(fs.readFileSync('static/reader-resources.js', 'utf8'), c);
|
| 17 |
+
for (const path of paths) {
|
| 18 |
+
assert.ok(APP_DEPENDENCIES.indexOf(path) > APP_DEPENDENCIES.indexOf('search/reader-navigation.js'));
|
| 19 |
+
assert.ok(html.indexOf(path) > html.indexOf('search/reader-navigation.js'));
|
| 20 |
+
assert.ok(html.indexOf(path) < html.indexOf('static/app.js'));
|
| 21 |
+
assert.ok(!stripBundledScripts(html).includes(path));
|
| 22 |
+
assert.ok(fs.readFileSync('static/sw.js', 'utf8').includes('/static/' + path));
|
| 23 |
+
for (const site of ['github', 'huggingface']) assert.ok(c.VoiceOfMLReaderResources.buildFiles(site).includes(path));
|
| 24 |
+
const source = fs.readFileSync('static/' + path, 'utf8');
|
| 25 |
+
assert.doesNotMatch(source, /\bSTATE\b|\bVSCROLL\b|\bDOM\b|new Proxy/);
|
| 26 |
+
}
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
test('return position owns scroll cancellation and retires queued route restores', () => {
|
| 30 |
+
const frames = [], writes = [];
|
| 31 |
+
const location = new URL('https://example.test/search/');
|
| 32 |
+
const c = context({location, requestAnimationFrame: fn => frames.push(fn)});
|
| 33 |
+
let view = {hasContainer:true, containerHeight:100, resultCount:5}, position, render;
|
| 34 |
+
const deps = {readView:()=>view, getViewKey:()=> 'view', ensureHeights(){}, getOffset:i=>i*100,
|
| 35 |
+
getTotalHeight:()=>500, setTop:top=>{writes.push(top);position.cancelOnScroll();}, getTop:()=>110,
|
| 36 |
+
invalidateWindow(){}, renderVisible:()=>render?.(), updateTrack(){}};
|
| 37 |
+
position = c.VoiceOfMLReaderReturn.create(deps);
|
| 38 |
+
const saved = {route:location.href,viewKey:'view',index:1,offset:10,top:110,focus:null};
|
| 39 |
+
position.setScroll(saved);
|
| 40 |
+
position.restore();
|
| 41 |
+
assert.deepEqual(writes,[110], 'synchronous scroll event cannot cancel the active restoration');
|
| 42 |
+
view = {...view,resultCount:0};
|
| 43 |
+
position.setScroll(saved);position.restore();
|
| 44 |
+
position.invalidate();view.resultCount=5;
|
| 45 |
+
while(frames.length) frames.shift()();
|
| 46 |
+
assert.deepEqual(writes,[110], 'route invalidation retires callbacks already queued');
|
| 47 |
+
position.cancelOnScroll();assert.equal(position.scroll,null);
|
| 48 |
+
render=()=>writes.push('new renderer');
|
| 49 |
+
position.setScroll(saved);position.restore();
|
| 50 |
+
assert.equal(writes.at(-1),'new renderer','effects resolve the current host hook');
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
test('handoff requires the matching session token and yields to input ownership', () => {
|
| 54 |
+
for (const mode of ['valid','missing-token','blocked-storage','input','new-route']) {
|
| 55 |
+
const frames=[],listeners=new Map(),writes=[],focused=[];
|
| 56 |
+
const location=new URL('https://example.test/search/');
|
| 57 |
+
class Input { focus(options){focused.push(options);} setSelectionRange(...args){focused.push(args);} }
|
| 58 |
+
const input=new Input(),body={};
|
| 59 |
+
const saved={route:location.href,viewKey:'view',index:0,offset:3,top:3,
|
| 60 |
+
focus:{id:'query',start:1,end:3,direction:'backward'}};
|
| 61 |
+
const readerUrl='https://example.test/reader?nav=token';
|
| 62 |
+
const stored=new Map([
|
| 63 |
+
['reader-navigation-restore',JSON.stringify({returnUrl:location.href,readerUrl})],
|
| 64 |
+
['reader-return:token',location.href]
|
| 65 |
+
]);
|
| 66 |
+
if(mode==='missing-token') stored.delete('reader-return:token');
|
| 67 |
+
const c=context({location,HTMLInputElement:Input,requestAnimationFrame:fn=>frames.push(fn),
|
| 68 |
+
sessionStorage:{getItem(key){if(mode==='blocked-storage') throw Error('blocked');return stored.get(key);},removeItem:key=>stored.delete(key)},
|
| 69 |
+
document:{body,activeElement:body,getElementById:()=>input,
|
| 70 |
+
addEventListener:(type,fn)=>listeners.set(type,fn),removeEventListener:type=>listeners.delete(type)}});
|
| 71 |
+
let revision=1;
|
| 72 |
+
const position=c.VoiceOfMLReaderReturn.create({
|
| 73 |
+
readView:()=>({hasContainer:true,containerHeight:100,resultCount:1,total:1,loading:false,loadedPage:1,
|
| 74 |
+
positionRestore:{key:'view',preview:true},routeRevision:revision}),
|
| 75 |
+
hasResult:()=>true,getViewKey:()=> 'view',ensureHeights(){},getOffset:()=>0,getTotalHeight:()=>500,
|
| 76 |
+
setTop:top=>writes.push(top),getTop:()=>3,invalidateWindow(){},renderVisible(){},updateTrack(){},
|
| 77 |
+
handoffReady:saved=>position.ready(saved),restoreScroll:(rendered,top)=>position.restore(rendered,top)
|
| 78 |
+
});
|
| 79 |
+
position.restoreHandoff({saved:()=>({readerUrl,returnScroll:saved}),parse:raw=>new URL(raw)});
|
| 80 |
+
if(mode==='input') listeners.get('input')();
|
| 81 |
+
if(mode==='new-route') revision++;
|
| 82 |
+
while(frames.length) frames.shift()();
|
| 83 |
+
assert.equal(listeners.size,0,'interaction listeners are released');
|
| 84 |
+
if(mode==='valid') {
|
| 85 |
+
assert.deepEqual(writes,[3]);
|
| 86 |
+
assert.equal(focused[0].preventScroll,true);
|
| 87 |
+
assert.deepEqual(focused[1],[1,3,'backward']);
|
| 88 |
+
} else {assert.deepEqual(writes,[]);assert.deepEqual(focused,[]);}
|
| 89 |
+
}
|
| 90 |
+
});
|
| 91 |
+
|
| 92 |
+
test('host release is synchronous and disposal reentry keeps the newer reader', () => {
|
| 93 |
+
for (const hashRoute of [false,true]) {
|
| 94 |
+
const location = new URL('https://example.test' + (hashRoute ? '/search/' : '/'));
|
| 95 |
+
const history = {state:null,replaceState(state, unused, url){this.state=state;location.href=url;}};
|
| 96 |
+
const c = context({location,history});
|
| 97 |
+
let scroll=null,host,onUnmount,focuses=0,restores=0;
|
| 98 |
+
const position = {get scroll(){return scroll;},setScroll:value=>{scroll=value;}};
|
| 99 |
+
const navigation = {parse:raw=>new URL(raw,location),mount:url=>({src:url.href,contentWindow:{}}),
|
| 100 |
+
unmount(){onUnmount?.();return {isConnected:true,focus(){focuses++;}};},remember(){},
|
| 101 |
+
accepts:event=>!!host.overlay && event.origin===location.origin && event.source===host.overlay.contentWindow};
|
| 102 |
+
const deps = {hashRoute,position,createNavigation:()=>navigation,getViewKey:()=> 'view',
|
| 103 |
+
captureScroll:()=>null,saveSnapshot:()=>null,restoreScroll:()=>restores++,
|
| 104 |
+
openOverlay:(...args)=>host.openReaderOverlay(...args),closeOverlay:(...args)=>host.closeReaderOverlay(...args),
|
| 105 |
+
reconcile:()=>host.reconcileSearchDestination(),routeChanged:()=>false,applyTheme(){throw Error('unexpected theme');}};
|
| 106 |
+
host=c.VoiceOfMLReaderHost.create(deps);
|
| 107 |
+
host.openReaderOverlay(new URL('/reader?id=old',location));
|
| 108 |
+
const first=host.overlay;
|
| 109 |
+
host.handleReaderMessage({origin:'https://other.test',source:first.contentWindow,data:{type:'voice-reader-theme',theme:'dark'}});
|
| 110 |
+
host.handleReaderMessage({origin:location.origin,source:{},data:{type:'voice-reader-theme',theme:'dark'}});
|
| 111 |
+
assert.equal(host.overlay,first);
|
| 112 |
+
onUnmount=()=>{assert.equal(host.overlay,null);host.openReaderOverlay(new URL('/reader?id=new',location),false);};
|
| 113 |
+
host.restoreReaderOverlay({voiceReaderOverlay:true,readerUrl:'/reader?id=stale'});
|
| 114 |
+
assert.equal(new URL(host.overlay.src).searchParams.get('id'),'new');
|
| 115 |
+
assert.equal(restores,0);assert.equal(focuses,0);
|
| 116 |
+
onUnmount=null;host.closeReaderOverlay();
|
| 117 |
+
assert.equal(host.overlay,null);assert.equal(restores,1);assert.equal(focuses,1);
|
| 118 |
+
}
|
| 119 |
+
});
|
tests/search/reader-navigation/test_search_history_races.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import assert from 'node:assert/strict';
|
|
| 4 |
import fs from 'node:fs';
|
| 5 |
import vm from 'node:vm';
|
| 6 |
import test from 'node:test';
|
|
|
|
| 7 |
import '../paging/result_window_contracts.mjs';
|
| 8 |
import { installClassicSearchModules } from '../../support/classic_search_modules.js';
|
| 9 |
import { APP_DEPENDENCIES, stripBundledScripts } from '../../../scripts/build/compose_app.mjs';
|
|
@@ -12,6 +13,12 @@ const source = fs.readFileSync('static/app.js', 'utf8');
|
|
| 12 |
function fixture(names, values = {}) {
|
| 13 |
const context = vm.createContext({AbortController, searchTransport:undefined, searchPagePrefetch:undefined, ...values});
|
| 14 |
installClassicSearchModules(process.cwd(), context);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
for (const name of names) {
|
| 16 |
const match = source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));
|
| 17 |
assert.ok(match, name);
|
|
|
|
| 4 |
import fs from 'node:fs';
|
| 5 |
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';
|
|
|
|
| 13 |
function fixture(names, values = {}) {
|
| 14 |
const context = vm.createContext({AbortController, searchTransport:undefined, searchPagePrefetch:undefined, ...values});
|
| 15 |
installClassicSearchModules(process.cwd(), context);
|
| 16 |
+
context.readerHost = {overlay: null};
|
| 17 |
+
context.readerReturnPosition = context.VoiceOfMLReaderReturn.create({
|
| 18 |
+
readView: () => ({loading: context.STATE.isLoading, loadedPage: context.STATE._loadedPage,
|
| 19 |
+
resultCount: context.STATE.results.length, total: context.STATE.total, positionRestore: context.positionRestore}),
|
| 20 |
+
hasResult: index => !!context.STATE.results[index]
|
| 21 |
+
});
|
| 22 |
for (const name of names) {
|
| 23 |
const match = source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));
|
| 24 |
assert.ok(match, name);
|
tests/support/classic_search_modules.js
CHANGED
|
@@ -6,6 +6,7 @@ const path = require("path");
|
|
| 6 |
const vm = require("vm");
|
| 7 |
|
| 8 |
const MODULES = ["static/search/folder-selection.js", "static/search/domain/height-index.js",
|
|
|
|
| 9 |
"static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js",
|
| 10 |
"static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"];
|
| 11 |
const sources = new Map();
|
|
|
|
| 6 |
const vm = require("vm");
|
| 7 |
|
| 8 |
const MODULES = ["static/search/folder-selection.js", "static/search/domain/height-index.js",
|
| 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"];
|
| 12 |
const sources = new Map();
|
typings/search-reader-host.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
interface ReaderReturnPosition {
|
| 2 |
+
route: string; viewKey: string; top: number; index: number; offset: number;
|
| 3 |
+
focus: { id: string; start: number | null; end: number | null; direction: "forward" | "backward" | "none" | null } | null;
|
| 4 |
+
}
|
| 5 |
+
interface ReaderReturnDependencies {
|
| 6 |
+
readView(): { hasContainer: boolean; containerHeight: number; resultCount: number; total: number;
|
| 7 |
+
loading: boolean; loadedPage: number; positionRestore: { preview?: boolean; key: string } | null; routeRevision: number };
|
| 8 |
+
hasResult(index: number): boolean;
|
| 9 |
+
getViewKey(): string; getTop(): number; setTop(top: number): void;
|
| 10 |
+
ensureHeights(): void; findIndex(top: number): number; getOffset(index: number): number;
|
| 11 |
+
getTotalHeight(): number; invalidateWindow(): void; renderVisible(): void; updateTrack(): void;
|
| 12 |
+
handoffReady(saved: ReaderReturnPosition): boolean; restoreScroll(rendered: boolean, top: boolean): void;
|
| 13 |
+
}
|
| 14 |
+
interface ReaderReturnController {
|
| 15 |
+
capture(): ReaderReturnPosition | null; ready(saved: ReaderReturnPosition): boolean;
|
| 16 |
+
restore(windowRendered?: boolean, restoreTop?: boolean): void;
|
| 17 |
+
restoreHandoff(navigation: ReturnType<SearchReaderNavigationApi['createNavigation']>): void;
|
| 18 |
+
readonly scroll: ReaderReturnPosition | null;
|
| 19 |
+
setScroll(value: ReaderReturnPosition | null): void; invalidate(): void; cancelOnScroll(): void;
|
| 20 |
+
}
|
| 21 |
+
// The snapshot is an opaque identity handle; only the host reads its payload.
|
| 22 |
+
interface ReaderHostSnapshot { readonly results: readonly unknown[]; readonly loadedPage: number }
|
| 23 |
+
interface ReaderHostMessage {
|
| 24 |
+
origin: string; source: MessageEventSource | null;
|
| 25 |
+
data: { type?: string; state?: string; theme?: string; url?: string;
|
| 26 |
+
progress?: {url?: unknown; closeTime?: unknown} | null };
|
| 27 |
+
}
|
| 28 |
+
interface ReaderHostDependencies {
|
| 29 |
+
hashRoute: boolean; position: ReaderReturnController;
|
| 30 |
+
createNavigation(options: {resume(url: string): void; close(): void}): ReturnType<SearchReaderNavigationApi['createNavigation']>;
|
| 31 |
+
buildParams(): URLSearchParams; readQuery(): string; currentParams(): URLSearchParams;
|
| 32 |
+
getViewKey(): string; captureScroll(): ReaderReturnPosition | null; restoreScroll(): void;
|
| 33 |
+
saveSnapshot(key: string): ReaderHostSnapshot | null;
|
| 34 |
+
snapshotChanged(snapshot: ReaderHostSnapshot, key: string): boolean; restoreSnapshot(key: string): void;
|
| 35 |
+
routeChanged(): boolean; applyRoute(preserve: boolean): void; closeMobileSidebars(): void;
|
| 36 |
+
applyTheme(theme: "dark" | "light"): void;
|
| 37 |
+
navigate(url: string): void; handleMessage(event: ReaderHostMessage): void;
|
| 38 |
+
syncFolder(url: string): string; normalizeReturn(url: string): string;
|
| 39 |
+
openOverlay(url: URL, addHistory?: boolean): void; closeOverlay(focus?: boolean, scroll?: boolean): void; reconcile(): void;
|
| 40 |
+
}
|
| 41 |
+
declare var VoiceOfMLReaderReturn: { create(deps: ReaderReturnDependencies): ReaderReturnController };
|
| 42 |
+
declare var VoiceOfMLReaderHost: { create(deps: ReaderHostDependencies): {
|
| 43 |
+
readonly navigation: ReturnType<SearchReaderNavigationApi['createNavigation']>;
|
| 44 |
+
readonly keys: readonly string[]; readonly overlay: HTMLIFrameElement | null;
|
| 45 |
+
readonly closing: boolean; readonly uiState: string; readonly returnSnapshot: ReaderHostSnapshot | null;
|
| 46 |
+
currentReaderSearchParams(): URLSearchParams; normalizeReaderReturnUrl(raw: string): string;
|
| 47 |
+
syncReaderFolderFilter(raw: string): string;
|
| 48 |
+
closeReaderOverlay(focus?: boolean, scroll?: boolean): boolean;
|
| 49 |
+
openReaderOverlay(url: URL, addHistory?: boolean): void; reconcileSearchDestination(): void;
|
| 50 |
+
restoreReaderOverlay(state: {voiceReaderOverlay?: boolean; readerUrl?: string} | null): void;
|
| 51 |
+
handleReaderMessage(event: ReaderHostMessage): void; navigateToReader(raw: string, returnUrl?: string): boolean;
|
| 52 |
+
restoreReaderFromSession(): void;
|
| 53 |
+
} };
|