vomebook commited on
Commit ·
e9d982d
1
Parent(s): 804bf29
Improve search concurrency and demand-driven static caching
Browse filesFiles changed (10)
- Dockerfile+1-1
- SITE_OPTIMIZATION_REPORT.mdAdded+34
- app.py+26-3
- scripts/build_static_assets.mjs+8-2
- search_execution.pyAdded+60
- static/sw.js+22-65
- tests/test_fastapi_endpoints.py+2-1
- tests/test_search_execution.pyAdded+87
- tests/test_service_worker.js+73-64
- tests/test_static_contract.py+2-2
40 unmodified lines4142434445464740 unmodified linesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY app.py data_formats.py proxy_streams.py record_metadata.py upstream_http.py .COPY --from=static-assets /out/ static/COPY data/ data/COPY txt/ txt/40 unmodified lines4142434445464740 unmodified linesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY app.py data_formats.py proxy_streams.py record_metadata.py upstream_http.py search_execution.py .COPY --from=static-assets /out/ static/COPY data/ data/COPY txt/ txt/
12345678910111213141516171819202122232425262728293031323334# Site optimization acceptance — 2026-09-18
HF search computations now run in one owned thread. At most 32 jobs are admitted;search caches remain serially owned, queued cancellation drops unused work, andcancelling a running request does not release the computation slot early. Shutdowndrains owned work. Responses expose queue, search, Reader-assets and serializationdurations through `Server-Timing`, without queries or paths.
Paired local measurements used the checked-out 100,000-record snapshot and the exactwildcard query `*文*`, alternating the previous synchronous call and the threaded APIthree times each in one process, clearing both search caches before each call.All samples returned 18,972 records in total and identical first-page result hashes.These counts describe the local snapshot only.
| Median | Previous | Current || --- | ---: | ---: || Largest event-loop heartbeat interval | 1288.73 ms | 18.67 ms || Search-call duration | 1288.55 ms | 1371.55 ms |
The improvement is availability for other requests, not faster CPU search. Thethreaded samples had modest additional elapsed time; no throughput gain is claimed.HTTP tests separately confirm ping completes while a search computation is held.
The static build now pins more Reader dependencies and the app's warmup references.Immutable cache hits reuse bytes without a network request. Service Worker backgroundwrites retain event lifetime; quota failures preserve network responses; 206 responsesare excluded. Installation caches the search shell and global data only.
An actual Chromium install comparison served identical built resources with 25 msrequest latency and empty browser contexts. The previous SW requested 47 resources(669,780 bytes); the new SW requested 16 (281,694 bytes), reducing transferred bodiesby 58%. Installation took 713 ms versus 279 ms in that run. This isolates SW installation,not public-network page-render time. Old-cache upgrade, demand repository caching,immutable reuse and offline reads passed with the fixed cache name.27 unmodified lines2829303132331210 unmodified lines12441245124612471248124913 unmodified lines12631264126512661267126816 unmodified lines128512861287128812891290129137 unmodified lines1329133013311332133313341335133627 unmodified linesfrom pydantic import BaseModel, Fieldfrom contextlib import asynccontextmanagerfrom proxy_streams import UpstreamLeasefrom data_formats import (decode_browser_entry, decode_folder_browser_data, decode_folder_tree_data,decode_search_payload, decode_tree_node,1210 unmodified linesasync def lifespan(app: FastAPI):load_data()app.state.http_session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=300, connect=15),connector=aiohttp.TCPConnector(keepalive_timeout=60, ttl_dns_cache=300),13 unmodified linestry:yieldfinally:app.state.download_warm_enabled = Falseif app.state.download_warm_task is not None:app.state.download_warm_task.cancel()16 unmodified linesallow_origins=["*"],allow_methods=["*"],allow_headers=["*"],expose_headers=["Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Last-Modified"],)@app.middleware("http")37 unmodified linesparams = body.model_dump(exclude={"repos"})for name in ("extensions", "folders", "folder_selfs", "folder_subtrees"):params[name] = normalize_search_list(params[name], lowercase=name == "extensions")payload = search(repos=repos, **params)return JSONResponse(add_reader_assets(payload, await get_reader_assets()))@app.post("/api/search")27 unmodified lines282930313233341210 unmodified lines124512461247124812491250125113 unmodified lines1265126612671268126912701271127216 unmodified lines128912901291129212931294129537 unmodified lines13331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135927 unmodified linesfrom pydantic import BaseModel, Fieldfrom contextlib import asynccontextmanagerfrom proxy_streams import UpstreamLeasefrom search_execution import SearchBusy, SearchExecutorfrom data_formats import (decode_browser_entry, decode_folder_browser_data, decode_folder_tree_data,decode_search_payload, decode_tree_node,1210 unmodified linesasync def lifespan(app: FastAPI):load_data()app.state.search_executor = SearchExecutor()app.state.http_session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=300, connect=15),connector=aiohttp.TCPConnector(keepalive_timeout=60, ttl_dns_cache=300),13 unmodified linestry:yieldfinally:await app.state.search_executor.close()del app.state.search_executorapp.state.download_warm_enabled = Falseif app.state.download_warm_task is not None:app.state.download_warm_task.cancel()16 unmodified linesallow_origins=["*"],allow_methods=["*"],allow_headers=["*"],expose_headers=["Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Last-Modified", "Server-Timing"],)@app.middleware("http")37 unmodified linesparams = body.model_dump(exclude={"repos"})for name in ("extensions", "folders", "folder_selfs", "folder_subtrees"):params[name] = normalize_search_list(params[name], lowercase=name == "extensions")compute = functools.partial(search, repos=repos, **params)try:executor = getattr(app.state, "search_executor", None)if executor is None:# Direct endpoint tests without ASGI lifespan own a temporary pool.async with SearchExecutor() as executor:payload, queued_ms, search_ms = await executor.run(compute)else:payload, queued_ms, search_ms = await executor.run(compute)except SearchBusy:return JSONResponse({"error": "搜索繁忙,请稍后重试"}, status_code=503,headers={"Retry-After": "1"})started = time.perf_counter()assets = await get_reader_assets()assets_ms = (time.perf_counter() - started) * 1000started = time.perf_counter()response = JSONResponse(add_reader_assets(payload, assets))response.headers["Server-Timing"] = (f"queue;dur={queued_ms:.2f}, search;dur={search_ms:.2f}, "f"reader_assets;dur={assets_ms:.2f}, response;dur={(time.perf_counter() - started) * 1000:.2f}")return response@app.post("/api/search")
4 unmodified lines56789101112134 unmodified linesconst outputDir = process.env.STATIC_OUTPUT_DIR || "/out";const replacements = new Map();for (const filename of ["reader-chapter-search-worker.mjs", "reader-chapter-search.mjs", "app.js", "style.css", "reader-contract.js", "reader-navigation.js", "reader-store.js", "reader.js", "reader.css"]) {const source = join(outputDir, filename);if (["reader-chapter-search.mjs", "reader.js"].includes(filename)) {let text = readFileSync(source, "utf8");for (const [original, versioned] of replacements) text = text.split(original).join(versioned);writeFileSync(source, text);4 unmodified lines56789101112131415161718194 unmodified linesconst outputDir = process.env.STATIC_OUTPUT_DIR || "/out";const replacements = new Map();for (const filename of ["reader-chapter-search-worker.mjs", "reader-chapter-search.mjs","reader-contract.js", "reader-navigation.js", "reader-store.js","reader-request-manager.js", "reader-chapter-repository.js", "reader-scroll-anchor.js","reader-section-virtualizer.js", "reader-runtime.js", "reader-format-adapters.js","reader-security.js", "pdf-worker-wrapper.mjs", "style.css", "reader.css", "reader.js", "app.js"]) {const source = join(outputDir, filename);{let text = readFileSync(source, "utf8");for (const [original, versioned] of replacements) text = text.split(original).join(versioned);writeFileSync(source, text);
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""One owned search thread; cancellation never releases an active computation."""import asynciofrom concurrent.futures import ThreadPoolExecutorimport time
class SearchBusy(Exception): pass
class SearchExecutor: def __init__(self, capacity=32): self.capacity = capacity self._pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="search") self._lock = asyncio.Lock() self._tasks = set() self._closing = False
async def __aenter__(self): return self
async def __aexit__(self, *args): await self.close()
async def run(self, function): if self._closing or len(self._tasks) >= self.capacity: raise SearchBusy() job = {"started": False} queued = time.perf_counter()
def compute(): started = time.perf_counter() result = function() return result, (started - queued) * 1000, (time.perf_counter() - started) * 1000
async def execute(): async with self._lock: job["started"] = True return await asyncio.get_running_loop().run_in_executor(self._pool, compute)
task = asyncio.create_task(execute()) self._tasks.add(task)
def finished(done): self._tasks.discard(done) if not done.cancelled(): done.exception() # Consume failures when the requester has left.
task.add_done_callback(finished) try: return await asyncio.shield(task) except asyncio.CancelledError: if not job["started"]: task.cancel() # Queued work has no side effects and can be dropped. raise
async def close(self): self._closing = True await asyncio.gather(*self._tasks, return_exceptions=True) self._pool.shutdown(wait=True)4 unmodified lines5678910111213141516171819202122232417 unmodified lines4243444546474849505152535455565758596061626310 unmodified lines747576777879802 unmodified lines83848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281294 unmodified lines"/static/style.css","/static/reader-contract.js","/static/reader-navigation.js","/static/reader-store.js","/static/reader-request-manager.js","/static/reader-chapter-repository.js","/static/reader-scroll-anchor.js","/static/reader-section-virtualizer.js","/static/reader-runtime.js","/static/reader-format-adapters.js","/static/reader-security.js","/static/reader.html","/static/reader.css","/static/reader.js","/static/app.js","/data/initial/manifest.json","/data/sidebar/manifest.json","/manifest.json","/icons/logo.svg","/icons/logo-dark.svg",17 unmodified lines"/static/reader.css","/static/reader.js"]);function precacheManifest(cache, url) {return fetch(url).then(response => response.ok ? response.json() : null).then(manifest => {if (manifest && Array.isArray(manifest.urls)) return cache.addAll(manifest.urls);}).catch(() => {});}self.addEventListener("install", (event) => {event.waitUntil(caches.open(CACHE_NAME).then((cache) => {return cache.addAll(PRECACHE_URLS).then(() => Promise.all([precacheManifest(cache, "/data/initial/manifest.json"),precacheManifest(cache, "/data/sidebar/manifest.json")])).catch((err) => {console.warn("[SW] precache partial failure:", err);});}).then(() => self.skipWaiting())10 unmodified lines});self.addEventListener("fetch", (event) => {const url = new URL(event.request.url);if (url.hostname !== self.location.hostname) {return;}if (url.pathname.startsWith("/api/")) {2 unmodified linesif (url.pathname.startsWith("/txt/")) {return;}if ((event.request.mode === "navigate" && url.pathname === "/static/reader.html") || READER_RUNTIME_PATHS.has(url.pathname)) {const cacheKey = event.request.mode === "navigate" ? "/static/reader.html" : event.request;event.respondWith(caches.open(CACHE_NAME).then((cache) => cache.match(cacheKey).then((cached) =>fetch(event.request).then((response) => {if (response.ok) cache.put(cacheKey, response.clone());return response.ok || !cached ? response : cached;}).catch(() => cached))));return;}if (event.request.mode === "navigate") {return;}if ((url.pathname.startsWith("/data/initial/") || url.pathname.startsWith("/data/sidebar/")) && url.pathname.endsWith(".json")) {event.respondWith(caches.open(CACHE_NAME).then((cache) => {return cache.match(event.request).then((cached) => {const fetchPromise = fetch(event.request).then((response) => {if (response.ok) cache.put(event.request, response.clone());return response;}).catch(() => cached);return cached || fetchPromise;});}));return;}event.respondWith(caches.match(event.request).then((cached) => {const fetchPromise = fetch(event.request).then((response) => {if (response.ok && response.status !== 206) {const clone = response.clone();caches.open(CACHE_NAME).then((cache) => {cache.put(event.request, clone);});}return response;}).catch(() => cached);return cached || fetchPromise;}));});4 unmodified lines5678910111213141517 unmodified lines333435363738394041424310 unmodified lines545556575859602 unmodified lines6364656667686970717273747576777879808182838485864 unmodified lines"/static/style.css","/static/reader-contract.js","/static/reader-navigation.js","/static/app.js","/data/initial/manifest.json","/data/sidebar/manifest.json","/data/initial/global.json","/data/sidebar/global.json","/manifest.json","/icons/logo.svg","/icons/logo-dark.svg",17 unmodified lines"/static/reader.css","/static/reader.js"]);self.addEventListener("install", (event) => {event.waitUntil(caches.open(CACHE_NAME).then((cache) => {return cache.addAll(PRECACHE_URLS).catch((err) => {console.warn("[SW] precache partial failure:", err);});}).then(() => self.skipWaiting())10 unmodified lines});self.addEventListener("fetch", (event) => {const url = new URL(event.request.url);if (url.hostname !== self.location.hostname || (event.request.method || "GET") !== "GET") {return;}if (url.pathname.startsWith("/api/")) {2 unmodified linesif (url.pathname.startsWith("/txt/")) {return;}const readerNavigation = event.request.mode === "navigate" && url.pathname === "/static/reader.html";if (event.request.mode === "navigate" && !readerNavigation) {return;}const networkFirst = readerNavigation || READER_RUNTIME_PATHS.has(url.pathname);const cacheKey = readerNavigation ? "/static/reader.html" : event.request;const cachePromise = caches.open(CACHE_NAME).catch(() => null);const cachedPromise = cachePromise.then(cache => cache ? cache.match(cacheKey) : undefined).catch(() => undefined);const immutable = /\.[0-9a-f]{12}\.(?:js|mjs|css)$/.test(url.pathname);let cacheWrite;const networkPromise = Promise.all([cachePromise, immutable ? cachedPromise : null]).then(([cache, cached]) => cached || fetch(event.request).then(response => {if (cache && response.ok && response.status !== 206) {cacheWrite = cache.put(cacheKey, response.clone()).catch(() => {});}return response;}));event.waitUntil(networkPromise.then(() => cacheWrite).catch(() => {}));event.respondWith(networkFirst? networkPromise.then(response => response.ok ? response : cachedPromise.then(cached => cached || response)).catch(() => cachedPromise): cachedPromise.then(cached => cached || networkPromise.catch(() => cached)));});
37 unmodified lines3839404142434437 unmodified linesresponse = self.client.post("/api/search", json={"q": "readme", "page_size": 1})self.assertEqual(response.status_code, 200)self.assertEqual(response.json()["total"], 1)self.assertNotIn("server-timing", response.headers)def test_search_endpoint_rejects_malformed_json(self):self.assertEqual(self.client.post("/api/search", content="not-json", headers={"content-type": "application/json"}).status_code, 422)37 unmodified lines383940414243444537 unmodified linesresponse = self.client.post("/api/search", json={"q": "readme", "page_size": 1})self.assertEqual(response.status_code, 200)self.assertEqual(response.json()["total"], 1)self.assertRegex(response.headers["server-timing"], r"queue;dur=\d+\.\d+, search;dur=\d+\.\d+")self.assertNotIn("readme", response.headers["server-timing"])def test_search_endpoint_rejects_malformed_json(self):self.assertEqual(self.client.post("/api/search", content="not-json", headers={"content-type": "application/json"}).status_code, 422)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import asyncioimport threadingimport unittestfrom search_execution import SearchBusy, SearchExecutor
class SearchExecutionTests(unittest.IsolatedAsyncioTestCase): async def test_slow_search_does_not_block_http_ping_and_busy_requests_retry(self): import app import httpx from unittest.mock import patch, AsyncMock started, release = threading.Event(), threading.Event() def slow(**params): started.set() release.wait(2) return dict(results=[], total=0, page=1, page_size=100) async with SearchExecutor(capacity=1) as executor: with patch.object(app.app.state, 'search_executor', executor, create=True), \ patch.object(app, 'search', slow), \ patch.object(app, 'get_reader_assets', AsyncMock(return_value={'v': 1, 'f': {}})): async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app.app), base_url='http://test') as client: search = asyncio.create_task(client.post('/api/search', json={'q': 'query'})) try: self.assertTrue(await asyncio.to_thread(started.wait, 1)) ping = await asyncio.wait_for(client.get('/api/ping'), .5) self.assertEqual(ping.status_code, 204) self.assertFalse(search.done()) busy = await client.post('/api/search', json={}) self.assertEqual(busy.status_code, 503) self.assertEqual(busy.headers['retry-after'], '1') finally: release.set() response = await search self.assertEqual(response.status_code, 200) self.assertIn('reader_assets;dur=', response.headers['server-timing'])
async def test_active_cancellation_retains_slot_and_queued_cancellation_drops_work(self): started, release = threading.Event(), threading.Event() seen = [] def slow(): started.set() release.wait(2) seen.append('first') return 1 async with SearchExecutor(capacity=3) as executor: first = asyncio.create_task(executor.run(slow)) try: self.assertTrue(await asyncio.to_thread(started.wait, 1)) first.cancel() with self.assertRaises(asyncio.CancelledError): await first queued = asyncio.create_task(executor.run(lambda: seen.append('cancelled'))) await asyncio.sleep(0) queued.cancel() with self.assertRaises(asyncio.CancelledError): await queued next_job = asyncio.create_task(executor.run(lambda: seen.append('next') or 2)) await asyncio.sleep(.02) self.assertFalse(next_job.done()) self.assertEqual(seen, []) finally: release.set() self.assertEqual((await next_job)[0], 2) self.assertEqual(seen, ['first', 'next'])
async def test_capacity_failure_and_recovery(self): started, release = threading.Event(), threading.Event() def slow(): started.set() release.wait(2) async with SearchExecutor(capacity=1) as executor: active = asyncio.create_task(executor.run(slow)) try: self.assertTrue(await asyncio.to_thread(started.wait, 1)) with self.assertRaises(SearchBusy): await executor.run(lambda: None) finally: release.set() await active with self.assertRaisesRegex(ValueError, 'failure'): await executor.run(lambda: (_ for _ in ()).throw(ValueError('failure'))) value, queue, compute = await executor.run(lambda: 42) self.assertEqual(value, 42) self.assertGreaterEqual(queue, 0) self.assertGreaterEqual(compute, 0) with self.assertRaises(SearchBusy): await executor.run(lambda: None)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273const assert = require('assert');const fs = require('fs');const vm = require('vm');const {execFileSync} = require('child_process');const source = process.argv.includes('--baseline')? execFileSync('git', ['-c', `safe.directory=${process.cwd()}`, 'show', 'd07925f:static/sw.js'], {encoding:'utf8'}): fs.readFileSync('static/sw.js', 'utf8');async function check(failure) {const events = {}, added = [], deleted = [], requests = [];const cache = {addAll: async urls => {added.push([...urls]);if (failure === 'core' && urls.includes('/')) throw Error('core');if (failure === 'payload' && urls.includes('/initial-payload')) throw Error('payload');}};let waiting = 0, claimed = 0;vm.runInNewContext(source, {URL, Set, console:{warn(){}},self:{location:{hostname:'localhost'}, addEventListener:(name, fn)=>events[name]=fn,skipWaiting:()=>waiting++, clients:{claim:()=>claimed++}},caches:{open:async()=>cache, keys:async()=>['old-cache','voiceofml-search-hf-v1.0.0'],delete:async name=>deleted.push(name)},fetch:async url=>{requests.push(url);const initial=url.includes('/initial/');if (initial && failure === 'network') throw Error('network');return {ok:!(initial && failure==='status'),json:async()=>initial && failure==='invalid' ? {urls:'invalid'} : {urls:[initial?'/initial-payload':'/sidebar-payload']}};},});let completion;events.install({waitUntil:value=>completion=value});await completion;assert.strictEqual(waiting,1);assert.ok(added[0].includes('/static/app.js'));if (failure==='core') assert.strictEqual(requests.length,0);else {assert.strictEqual(requests.length,2);assert.ok(added.some(urls=>urls.includes('/sidebar-payload')));assert.strictEqual(added.some(urls=>urls.includes('/initial-payload')), !['network','status','invalid'].includes(failure));}events.activate({waitUntil:value=>completion=value});await completion;assert.deepStrictEqual(deleted,['old-cache']);assert.strictEqual(claimed,1);for(const [url,mode] of [['https://other.test/static/app.js','cors'], ['https://localhost/api/search','cors'],['https://localhost/txt/book.txt','cors'], ['https://localhost/Teachers','navigate']]) {events.fetch({request:{url,mode},respondWith(){throw Error('unexpected interception: '+url)}});}}async function checkSearchRuntimeCache(hasOldCache) {const events = {}, updates = [];const fresh = {ok:true, version:'current', clone(){return this;}};const old = hasOldCache ? {ok:true, version:'previous'} : undefined;vm.runInNewContext(source, {URL, Set, console,self:{location:{hostname:'localhost'},addEventListener:(name,fn)=>events[name]=fn},caches:{open:async()=>({match:async()=>old,put:async(key,value)=>updates.push(value.version)})},fetch:async()=>fresh,});for(const name of ['reader-chapter-search.mjs','reader-chapter-search-worker.mjs']) {let completion;events.fetch({request:{url:'https://localhost/static/'+name,mode:'cors'},respondWith(value){completion=value;}});assert.strictEqual((await completion).version,'current');}assert.deepStrictEqual(updates,['current','current']);}(async()=>{for(const failure of ['none','core','network','status','invalid','payload']) await check(failure);for(const old of [false,true]) await checkSearchRuntimeCache(old);console.log('HF service worker: manifest failure isolation, fixed cache activation and API/TXT/navigation bypass passed');})().catch(error=>{console.error(error);process.exitCode=1;});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182const assert = require('assert');const fs = require('fs');const vm = require('vm');const source = fs.readFileSync('static/sw.js', 'utf8');function response(version, status = 200) {return {version, status, ok: status >= 200 && status < 300, clone() { return this; }};}function harness({cached, fetchError, openError, put, fetch: network} = {}) {const events = {}, writes = [], fetched = [], added = [], lifetimes = [];const fresh = response('new');vm.runInNewContext(source, {URL, Set, console: {warn() {}},self: {location: {hostname: 'localhost'}, addEventListener: (name, fn) => events[name] = fn,skipWaiting() {}, clients: {claim() {}}},caches: {open: async () => {if (openError) throw Error('storage');return {match: async () => cached, addAll: async urls => added.push([...urls]),put: (key, value) => {writes.push(value); return put ? put() : Promise.resolve();}};}, keys: async () => ['voiceofml-search-hf-v1.0.0'], delete: async () => {}},fetch: async request => {fetched.push(request);if (fetchError) throw Error('offline');return network ? network() : fresh;},});function dispatch(path, mode = 'cors', method = 'GET') {let result;events.fetch({request: {url: 'https://localhost' + path, mode, method},respondWith: promise => result = promise, waitUntil: promise => lifetimes.push(promise)});return result;}return {events, writes, fetched, added, lifetimes, fresh, dispatch};}(async () => {const install = harness();let installed;install.events.install({waitUntil: promise => installed = promise});await installed;assert.strictEqual(install.added.length, 1);assert.ok(install.added[0].includes('/data/initial/global.json'));assert.ok(!install.added[0].some(url => /\/repos\/|\/reader\.(?:js|html|css)$/.test(url)));assert.strictEqual(install.fetched.length, 0);for (const path of ['/api/search', '/txt/book.txt', '/Teachers'])assert.strictEqual(install.dispatch(path, path === '/Teachers' ? 'navigate' : 'cors'), undefined);assert.strictEqual(install.dispatch('/static/app.js', 'cors', 'POST'), undefined);for (const path of ['/data/initial/global.json', '/data/sidebar/global.json', '/static/app.js']) {let releaseNetwork, releaseWrite, done = false;const old = response('old');const h = harness({cached: old, fetch: () => new Promise(resolve => releaseNetwork = resolve),put: () => new Promise(resolve => releaseWrite = resolve)});assert.strictEqual(await h.dispatch(path), old);h.lifetimes[0].then(() => done = true);releaseNetwork(response('new'));await new Promise(resolve => setTimeout(resolve, 0));assert.strictEqual(done, false);releaseWrite();await h.lifetimes[0];assert.strictEqual(done, true);}for (const options of [{openError: true}, {put: () => Promise.reject(Error('quota'))}]) {const h = harness(options);assert.strictEqual(await h.dispatch('/static/reader.js'), h.fresh);await Promise.all(h.lifetimes);}for (const path of ['/static/reader.js', '/data/initial/global.json']) {const h = harness({fetch: () => response('partial', 206)});assert.strictEqual((await h.dispatch(path)).status, 206);await Promise.all(h.lifetimes);assert.strictEqual(h.writes.length, 0);}for (const path of ['/static/reader-chapter-search.mjs', '/static/reader-chapter-search-worker.mjs']) {const h = harness({cached: response('old')});assert.strictEqual(await h.dispatch(path), h.fresh);await Promise.all(h.lifetimes);assert.strictEqual(h.writes.length, 1);}const pinned = harness({cached: response('pinned')});assert.strictEqual((await pinned.dispatch('/static/app.0123456789ab.js')).version, 'pinned');await Promise.all(pinned.lifetimes);assert.strictEqual(pinned.fetched.length, 0);console.log('HF Service Worker: demand caching, immutable reuse, write lifetime, storage errors and bypass passed');})().catch(error => {console.error(error); process.exitCode = 1;});
491 unmodified lines492493494495496497498499491 unmodified linesdef test_reader_runtime_is_network_first_with_one_navigation_cache_key(self):self.assertIn('event.request.mode === "navigate" && url.pathname === "/static/reader.html"', self.sw)self.assertIn('READER_RUNTIME_PATHS.has(url.pathname)', self.sw)self.assertIn('cacheKey = event.request.mode === "navigate" ? "/static/reader.html" : event.request', self.sw)self.assertIn('fetch(event.request).then((response)', self.sw)self.assertIn('cache.put(cacheKey, response.clone())', self.sw)def test_manifest_is_valid_and_scoped(self):491 unmodified lines492493494495496497498499491 unmodified linesdef test_reader_runtime_is_network_first_with_one_navigation_cache_key(self):self.assertIn('event.request.mode === "navigate" && url.pathname === "/static/reader.html"', self.sw)self.assertIn('READER_RUNTIME_PATHS.has(url.pathname)', self.sw)self.assertIn('cacheKey = readerNavigation ? "/static/reader.html" : event.request', self.sw)self.assertIn('event.waitUntil(networkPromise.then(() => cacheWrite)', self.sw)self.assertIn('cache.put(cacheKey, response.clone())', self.sw)def test_manifest_is_valid_and_scoped(self):
Dockerfile+1-1
SITE_OPTIMIZATION_REPORT.mdAdded+34
app.py+26-3
scripts/build_static_assets.mjs+8-2
search_execution.pyAdded+60
static/sw.js+22-65
tests/test_fastapi_endpoints.py+2-1
tests/test_search_execution.pyAdded+87
tests/test_service_worker.js+73-64
tests/test_static_contract.py+2-2