vomebook commited on
Commit ·
73da0eb
1
Parent(s): 3d91c94
fix: prevent PDF range browser cache serialization
Browse filesFiles changed (6)
2249 unmodified lines22502251225222532254225526 unmodified lines228222832284228522862287228823 unmodified lines2312231323142315231623172249 unmodified linesreturn await stream_reader_document(request, target_url)async def stream_reader_document(request: Request, target_url: str, *,url_validator=validate_reader_redirect_url, cache_control: str | None = None,26 unmodified linescached_at, payload, cached_headers = cachedif time.monotonic() - cached_at < READER_RANGE_CACHE_TTL_SECONDS:app.state.reader_range_cache.move_to_end(range_key)return Response(content=payload, status_code=206, headers=cached_headers)app.state.reader_range_cache.pop(range_key, None)app.state.reader_range_cache_bytes -= len(payload)semaphore = app.state.upstream_semaphore23 unmodified linesif media_type:headers["Content-Type"] = media_typestatus = upstream.statusdeclared_length = upstream.headers.get("Content-Length")length = Noneif declared_length is not None:2249 unmodified lines22502251225222532254225522562257225822592260226122622263226422652266226726 unmodified lines2294229522962297229822992300230123 unmodified lines23252326232723282329233023312249 unmodified linesreturn await stream_reader_document(request, target_url)def reader_document_browser_headers(target_url: str, headers: dict, status: int) -> dict:is_pdf = (headers.get("Content-Type", "").split(";", 1)[0].strip().lower() == "application/pdf"or urlparse(target_url).path.lower().endswith(".pdf"))if status == 206 and is_pdf:# Keep browser partial bodies separate from the bounded server cache.# The request-side PDF policy bypasses Chromium's same-URL cache lock.return {**headers, "Cache-Control": "no-store"}return headersasync def stream_reader_document(request: Request, target_url: str, *,url_validator=validate_reader_redirect_url, cache_control: str | None = None,26 unmodified linescached_at, payload, cached_headers = cachedif time.monotonic() - cached_at < READER_RANGE_CACHE_TTL_SECONDS:app.state.reader_range_cache.move_to_end(range_key)return Response(content=payload, status_code=206,headers=reader_document_browser_headers(target_url, cached_headers, 206))app.state.reader_range_cache.pop(range_key, None)app.state.reader_range_cache_bytes -= len(payload)semaphore = app.state.upstream_semaphore23 unmodified linesif media_type:headers["Content-Type"] = media_typestatus = upstream.statusheaders = reader_document_browser_headers(target_url, headers, status)declared_length = upstream.headers.get("Content-Length")length = Noneif declared_length is not None:
1234567891011121314151617181920export function createPdfFetchPolicy() { const documents = new Set(); const nativeFetch = globalThis.fetch; const pdfFetch = (input, init) => { let url; try { url = new URL(input instanceof Request ? input.url : input, location.href).href; } catch (_) { return nativeFetch.call(globalThis, input, init); } return nativeFetch.call(globalThis, input, documents.has(url) ? { ...init, cache: "no-store" } : init); }; globalThis.fetch = pdfFetch; return { add(urls) { for (const url of urls) documents.add(new URL(url, location.href).href); }, dispose() { documents.clear(); if (globalThis.fetch === pdfFetch) globalThis.fetch = nativeFetch; } };}70 unmodified lines71727374757670 unmodified lines"reader-pdf-book-search-worker.mjs","reader-pdf-book-search.mjs","pdf-worker-wrapper.mjs","reader.css","reader.js"]);70 unmodified lines7172737475767770 unmodified lines"reader-pdf-book-search-worker.mjs","reader-pdf-book-search.mjs","pdf-worker-wrapper.mjs","reader-pdf-network.mjs","reader.css","reader.js"]);
7 unmodified lines89101112135166 unmodified lines5180518151825183518451857 unmodified linesimport "/static/reader-format-adapters.js";import { populatePdfTextLayer, populateOcrTextLayer, pdfTextContent, pdfSearchText, normalizePdfSearchText } from "/static/reader-pdf-text.js";import { paintTextHit } from "/static/reader-book-text.js";// Engines and Reader lifecycle.const PDFJS_URL = VoiceOfMLReaderResources.vendorUrl("pdf", "/static/");const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";5166 unmodified linesfunction loadPdfDocument() {return preloadPdfEngine().then((pdfjs) => {assertReaderActive();pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;const options = (url) => ({url,7 unmodified lines891011121314155166 unmodified lines518251835184518551865187518851895190519151927 unmodified linesimport "/static/reader-format-adapters.js";import { populatePdfTextLayer, populateOcrTextLayer, pdfTextContent, pdfSearchText, normalizePdfSearchText } from "/static/reader-pdf-text.js";import { paintTextHit } from "/static/reader-book-text.js";import { createPdfFetchPolicy } from "./reader-pdf-network.mjs";let pdfFetchPolicy = null;// Engines and Reader lifecycle.const PDFJS_URL = VoiceOfMLReaderResources.vendorUrl("pdf", "/static/");const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";5166 unmodified linesfunction loadPdfDocument() {return preloadPdfEngine().then((pdfjs) => {assertReaderActive();if (!pdfFetchPolicy) {pdfFetchPolicy = createPdfFetchPolicy();trackReaderResource(() => { pdfFetchPolicy?.dispose(); pdfFetchPolicy = null; });}pdfFetchPolicy.add([sourceUrl, contentUrl]);pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;const options = (url) => ({url,
746 unmodified lines74774874975075175212 unmodified lines765766767768769770771772773774775746 unmodified linesself.assertEqual(response.headers["content-range"], "bytes 0-1/10")self.assertEqual(response.headers["content-length"], "2")self.assertEqual(response.headers["content-encoding"], "identity")self.assertIs(session.urls[0][1]["auto_decompress"], False)self.assertNotIn("set-cookie", response.headers)self.assertTrue(upstream.released)12 unmodified linesrequest = SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"})url = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/document.pdf"first = await app.api_reader_content(request, url)self.assertEqual([chunk async for chunk in first.body_iterator], [b"ab"])second = await app.api_reader_content(request, url)self.assertEqual(second.body, b"ab")self.assertEqual(len(session.urls), 1)async def test_reader_content_does_not_reuse_range_cache_for_conditional_request(self):first_upstream = FakeResponse(206, {"Content-Type": "application/pdf", "Content-Length": "2",746 unmodified lines74774874975075175275312 unmodified lines766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797746 unmodified linesself.assertEqual(response.headers["content-range"], "bytes 0-1/10")self.assertEqual(response.headers["content-length"], "2")self.assertEqual(response.headers["content-encoding"], "identity")self.assertEqual(response.headers["cache-control"], "no-store")self.assertIs(session.urls[0][1]["auto_decompress"], False)self.assertNotIn("set-cookie", response.headers)self.assertTrue(upstream.released)12 unmodified linesrequest = SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"})url = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/document.pdf"first = await app.api_reader_content(request, url)self.assertEqual(first.headers["cache-control"], "no-store")self.assertEqual([chunk async for chunk in first.body_iterator], [b"ab"])next(iter(app.app.state.reader_range_cache.values()))[2]["Cache-Control"] = "public, max-age=31536000"second = await app.api_reader_content(request, url)self.assertEqual(second.body, b"ab")self.assertEqual(second.headers["cache-control"], "no-store")self.assertEqual(len(session.urls), 1)async def test_reader_browser_cache_policy_only_changes_partial_pdf_responses(self):for suffix, mime, status, expected in (("pdf", "application/pdf", 206, "no-store"),("PDF", "application/octet-stream", 206, "no-store"),("bin", "application/pdf; charset=binary", 206, "no-store"),("pdf", "application/pdf", 200, "public, max-age=3600"),("pdf", "application/pdf", 304, "public, max-age=3600"),("mp4", "video/mp4", 206, "public, max-age=3600"),):with self.subTest(suffix=suffix, mime=mime, status=status):headers = {"Content-Type": mime, "Cache-Control": "public, max-age=3600", "ETag": '"same"'}result = app.reader_document_browser_headers("https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book." + suffix, headers, status)self.assertEqual(result["Cache-Control"], expected)self.assertEqual(result["Content-Type"], mime)self.assertEqual(result["ETag"], '"same"')self.assertEqual(headers["Cache-Control"], "public, max-age=3600")async def test_reader_content_does_not_reuse_range_cache_for_conditional_request(self):first_upstream = FakeResponse(206, {"Content-Type": "application/pdf", "Content-Length": "2",
39 unmodified lines40414243444546474814 unmodified lines63646566676839 unmodified linesself.page.on('request', lambda request: self.modules.append(request.url)if '/vendor/pdf.min.' in request.url else None)self.page.route('**/api/reader-content**', self.document)cdp = self.context.new_cdp_session(self.page)cdp.send('Network.enable')cdp.send('Network.setCacheDisabled', {'cacheDisabled': True})def document(self, route):self.documents.append(route.request.url)14 unmodified linesself.assertEqual(len(self.modules), 1)self.assertNotIn('reader-module-retry', self.modules[0])def test_bucket_pdf_uses_same_origin_proxy_without_preparing_page_panel(self):path = 'derived/test/' + 'a' * 32 + '/document.pdf'source = self.origin + '/api/reader-bucket-resource?' + urllib.parse.urlencode({'path': path})39 unmodified lines40414243444514 unmodified lines6061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015139 unmodified linesself.page.on('request', lambda request: self.modules.append(request.url)if '/vendor/pdf.min.' in request.url else None)self.page.route('**/api/reader-content**', self.document)def document(self, route):self.documents.append(route.request.url)14 unmodified linesself.assertEqual(len(self.modules), 1)self.assertNotIn('reader-module-retry', self.modules[0])def test_pdf_range_policy_keeps_default_browser_cache_from_serializing_reads(self):payload = b''.join(bytes([index]) * 128 for index in range(16))metrics = {mode: {'active': 0, 'peak': 0} for mode in ('upstream', 'reader')}lock = threading.Lock()original = StaticHandler.do_GETdef serve(handler):if not handler.path.startswith('/cache-lock-probe.pdf?'):return original(handler)mode = urllib.parse.parse_qs(urllib.parse.urlsplit(handler.path).query)['mode'][0]match = re.fullmatch(r'bytes=(\d+)-(\d+)', handler.headers.get('Range', ''))start, end = int(match[1]), int(match[2])headers = {'Content-Type': 'application/pdf', 'Cache-Control': 'public, max-age=31536000','ETag': '"range-cache-probe"', 'Accept-Ranges': 'bytes','Content-Range': f'bytes {start}-{end}/{len(payload)}', 'Content-Length': str(end-start+1)}with lock:metrics[mode]['active'] += 1metrics[mode]['peak'] = max(metrics[mode]['peak'], metrics[mode]['active'])try:time.sleep(.08)handler.send_response(206)for name, value in headers.items():handler.send_header(name, value)handler.end_headers()handler.wfile.write(payload[start:end+1])handler.wfile.flush()finally:with lock:metrics[mode]['active'] -= 1# Playwright routing also disables HTTP caching. Use an un-routed context.with patch.object(StaticHandler, 'do_GET', serve), \self.browser.new_context(service_workers='block') as context:page = context.new_page()page.goto(self.origin + '/static/manifest.json')page.evaluate("async () => { window.__pdfNetwork = await import('/static/reader-pdf-network.mjs'); }")for mode in ('upstream', 'reader'):results = page.evaluate('''async mode => {const url = '/cache-lock-probe.pdf?mode=' + mode;const policy = mode === 'reader' ? __pdfNetwork.createPdfFetchPolicy() : null;policy?.add([url]);try { return await Promise.all(Array.from({length:16}, async (_, index) => {const headers = {Range:'bytes=' + index*128 + '-' + (index*128+127)};const response = await fetch(url, {headers});const bytes = new Uint8Array(await response.arrayBuffer());return {status:response.status, range:response.headers.get('Content-Range'),exact:bytes.length === 128 && bytes.every(value => value === index)};})); } finally { policy?.dispose(); }}''', mode)self.assertEqual(results, [{'status':206, 'range':f'bytes {index*128}-{index*128+127}/2048','exact':True} for index in range(16)])self.assertGreater(metrics['reader']['peak'], 1, metrics)self.assertEqual(self.errors, [])def test_pdf_fetch_policy_scopes_requests_preserves_options_and_restores_owner(self):with self.browser.new_context(service_workers='block') as context:page = context.new_page()page.goto(self.origin + '/static/manifest.json')result = page.evaluate('''async () => {const {createPdfFetchPolicy} = await import('/static/reader-pdf-network.mjs');const native = fetch, calls = [], signal = new AbortController().signal;const init = {cache:'force-cache', signal, headers:{Range:'bytes=0-1'}};const spy = (input, options) => {calls.push({input, options}); return Promise.resolve(new Response('ok'));};globalThis.fetch = spy;const policy = createPdfFetchPolicy();try {policy.add(['/document.pdf']);await fetch('/document.pdf', init);await fetch('/document.pdf?other=1', init);policy.add(['/fallback.pdf']);const request = new Request(new URL('/fallback.pdf', location.href));await fetch(request, init);policy.dispose();const restored = fetch === spy;await fetch('/document.pdf', init);return {caches:calls.map(call => call.options.cache),signals:calls.every(call => call.options.signal === signal),headers:calls.every(call => call.options.headers === init.headers),request:calls[2].input === request, outside:calls[1].options === init,restored, originalCache:init.cache};} finally { policy.dispose(); globalThis.fetch = native; }}''')self.assertEqual(result, {'caches':['no-store','force-cache','no-store','force-cache'],'signals':True, 'headers':True, 'request':True, 'outside':True,'restored':True, 'originalCache':'force-cache'})def test_bucket_pdf_uses_same_origin_proxy_without_preparing_page_panel(self):path = 'derived/test/' + 'a' * 32 + '/document.pdf'source = self.origin + '/api/reader-bucket-resource?' + urllib.parse.urlencode({'path': path})
app.py+15-1
static/reader-pdf-network.mjsAdded+20
static/reader-resources.js+1
static/reader.js+7
tests/test_async_proxy.py+22
tests/test_reader_pdf_loading.py+86-3