vomebook commited on
Commit ·
e9d982d
1
Parent(s): 804bf29
Improve search concurrency and demand-driven static caching
Browse files- Dockerfile +1 -1
- SITE_OPTIMIZATION_REPORT.md +34 -0
- app.py +26 -3
- scripts/build_static_assets.mjs +8 -2
- search_execution.py +60 -0
- static/sw.js +22 -65
- tests/test_fastapi_endpoints.py +2 -1
- tests/test_search_execution.py +87 -0
- tests/test_service_worker.js +73 -64
- tests/test_static_contract.py +2 -2
Dockerfile
CHANGED
|
@@ -41,7 +41,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
| 41 |
COPY requirements.txt .
|
| 42 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 43 |
|
| 44 |
-
COPY app.py data_formats.py proxy_streams.py record_metadata.py upstream_http.py .
|
| 45 |
COPY --from=static-assets /out/ static/
|
| 46 |
COPY data/ data/
|
| 47 |
COPY txt/ txt/
|
|
|
|
| 41 |
COPY requirements.txt .
|
| 42 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 43 |
|
| 44 |
+
COPY app.py data_formats.py proxy_streams.py record_metadata.py upstream_http.py search_execution.py .
|
| 45 |
COPY --from=static-assets /out/ static/
|
| 46 |
COPY data/ data/
|
| 47 |
COPY txt/ txt/
|
SITE_OPTIMIZATION_REPORT.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Site optimization acceptance — 2026-09-18
|
| 2 |
+
|
| 3 |
+
HF search computations now run in one owned thread. At most 32 jobs are admitted;
|
| 4 |
+
search caches remain serially owned, queued cancellation drops unused work, and
|
| 5 |
+
cancelling a running request does not release the computation slot early. Shutdown
|
| 6 |
+
drains owned work. Responses expose queue, search, Reader-assets and serialization
|
| 7 |
+
durations through `Server-Timing`, without queries or paths.
|
| 8 |
+
|
| 9 |
+
Paired local measurements used the checked-out 100,000-record snapshot and the exact
|
| 10 |
+
wildcard query `*文*`, alternating the previous synchronous call and the threaded API
|
| 11 |
+
three times each in one process, clearing both search caches before each call.
|
| 12 |
+
All samples returned 18,972 records in total and identical first-page result hashes.
|
| 13 |
+
These counts describe the local snapshot only.
|
| 14 |
+
|
| 15 |
+
| Median | Previous | Current |
|
| 16 |
+
| --- | ---: | ---: |
|
| 17 |
+
| Largest event-loop heartbeat interval | 1288.73 ms | 18.67 ms |
|
| 18 |
+
| Search-call duration | 1288.55 ms | 1371.55 ms |
|
| 19 |
+
|
| 20 |
+
The improvement is availability for other requests, not faster CPU search. The
|
| 21 |
+
threaded samples had modest additional elapsed time; no throughput gain is claimed.
|
| 22 |
+
HTTP tests separately confirm ping completes while a search computation is held.
|
| 23 |
+
|
| 24 |
+
The static build now pins more Reader dependencies and the app's warmup references.
|
| 25 |
+
Immutable cache hits reuse bytes without a network request. Service Worker background
|
| 26 |
+
writes retain event lifetime; quota failures preserve network responses; 206 responses
|
| 27 |
+
are excluded. Installation caches the search shell and global data only.
|
| 28 |
+
|
| 29 |
+
An actual Chromium install comparison served identical built resources with 25 ms
|
| 30 |
+
request latency and empty browser contexts. The previous SW requested 47 resources
|
| 31 |
+
(669,780 bytes); the new SW requested 16 (281,694 bytes), reducing transferred bodies
|
| 32 |
+
by 58%. Installation took 713 ms versus 279 ms in that run. This isolates SW installation,
|
| 33 |
+
not public-network page-render time. Old-cache upgrade, demand repository caching,
|
| 34 |
+
immutable reuse and offline reads passed with the fixed cache name.
|
app.py
CHANGED
|
@@ -28,6 +28,7 @@ from fastapi.middleware.gzip import GZipMiddleware
|
|
| 28 |
from pydantic import BaseModel, Field
|
| 29 |
from contextlib import asynccontextmanager
|
| 30 |
from proxy_streams import UpstreamLease
|
|
|
|
| 31 |
from data_formats import (
|
| 32 |
decode_browser_entry, decode_folder_browser_data, decode_folder_tree_data,
|
| 33 |
decode_search_payload, decode_tree_node,
|
|
@@ -1244,6 +1245,7 @@ async def warm_txt_proxy_loop(app: FastAPI):
|
|
| 1244 |
|
| 1245 |
async def lifespan(app: FastAPI):
|
| 1246 |
load_data()
|
|
|
|
| 1247 |
app.state.http_session = aiohttp.ClientSession(
|
| 1248 |
timeout=aiohttp.ClientTimeout(total=300, connect=15),
|
| 1249 |
connector=aiohttp.TCPConnector(keepalive_timeout=60, ttl_dns_cache=300),
|
|
@@ -1263,6 +1265,8 @@ async def lifespan(app: FastAPI):
|
|
| 1263 |
try:
|
| 1264 |
yield
|
| 1265 |
finally:
|
|
|
|
|
|
|
| 1266 |
app.state.download_warm_enabled = False
|
| 1267 |
if app.state.download_warm_task is not None:
|
| 1268 |
app.state.download_warm_task.cancel()
|
|
@@ -1285,7 +1289,7 @@ app.add_middleware(
|
|
| 1285 |
allow_origins=["*"],
|
| 1286 |
allow_methods=["*"],
|
| 1287 |
allow_headers=["*"],
|
| 1288 |
-
expose_headers=["Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Last-Modified"],
|
| 1289 |
)
|
| 1290 |
|
| 1291 |
@app.middleware("http")
|
|
@@ -1329,8 +1333,27 @@ async def build_search_api_response(body: SearchRequest, repos: list[str] | None
|
|
| 1329 |
params = body.model_dump(exclude={"repos"})
|
| 1330 |
for name in ("extensions", "folders", "folder_selfs", "folder_subtrees"):
|
| 1331 |
params[name] = normalize_search_list(params[name], lowercase=name == "extensions")
|
| 1332 |
-
|
| 1333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1334 |
|
| 1335 |
|
| 1336 |
@app.post("/api/search")
|
|
|
|
| 28 |
from pydantic import BaseModel, Field
|
| 29 |
from contextlib import asynccontextmanager
|
| 30 |
from proxy_streams import UpstreamLease
|
| 31 |
+
from search_execution import SearchBusy, SearchExecutor
|
| 32 |
from data_formats import (
|
| 33 |
decode_browser_entry, decode_folder_browser_data, decode_folder_tree_data,
|
| 34 |
decode_search_payload, decode_tree_node,
|
|
|
|
| 1245 |
|
| 1246 |
async def lifespan(app: FastAPI):
|
| 1247 |
load_data()
|
| 1248 |
+
app.state.search_executor = SearchExecutor()
|
| 1249 |
app.state.http_session = aiohttp.ClientSession(
|
| 1250 |
timeout=aiohttp.ClientTimeout(total=300, connect=15),
|
| 1251 |
connector=aiohttp.TCPConnector(keepalive_timeout=60, ttl_dns_cache=300),
|
|
|
|
| 1265 |
try:
|
| 1266 |
yield
|
| 1267 |
finally:
|
| 1268 |
+
await app.state.search_executor.close()
|
| 1269 |
+
del app.state.search_executor
|
| 1270 |
app.state.download_warm_enabled = False
|
| 1271 |
if app.state.download_warm_task is not None:
|
| 1272 |
app.state.download_warm_task.cancel()
|
|
|
|
| 1289 |
allow_origins=["*"],
|
| 1290 |
allow_methods=["*"],
|
| 1291 |
allow_headers=["*"],
|
| 1292 |
+
expose_headers=["Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Last-Modified", "Server-Timing"],
|
| 1293 |
)
|
| 1294 |
|
| 1295 |
@app.middleware("http")
|
|
|
|
| 1333 |
params = body.model_dump(exclude={"repos"})
|
| 1334 |
for name in ("extensions", "folders", "folder_selfs", "folder_subtrees"):
|
| 1335 |
params[name] = normalize_search_list(params[name], lowercase=name == "extensions")
|
| 1336 |
+
compute = functools.partial(search, repos=repos, **params)
|
| 1337 |
+
try:
|
| 1338 |
+
executor = getattr(app.state, "search_executor", None)
|
| 1339 |
+
if executor is None:
|
| 1340 |
+
# Direct endpoint tests without ASGI lifespan own a temporary pool.
|
| 1341 |
+
async with SearchExecutor() as executor:
|
| 1342 |
+
payload, queued_ms, search_ms = await executor.run(compute)
|
| 1343 |
+
else:
|
| 1344 |
+
payload, queued_ms, search_ms = await executor.run(compute)
|
| 1345 |
+
except SearchBusy:
|
| 1346 |
+
return JSONResponse({"error": "搜索繁忙,请稍后重试"}, status_code=503,
|
| 1347 |
+
headers={"Retry-After": "1"})
|
| 1348 |
+
started = time.perf_counter()
|
| 1349 |
+
assets = await get_reader_assets()
|
| 1350 |
+
assets_ms = (time.perf_counter() - started) * 1000
|
| 1351 |
+
started = time.perf_counter()
|
| 1352 |
+
response = JSONResponse(add_reader_assets(payload, assets))
|
| 1353 |
+
response.headers["Server-Timing"] = (
|
| 1354 |
+
f"queue;dur={queued_ms:.2f}, search;dur={search_ms:.2f}, "
|
| 1355 |
+
f"reader_assets;dur={assets_ms:.2f}, response;dur={(time.perf_counter() - started) * 1000:.2f}")
|
| 1356 |
+
return response
|
| 1357 |
|
| 1358 |
|
| 1359 |
@app.post("/api/search")
|
scripts/build_static_assets.mjs
CHANGED
|
@@ -5,9 +5,15 @@ import { extname, join } from "node:path";
|
|
| 5 |
const outputDir = process.env.STATIC_OUTPUT_DIR || "/out";
|
| 6 |
const replacements = new Map();
|
| 7 |
|
| 8 |
-
for (const filename of [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
const source = join(outputDir, filename);
|
| 10 |
-
|
| 11 |
let text = readFileSync(source, "utf8");
|
| 12 |
for (const [original, versioned] of replacements) text = text.split(original).join(versioned);
|
| 13 |
writeFileSync(source, text);
|
|
|
|
| 5 |
const outputDir = process.env.STATIC_OUTPUT_DIR || "/out";
|
| 6 |
const replacements = new Map();
|
| 7 |
|
| 8 |
+
for (const filename of [
|
| 9 |
+
"reader-chapter-search-worker.mjs", "reader-chapter-search.mjs",
|
| 10 |
+
"reader-contract.js", "reader-navigation.js", "reader-store.js",
|
| 11 |
+
"reader-request-manager.js", "reader-chapter-repository.js", "reader-scroll-anchor.js",
|
| 12 |
+
"reader-section-virtualizer.js", "reader-runtime.js", "reader-format-adapters.js",
|
| 13 |
+
"reader-security.js", "pdf-worker-wrapper.mjs", "style.css", "reader.css", "reader.js", "app.js"
|
| 14 |
+
]) {
|
| 15 |
const source = join(outputDir, filename);
|
| 16 |
+
{
|
| 17 |
let text = readFileSync(source, "utf8");
|
| 18 |
for (const [original, versioned] of replacements) text = text.split(original).join(versioned);
|
| 19 |
writeFileSync(source, text);
|
search_execution.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One owned search thread; cancellation never releases an active computation."""
|
| 2 |
+
import asyncio
|
| 3 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SearchBusy(Exception):
|
| 8 |
+
pass
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SearchExecutor:
|
| 12 |
+
def __init__(self, capacity=32):
|
| 13 |
+
self.capacity = capacity
|
| 14 |
+
self._pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="search")
|
| 15 |
+
self._lock = asyncio.Lock()
|
| 16 |
+
self._tasks = set()
|
| 17 |
+
self._closing = False
|
| 18 |
+
|
| 19 |
+
async def __aenter__(self):
|
| 20 |
+
return self
|
| 21 |
+
|
| 22 |
+
async def __aexit__(self, *args):
|
| 23 |
+
await self.close()
|
| 24 |
+
|
| 25 |
+
async def run(self, function):
|
| 26 |
+
if self._closing or len(self._tasks) >= self.capacity:
|
| 27 |
+
raise SearchBusy()
|
| 28 |
+
job = {"started": False}
|
| 29 |
+
queued = time.perf_counter()
|
| 30 |
+
|
| 31 |
+
def compute():
|
| 32 |
+
started = time.perf_counter()
|
| 33 |
+
result = function()
|
| 34 |
+
return result, (started - queued) * 1000, (time.perf_counter() - started) * 1000
|
| 35 |
+
|
| 36 |
+
async def execute():
|
| 37 |
+
async with self._lock:
|
| 38 |
+
job["started"] = True
|
| 39 |
+
return await asyncio.get_running_loop().run_in_executor(self._pool, compute)
|
| 40 |
+
|
| 41 |
+
task = asyncio.create_task(execute())
|
| 42 |
+
self._tasks.add(task)
|
| 43 |
+
|
| 44 |
+
def finished(done):
|
| 45 |
+
self._tasks.discard(done)
|
| 46 |
+
if not done.cancelled():
|
| 47 |
+
done.exception() # Consume failures when the requester has left.
|
| 48 |
+
|
| 49 |
+
task.add_done_callback(finished)
|
| 50 |
+
try:
|
| 51 |
+
return await asyncio.shield(task)
|
| 52 |
+
except asyncio.CancelledError:
|
| 53 |
+
if not job["started"]:
|
| 54 |
+
task.cancel() # Queued work has no side effects and can be dropped.
|
| 55 |
+
raise
|
| 56 |
+
|
| 57 |
+
async def close(self):
|
| 58 |
+
self._closing = True
|
| 59 |
+
await asyncio.gather(*self._tasks, return_exceptions=True)
|
| 60 |
+
self._pool.shutdown(wait=True)
|
static/sw.js
CHANGED
|
@@ -5,20 +5,11 @@ const PRECACHE_URLS = [
|
|
| 5 |
"/static/style.css",
|
| 6 |
"/static/reader-contract.js",
|
| 7 |
"/static/reader-navigation.js",
|
| 8 |
-
"/static/reader-store.js",
|
| 9 |
-
"/static/reader-request-manager.js",
|
| 10 |
-
"/static/reader-chapter-repository.js",
|
| 11 |
-
"/static/reader-scroll-anchor.js",
|
| 12 |
-
"/static/reader-section-virtualizer.js",
|
| 13 |
-
"/static/reader-runtime.js",
|
| 14 |
-
"/static/reader-format-adapters.js",
|
| 15 |
-
"/static/reader-security.js",
|
| 16 |
-
"/static/reader.html",
|
| 17 |
-
"/static/reader.css",
|
| 18 |
-
"/static/reader.js",
|
| 19 |
"/static/app.js",
|
| 20 |
"/data/initial/manifest.json",
|
| 21 |
"/data/sidebar/manifest.json",
|
|
|
|
|
|
|
| 22 |
"/manifest.json",
|
| 23 |
"/icons/logo.svg",
|
| 24 |
"/icons/logo-dark.svg",
|
|
@@ -42,22 +33,11 @@ const READER_RUNTIME_PATHS = new Set([
|
|
| 42 |
"/static/reader.css",
|
| 43 |
"/static/reader.js"
|
| 44 |
]);
|
| 45 |
-
function precacheManifest(cache, url) {
|
| 46 |
-
return fetch(url)
|
| 47 |
-
.then(response => response.ok ? response.json() : null)
|
| 48 |
-
.then(manifest => {
|
| 49 |
-
if (manifest && Array.isArray(manifest.urls)) return cache.addAll(manifest.urls);
|
| 50 |
-
})
|
| 51 |
-
.catch(() => {});
|
| 52 |
-
}
|
| 53 |
|
| 54 |
self.addEventListener("install", (event) => {
|
| 55 |
event.waitUntil(
|
| 56 |
caches.open(CACHE_NAME).then((cache) => {
|
| 57 |
-
return cache.addAll(PRECACHE_URLS).
|
| 58 |
-
precacheManifest(cache, "/data/initial/manifest.json"),
|
| 59 |
-
precacheManifest(cache, "/data/sidebar/manifest.json")
|
| 60 |
-
])).catch((err) => {
|
| 61 |
console.warn("[SW] precache partial failure:", err);
|
| 62 |
});
|
| 63 |
}).then(() => self.skipWaiting())
|
|
@@ -74,7 +54,7 @@ self.addEventListener("activate", (event) => {
|
|
| 74 |
});
|
| 75 |
self.addEventListener("fetch", (event) => {
|
| 76 |
const url = new URL(event.request.url);
|
| 77 |
-
if (url.hostname !== self.location.hostname) {
|
| 78 |
return;
|
| 79 |
}
|
| 80 |
if (url.pathname.startsWith("/api/")) {
|
|
@@ -83,47 +63,24 @@ self.addEventListener("fetch", (event) => {
|
|
| 83 |
if (url.pathname.startsWith("/txt/")) {
|
| 84 |
return;
|
| 85 |
}
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
event.respondWith(
|
| 89 |
-
caches.open(CACHE_NAME).then((cache) => cache.match(cacheKey).then((cached) =>
|
| 90 |
-
fetch(event.request).then((response) => {
|
| 91 |
-
if (response.ok) cache.put(cacheKey, response.clone());
|
| 92 |
-
return response.ok || !cached ? response : cached;
|
| 93 |
-
}).catch(() => cached)
|
| 94 |
-
))
|
| 95 |
-
);
|
| 96 |
-
return;
|
| 97 |
-
}
|
| 98 |
-
if (event.request.mode === "navigate") {
|
| 99 |
return;
|
| 100 |
}
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
const fetchPromise = fetch(event.request).then((response) => {
|
| 118 |
-
if (response.ok && response.status !== 206) {
|
| 119 |
-
const clone = response.clone();
|
| 120 |
-
caches.open(CACHE_NAME).then((cache) => {
|
| 121 |
-
cache.put(event.request, clone);
|
| 122 |
-
});
|
| 123 |
-
}
|
| 124 |
-
return response;
|
| 125 |
-
}).catch(() => cached);
|
| 126 |
-
return cached || fetchPromise;
|
| 127 |
-
})
|
| 128 |
-
);
|
| 129 |
});
|
|
|
|
| 5 |
"/static/style.css",
|
| 6 |
"/static/reader-contract.js",
|
| 7 |
"/static/reader-navigation.js",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"/static/app.js",
|
| 9 |
"/data/initial/manifest.json",
|
| 10 |
"/data/sidebar/manifest.json",
|
| 11 |
+
"/data/initial/global.json",
|
| 12 |
+
"/data/sidebar/global.json",
|
| 13 |
"/manifest.json",
|
| 14 |
"/icons/logo.svg",
|
| 15 |
"/icons/logo-dark.svg",
|
|
|
|
| 33 |
"/static/reader.css",
|
| 34 |
"/static/reader.js"
|
| 35 |
]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
self.addEventListener("install", (event) => {
|
| 38 |
event.waitUntil(
|
| 39 |
caches.open(CACHE_NAME).then((cache) => {
|
| 40 |
+
return cache.addAll(PRECACHE_URLS).catch((err) => {
|
|
|
|
|
|
|
|
|
|
| 41 |
console.warn("[SW] precache partial failure:", err);
|
| 42 |
});
|
| 43 |
}).then(() => self.skipWaiting())
|
|
|
|
| 54 |
});
|
| 55 |
self.addEventListener("fetch", (event) => {
|
| 56 |
const url = new URL(event.request.url);
|
| 57 |
+
if (url.hostname !== self.location.hostname || (event.request.method || "GET") !== "GET") {
|
| 58 |
return;
|
| 59 |
}
|
| 60 |
if (url.pathname.startsWith("/api/")) {
|
|
|
|
| 63 |
if (url.pathname.startsWith("/txt/")) {
|
| 64 |
return;
|
| 65 |
}
|
| 66 |
+
const readerNavigation = event.request.mode === "navigate" && url.pathname === "/static/reader.html";
|
| 67 |
+
if (event.request.mode === "navigate" && !readerNavigation) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
return;
|
| 69 |
}
|
| 70 |
+
const networkFirst = readerNavigation || READER_RUNTIME_PATHS.has(url.pathname);
|
| 71 |
+
const cacheKey = readerNavigation ? "/static/reader.html" : event.request;
|
| 72 |
+
const cachePromise = caches.open(CACHE_NAME).catch(() => null);
|
| 73 |
+
const cachedPromise = cachePromise.then(cache => cache ? cache.match(cacheKey) : undefined).catch(() => undefined);
|
| 74 |
+
const immutable = /\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url.pathname);
|
| 75 |
+
let cacheWrite;
|
| 76 |
+
const networkPromise = Promise.all([cachePromise, immutable ? cachedPromise : null]).then(([cache, cached]) => cached || fetch(event.request).then(response => {
|
| 77 |
+
if (cache && response.ok && response.status !== 206) {
|
| 78 |
+
cacheWrite = cache.put(cacheKey, response.clone()).catch(() => {});
|
| 79 |
+
}
|
| 80 |
+
return response;
|
| 81 |
+
}));
|
| 82 |
+
event.waitUntil(networkPromise.then(() => cacheWrite).catch(() => {}));
|
| 83 |
+
event.respondWith(networkFirst
|
| 84 |
+
? networkPromise.then(response => response.ok ? response : cachedPromise.then(cached => cached || response)).catch(() => cachedPromise)
|
| 85 |
+
: cachedPromise.then(cached => cached || networkPromise.catch(() => cached)));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
});
|
tests/test_fastapi_endpoints.py
CHANGED
|
@@ -38,7 +38,8 @@ class FastApiEndpointTests(unittest.TestCase):
|
|
| 38 |
response = self.client.post("/api/search", json={"q": "readme", "page_size": 1})
|
| 39 |
self.assertEqual(response.status_code, 200)
|
| 40 |
self.assertEqual(response.json()["total"], 1)
|
| 41 |
-
self.
|
|
|
|
| 42 |
|
| 43 |
def test_search_endpoint_rejects_malformed_json(self):
|
| 44 |
self.assertEqual(self.client.post("/api/search", content="not-json", headers={"content-type": "application/json"}).status_code, 422)
|
|
|
|
| 38 |
response = self.client.post("/api/search", json={"q": "readme", "page_size": 1})
|
| 39 |
self.assertEqual(response.status_code, 200)
|
| 40 |
self.assertEqual(response.json()["total"], 1)
|
| 41 |
+
self.assertRegex(response.headers["server-timing"], r"queue;dur=\d+\.\d+, search;dur=\d+\.\d+")
|
| 42 |
+
self.assertNotIn("readme", response.headers["server-timing"])
|
| 43 |
|
| 44 |
def test_search_endpoint_rejects_malformed_json(self):
|
| 45 |
self.assertEqual(self.client.post("/api/search", content="not-json", headers={"content-type": "application/json"}).status_code, 422)
|
tests/test_search_execution.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import threading
|
| 3 |
+
import unittest
|
| 4 |
+
from search_execution import SearchBusy, SearchExecutor
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SearchExecutionTests(unittest.IsolatedAsyncioTestCase):
|
| 8 |
+
async def test_slow_search_does_not_block_http_ping_and_busy_requests_retry(self):
|
| 9 |
+
import app
|
| 10 |
+
import httpx
|
| 11 |
+
from unittest.mock import patch, AsyncMock
|
| 12 |
+
started, release = threading.Event(), threading.Event()
|
| 13 |
+
def slow(**params):
|
| 14 |
+
started.set()
|
| 15 |
+
release.wait(2)
|
| 16 |
+
return dict(results=[], total=0, page=1, page_size=100)
|
| 17 |
+
async with SearchExecutor(capacity=1) as executor:
|
| 18 |
+
with patch.object(app.app.state, 'search_executor', executor, create=True), \
|
| 19 |
+
patch.object(app, 'search', slow), \
|
| 20 |
+
patch.object(app, 'get_reader_assets', AsyncMock(return_value={'v': 1, 'f': {}})):
|
| 21 |
+
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app.app), base_url='http://test') as client:
|
| 22 |
+
search = asyncio.create_task(client.post('/api/search', json={'q': 'query'}))
|
| 23 |
+
try:
|
| 24 |
+
self.assertTrue(await asyncio.to_thread(started.wait, 1))
|
| 25 |
+
ping = await asyncio.wait_for(client.get('/api/ping'), .5)
|
| 26 |
+
self.assertEqual(ping.status_code, 204)
|
| 27 |
+
self.assertFalse(search.done())
|
| 28 |
+
busy = await client.post('/api/search', json={})
|
| 29 |
+
self.assertEqual(busy.status_code, 503)
|
| 30 |
+
self.assertEqual(busy.headers['retry-after'], '1')
|
| 31 |
+
finally:
|
| 32 |
+
release.set()
|
| 33 |
+
response = await search
|
| 34 |
+
self.assertEqual(response.status_code, 200)
|
| 35 |
+
self.assertIn('reader_assets;dur=', response.headers['server-timing'])
|
| 36 |
+
|
| 37 |
+
async def test_active_cancellation_retains_slot_and_queued_cancellation_drops_work(self):
|
| 38 |
+
started, release = threading.Event(), threading.Event()
|
| 39 |
+
seen = []
|
| 40 |
+
def slow():
|
| 41 |
+
started.set()
|
| 42 |
+
release.wait(2)
|
| 43 |
+
seen.append('first')
|
| 44 |
+
return 1
|
| 45 |
+
async with SearchExecutor(capacity=3) as executor:
|
| 46 |
+
first = asyncio.create_task(executor.run(slow))
|
| 47 |
+
try:
|
| 48 |
+
self.assertTrue(await asyncio.to_thread(started.wait, 1))
|
| 49 |
+
first.cancel()
|
| 50 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 51 |
+
await first
|
| 52 |
+
queued = asyncio.create_task(executor.run(lambda: seen.append('cancelled')))
|
| 53 |
+
await asyncio.sleep(0)
|
| 54 |
+
queued.cancel()
|
| 55 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 56 |
+
await queued
|
| 57 |
+
next_job = asyncio.create_task(executor.run(lambda: seen.append('next') or 2))
|
| 58 |
+
await asyncio.sleep(.02)
|
| 59 |
+
self.assertFalse(next_job.done())
|
| 60 |
+
self.assertEqual(seen, [])
|
| 61 |
+
finally:
|
| 62 |
+
release.set()
|
| 63 |
+
self.assertEqual((await next_job)[0], 2)
|
| 64 |
+
self.assertEqual(seen, ['first', 'next'])
|
| 65 |
+
|
| 66 |
+
async def test_capacity_failure_and_recovery(self):
|
| 67 |
+
started, release = threading.Event(), threading.Event()
|
| 68 |
+
def slow():
|
| 69 |
+
started.set()
|
| 70 |
+
release.wait(2)
|
| 71 |
+
async with SearchExecutor(capacity=1) as executor:
|
| 72 |
+
active = asyncio.create_task(executor.run(slow))
|
| 73 |
+
try:
|
| 74 |
+
self.assertTrue(await asyncio.to_thread(started.wait, 1))
|
| 75 |
+
with self.assertRaises(SearchBusy):
|
| 76 |
+
await executor.run(lambda: None)
|
| 77 |
+
finally:
|
| 78 |
+
release.set()
|
| 79 |
+
await active
|
| 80 |
+
with self.assertRaisesRegex(ValueError, 'failure'):
|
| 81 |
+
await executor.run(lambda: (_ for _ in ()).throw(ValueError('failure')))
|
| 82 |
+
value, queue, compute = await executor.run(lambda: 42)
|
| 83 |
+
self.assertEqual(value, 42)
|
| 84 |
+
self.assertGreaterEqual(queue, 0)
|
| 85 |
+
self.assertGreaterEqual(compute, 0)
|
| 86 |
+
with self.assertRaises(SearchBusy):
|
| 87 |
+
await executor.run(lambda: None)
|
tests/test_service_worker.js
CHANGED
|
@@ -1,73 +1,82 @@
|
|
| 1 |
const assert = require('assert');
|
| 2 |
const fs = require('fs');
|
| 3 |
const vm = require('vm');
|
| 4 |
-
const
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
const events = {}, added = [], deleted = [], requests = [];
|
| 12 |
-
const cache = {addAll: async urls => {
|
| 13 |
-
added.push([...urls]);
|
| 14 |
-
if (failure === 'core' && urls.includes('/')) throw Error('core');
|
| 15 |
-
if (failure === 'payload' && urls.includes('/initial-payload')) throw Error('payload');
|
| 16 |
-
}};
|
| 17 |
-
let waiting = 0, claimed = 0;
|
| 18 |
vm.runInNewContext(source, {
|
| 19 |
-
URL, Set, console:{warn(){}},
|
| 20 |
-
self:{location:{hostname:'localhost'}, addEventListener:(name, fn)=>events[name]=fn,
|
| 21 |
-
skipWaiting
|
| 22 |
-
caches:{open:
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
| 30 |
},
|
| 31 |
});
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
if (failure==='core') assert.strictEqual(requests.length,0);
|
| 38 |
-
else {
|
| 39 |
-
assert.strictEqual(requests.length,2);
|
| 40 |
-
assert.ok(added.some(urls=>urls.includes('/sidebar-payload')));
|
| 41 |
-
assert.strictEqual(added.some(urls=>urls.includes('/initial-payload')), !['network','status','invalid'].includes(failure));
|
| 42 |
-
}
|
| 43 |
-
events.activate({waitUntil:value=>completion=value});
|
| 44 |
-
await completion;
|
| 45 |
-
assert.deepStrictEqual(deleted,['old-cache']);
|
| 46 |
-
assert.strictEqual(claimed,1);
|
| 47 |
-
for(const [url,mode] of [['https://other.test/static/app.js','cors'], ['https://localhost/api/search','cors'],
|
| 48 |
-
['https://localhost/txt/book.txt','cors'], ['https://localhost/Teachers','navigate']]) {
|
| 49 |
-
events.fetch({request:{url,mode},respondWith(){throw Error('unexpected interception: '+url)}});
|
| 50 |
}
|
|
|
|
| 51 |
}
|
| 52 |
-
async
|
| 53 |
-
const
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
}
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
(
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
const assert = require('assert');
|
| 2 |
const fs = require('fs');
|
| 3 |
const vm = require('vm');
|
| 4 |
+
const source = fs.readFileSync('static/sw.js', 'utf8');
|
| 5 |
+
function response(version, status = 200) {
|
| 6 |
+
return {version, status, ok: status >= 200 && status < 300, clone() { return this; }};
|
| 7 |
+
}
|
| 8 |
+
function harness({cached, fetchError, openError, put, fetch: network} = {}) {
|
| 9 |
+
const events = {}, writes = [], fetched = [], added = [], lifetimes = [];
|
| 10 |
+
const fresh = response('new');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
vm.runInNewContext(source, {
|
| 12 |
+
URL, Set, console: {warn() {}},
|
| 13 |
+
self: {location: {hostname: 'localhost'}, addEventListener: (name, fn) => events[name] = fn,
|
| 14 |
+
skipWaiting() {}, clients: {claim() {}}},
|
| 15 |
+
caches: {open: async () => {
|
| 16 |
+
if (openError) throw Error('storage');
|
| 17 |
+
return {match: async () => cached, addAll: async urls => added.push([...urls]),
|
| 18 |
+
put: (key, value) => {writes.push(value); return put ? put() : Promise.resolve();}};
|
| 19 |
+
}, keys: async () => ['voiceofml-search-hf-v1.0.0'], delete: async () => {}},
|
| 20 |
+
fetch: async request => {
|
| 21 |
+
fetched.push(request);
|
| 22 |
+
if (fetchError) throw Error('offline');
|
| 23 |
+
return network ? network() : fresh;
|
| 24 |
},
|
| 25 |
});
|
| 26 |
+
function dispatch(path, mode = 'cors', method = 'GET') {
|
| 27 |
+
let result;
|
| 28 |
+
events.fetch({request: {url: 'https://localhost' + path, mode, method},
|
| 29 |
+
respondWith: promise => result = promise, waitUntil: promise => lifetimes.push(promise)});
|
| 30 |
+
return result;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
}
|
| 32 |
+
return {events, writes, fetched, added, lifetimes, fresh, dispatch};
|
| 33 |
}
|
| 34 |
+
(async () => {
|
| 35 |
+
const install = harness();
|
| 36 |
+
let installed;
|
| 37 |
+
install.events.install({waitUntil: promise => installed = promise});
|
| 38 |
+
await installed;
|
| 39 |
+
assert.strictEqual(install.added.length, 1);
|
| 40 |
+
assert.ok(install.added[0].includes('/data/initial/global.json'));
|
| 41 |
+
assert.ok(!install.added[0].some(url => /\/repos\/|\/reader\.(?:js|html|css)$/.test(url)));
|
| 42 |
+
assert.strictEqual(install.fetched.length, 0);
|
| 43 |
+
for (const path of ['/api/search', '/txt/book.txt', '/Teachers'])
|
| 44 |
+
assert.strictEqual(install.dispatch(path, path === '/Teachers' ? 'navigate' : 'cors'), undefined);
|
| 45 |
+
assert.strictEqual(install.dispatch('/static/app.js', 'cors', 'POST'), undefined);
|
| 46 |
+
for (const path of ['/data/initial/global.json', '/data/sidebar/global.json', '/static/app.js']) {
|
| 47 |
+
let releaseNetwork, releaseWrite, done = false;
|
| 48 |
+
const old = response('old');
|
| 49 |
+
const h = harness({cached: old, fetch: () => new Promise(resolve => releaseNetwork = resolve),
|
| 50 |
+
put: () => new Promise(resolve => releaseWrite = resolve)});
|
| 51 |
+
assert.strictEqual(await h.dispatch(path), old);
|
| 52 |
+
h.lifetimes[0].then(() => done = true);
|
| 53 |
+
releaseNetwork(response('new'));
|
| 54 |
+
await new Promise(resolve => setTimeout(resolve, 0));
|
| 55 |
+
assert.strictEqual(done, false);
|
| 56 |
+
releaseWrite();
|
| 57 |
+
await h.lifetimes[0];
|
| 58 |
+
assert.strictEqual(done, true);
|
| 59 |
}
|
| 60 |
+
for (const options of [{openError: true}, {put: () => Promise.reject(Error('quota'))}]) {
|
| 61 |
+
const h = harness(options);
|
| 62 |
+
assert.strictEqual(await h.dispatch('/static/reader.js'), h.fresh);
|
| 63 |
+
await Promise.all(h.lifetimes);
|
| 64 |
+
}
|
| 65 |
+
for (const path of ['/static/reader.js', '/data/initial/global.json']) {
|
| 66 |
+
const h = harness({fetch: () => response('partial', 206)});
|
| 67 |
+
assert.strictEqual((await h.dispatch(path)).status, 206);
|
| 68 |
+
await Promise.all(h.lifetimes);
|
| 69 |
+
assert.strictEqual(h.writes.length, 0);
|
| 70 |
+
}
|
| 71 |
+
for (const path of ['/static/reader-chapter-search.mjs', '/static/reader-chapter-search-worker.mjs']) {
|
| 72 |
+
const h = harness({cached: response('old')});
|
| 73 |
+
assert.strictEqual(await h.dispatch(path), h.fresh);
|
| 74 |
+
await Promise.all(h.lifetimes);
|
| 75 |
+
assert.strictEqual(h.writes.length, 1);
|
| 76 |
+
}
|
| 77 |
+
const pinned = harness({cached: response('pinned')});
|
| 78 |
+
assert.strictEqual((await pinned.dispatch('/static/app.0123456789ab.js')).version, 'pinned');
|
| 79 |
+
await Promise.all(pinned.lifetimes);
|
| 80 |
+
assert.strictEqual(pinned.fetched.length, 0);
|
| 81 |
+
console.log('HF Service Worker: demand caching, immutable reuse, write lifetime, storage errors and bypass passed');
|
| 82 |
+
})().catch(error => {console.error(error); process.exitCode = 1;});
|
tests/test_static_contract.py
CHANGED
|
@@ -492,8 +492,8 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 492 |
def test_reader_runtime_is_network_first_with_one_navigation_cache_key(self):
|
| 493 |
self.assertIn('event.request.mode === "navigate" && url.pathname === "/static/reader.html"', self.sw)
|
| 494 |
self.assertIn('READER_RUNTIME_PATHS.has(url.pathname)', self.sw)
|
| 495 |
-
self.assertIn('cacheKey =
|
| 496 |
-
self.assertIn('
|
| 497 |
self.assertIn('cache.put(cacheKey, response.clone())', self.sw)
|
| 498 |
|
| 499 |
def test_manifest_is_valid_and_scoped(self):
|
|
|
|
| 492 |
def test_reader_runtime_is_network_first_with_one_navigation_cache_key(self):
|
| 493 |
self.assertIn('event.request.mode === "navigate" && url.pathname === "/static/reader.html"', self.sw)
|
| 494 |
self.assertIn('READER_RUNTIME_PATHS.has(url.pathname)', self.sw)
|
| 495 |
+
self.assertIn('cacheKey = readerNavigation ? "/static/reader.html" : event.request', self.sw)
|
| 496 |
+
self.assertIn('event.waitUntil(networkPromise.then(() => cacheWrite)', self.sw)
|
| 497 |
self.assertIn('cache.put(cacheKey, response.clone())', self.sw)
|
| 498 |
|
| 499 |
def test_manifest_is_valid_and_scoped(self):
|