vomebook commited on
Commit ·
73da0eb
1
Parent(s): 3d91c94
fix: prevent PDF range browser cache serialization
Browse files- app.py +15 -1
- static/reader-pdf-network.mjs +20 -0
- static/reader-resources.js +1 -0
- static/reader.js +7 -0
- tests/test_async_proxy.py +22 -0
- tests/test_reader_pdf_loading.py +86 -3
app.py
CHANGED
|
@@ -2250,6 +2250,18 @@ async def api_reader_content(request: Request, url: Optional[str] = Query(defaul
|
|
| 2250 |
return await stream_reader_document(request, target_url)
|
| 2251 |
|
| 2252 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2253 |
async def stream_reader_document(
|
| 2254 |
request: Request, target_url: str, *,
|
| 2255 |
url_validator=validate_reader_redirect_url, cache_control: str | None = None,
|
|
@@ -2282,7 +2294,8 @@ async def stream_reader_document(
|
|
| 2282 |
cached_at, payload, cached_headers = cached
|
| 2283 |
if time.monotonic() - cached_at < READER_RANGE_CACHE_TTL_SECONDS:
|
| 2284 |
app.state.reader_range_cache.move_to_end(range_key)
|
| 2285 |
-
return Response(content=payload, status_code=206,
|
|
|
|
| 2286 |
app.state.reader_range_cache.pop(range_key, None)
|
| 2287 |
app.state.reader_range_cache_bytes -= len(payload)
|
| 2288 |
semaphore = app.state.upstream_semaphore
|
|
@@ -2312,6 +2325,7 @@ async def stream_reader_document(
|
|
| 2312 |
if media_type:
|
| 2313 |
headers["Content-Type"] = media_type
|
| 2314 |
status = upstream.status
|
|
|
|
| 2315 |
declared_length = upstream.headers.get("Content-Length")
|
| 2316 |
length = None
|
| 2317 |
if declared_length is not None:
|
|
|
|
| 2250 |
return await stream_reader_document(request, target_url)
|
| 2251 |
|
| 2252 |
|
| 2253 |
+
def reader_document_browser_headers(target_url: str, headers: dict, status: int) -> dict:
|
| 2254 |
+
is_pdf = (
|
| 2255 |
+
headers.get("Content-Type", "").split(";", 1)[0].strip().lower() == "application/pdf"
|
| 2256 |
+
or urlparse(target_url).path.lower().endswith(".pdf")
|
| 2257 |
+
)
|
| 2258 |
+
if status == 206 and is_pdf:
|
| 2259 |
+
# Keep browser partial bodies separate from the bounded server cache.
|
| 2260 |
+
# The request-side PDF policy bypasses Chromium's same-URL cache lock.
|
| 2261 |
+
return {**headers, "Cache-Control": "no-store"}
|
| 2262 |
+
return headers
|
| 2263 |
+
|
| 2264 |
+
|
| 2265 |
async def stream_reader_document(
|
| 2266 |
request: Request, target_url: str, *,
|
| 2267 |
url_validator=validate_reader_redirect_url, cache_control: str | None = None,
|
|
|
|
| 2294 |
cached_at, payload, cached_headers = cached
|
| 2295 |
if time.monotonic() - cached_at < READER_RANGE_CACHE_TTL_SECONDS:
|
| 2296 |
app.state.reader_range_cache.move_to_end(range_key)
|
| 2297 |
+
return Response(content=payload, status_code=206,
|
| 2298 |
+
headers=reader_document_browser_headers(target_url, cached_headers, 206))
|
| 2299 |
app.state.reader_range_cache.pop(range_key, None)
|
| 2300 |
app.state.reader_range_cache_bytes -= len(payload)
|
| 2301 |
semaphore = app.state.upstream_semaphore
|
|
|
|
| 2325 |
if media_type:
|
| 2326 |
headers["Content-Type"] = media_type
|
| 2327 |
status = upstream.status
|
| 2328 |
+
headers = reader_document_browser_headers(target_url, headers, status)
|
| 2329 |
declared_length = upstream.headers.get("Content-Length")
|
| 2330 |
length = None
|
| 2331 |
if declared_length is not None:
|
static/reader-pdf-network.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export function createPdfFetchPolicy() {
|
| 2 |
+
const documents = new Set();
|
| 3 |
+
const nativeFetch = globalThis.fetch;
|
| 4 |
+
const pdfFetch = (input, init) => {
|
| 5 |
+
let url;
|
| 6 |
+
try { url = new URL(input instanceof Request ? input.url : input, location.href).href; }
|
| 7 |
+
catch (_) { return nativeFetch.call(globalThis, input, init); }
|
| 8 |
+
return nativeFetch.call(globalThis, input, documents.has(url) ? { ...init, cache: "no-store" } : init);
|
| 9 |
+
};
|
| 10 |
+
globalThis.fetch = pdfFetch;
|
| 11 |
+
return {
|
| 12 |
+
add(urls) {
|
| 13 |
+
for (const url of urls) documents.add(new URL(url, location.href).href);
|
| 14 |
+
},
|
| 15 |
+
dispose() {
|
| 16 |
+
documents.clear();
|
| 17 |
+
if (globalThis.fetch === pdfFetch) globalThis.fetch = nativeFetch;
|
| 18 |
+
}
|
| 19 |
+
};
|
| 20 |
+
}
|
static/reader-resources.js
CHANGED
|
@@ -71,6 +71,7 @@
|
|
| 71 |
"reader-pdf-book-search-worker.mjs",
|
| 72 |
"reader-pdf-book-search.mjs",
|
| 73 |
"pdf-worker-wrapper.mjs",
|
|
|
|
| 74 |
"reader.css",
|
| 75 |
"reader.js"
|
| 76 |
]);
|
|
|
|
| 71 |
"reader-pdf-book-search-worker.mjs",
|
| 72 |
"reader-pdf-book-search.mjs",
|
| 73 |
"pdf-worker-wrapper.mjs",
|
| 74 |
+
"reader-pdf-network.mjs",
|
| 75 |
"reader.css",
|
| 76 |
"reader.js"
|
| 77 |
]);
|
static/reader.js
CHANGED
|
@@ -8,6 +8,8 @@ import "/static/reader-runtime.js";
|
|
| 8 |
import "/static/reader-format-adapters.js";
|
| 9 |
import { populatePdfTextLayer, populateOcrTextLayer, pdfTextContent, pdfSearchText, normalizePdfSearchText } from "/static/reader-pdf-text.js";
|
| 10 |
import { paintTextHit } from "/static/reader-book-text.js";
|
|
|
|
|
|
|
| 11 |
// Engines and Reader lifecycle.
|
| 12 |
const PDFJS_URL = VoiceOfMLReaderResources.vendorUrl("pdf", "/static/");
|
| 13 |
const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";
|
|
@@ -5180,6 +5182,11 @@ async function loadPdfEngine() {
|
|
| 5180 |
function loadPdfDocument() {
|
| 5181 |
return preloadPdfEngine().then((pdfjs) => {
|
| 5182 |
assertReaderActive();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5183 |
pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;
|
| 5184 |
const options = (url) => ({
|
| 5185 |
url,
|
|
|
|
| 8 |
import "/static/reader-format-adapters.js";
|
| 9 |
import { populatePdfTextLayer, populateOcrTextLayer, pdfTextContent, pdfSearchText, normalizePdfSearchText } from "/static/reader-pdf-text.js";
|
| 10 |
import { paintTextHit } from "/static/reader-book-text.js";
|
| 11 |
+
import { createPdfFetchPolicy } from "./reader-pdf-network.mjs";
|
| 12 |
+
let pdfFetchPolicy = null;
|
| 13 |
// Engines and Reader lifecycle.
|
| 14 |
const PDFJS_URL = VoiceOfMLReaderResources.vendorUrl("pdf", "/static/");
|
| 15 |
const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";
|
|
|
|
| 5182 |
function loadPdfDocument() {
|
| 5183 |
return preloadPdfEngine().then((pdfjs) => {
|
| 5184 |
assertReaderActive();
|
| 5185 |
+
if (!pdfFetchPolicy) {
|
| 5186 |
+
pdfFetchPolicy = createPdfFetchPolicy();
|
| 5187 |
+
trackReaderResource(() => { pdfFetchPolicy?.dispose(); pdfFetchPolicy = null; });
|
| 5188 |
+
}
|
| 5189 |
+
pdfFetchPolicy.add([sourceUrl, contentUrl]);
|
| 5190 |
pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;
|
| 5191 |
const options = (url) => ({
|
| 5192 |
url,
|
tests/test_async_proxy.py
CHANGED
|
@@ -747,6 +747,7 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
|
|
| 747 |
self.assertEqual(response.headers["content-range"], "bytes 0-1/10")
|
| 748 |
self.assertEqual(response.headers["content-length"], "2")
|
| 749 |
self.assertEqual(response.headers["content-encoding"], "identity")
|
|
|
|
| 750 |
self.assertIs(session.urls[0][1]["auto_decompress"], False)
|
| 751 |
self.assertNotIn("set-cookie", response.headers)
|
| 752 |
self.assertTrue(upstream.released)
|
|
@@ -765,11 +766,32 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
|
|
| 765 |
request = SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"})
|
| 766 |
url = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/document.pdf"
|
| 767 |
first = await app.api_reader_content(request, url)
|
|
|
|
| 768 |
self.assertEqual([chunk async for chunk in first.body_iterator], [b"ab"])
|
|
|
|
| 769 |
second = await app.api_reader_content(request, url)
|
| 770 |
self.assertEqual(second.body, b"ab")
|
|
|
|
| 771 |
self.assertEqual(len(session.urls), 1)
|
| 772 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 773 |
async def test_reader_content_does_not_reuse_range_cache_for_conditional_request(self):
|
| 774 |
first_upstream = FakeResponse(206, {
|
| 775 |
"Content-Type": "application/pdf", "Content-Length": "2",
|
|
|
|
| 747 |
self.assertEqual(response.headers["content-range"], "bytes 0-1/10")
|
| 748 |
self.assertEqual(response.headers["content-length"], "2")
|
| 749 |
self.assertEqual(response.headers["content-encoding"], "identity")
|
| 750 |
+
self.assertEqual(response.headers["cache-control"], "no-store")
|
| 751 |
self.assertIs(session.urls[0][1]["auto_decompress"], False)
|
| 752 |
self.assertNotIn("set-cookie", response.headers)
|
| 753 |
self.assertTrue(upstream.released)
|
|
|
|
| 766 |
request = SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"})
|
| 767 |
url = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/document.pdf"
|
| 768 |
first = await app.api_reader_content(request, url)
|
| 769 |
+
self.assertEqual(first.headers["cache-control"], "no-store")
|
| 770 |
self.assertEqual([chunk async for chunk in first.body_iterator], [b"ab"])
|
| 771 |
+
next(iter(app.app.state.reader_range_cache.values()))[2]["Cache-Control"] = "public, max-age=31536000"
|
| 772 |
second = await app.api_reader_content(request, url)
|
| 773 |
self.assertEqual(second.body, b"ab")
|
| 774 |
+
self.assertEqual(second.headers["cache-control"], "no-store")
|
| 775 |
self.assertEqual(len(session.urls), 1)
|
| 776 |
|
| 777 |
+
async def test_reader_browser_cache_policy_only_changes_partial_pdf_responses(self):
|
| 778 |
+
for suffix, mime, status, expected in (
|
| 779 |
+
("pdf", "application/pdf", 206, "no-store"),
|
| 780 |
+
("PDF", "application/octet-stream", 206, "no-store"),
|
| 781 |
+
("bin", "application/pdf; charset=binary", 206, "no-store"),
|
| 782 |
+
("pdf", "application/pdf", 200, "public, max-age=3600"),
|
| 783 |
+
("pdf", "application/pdf", 304, "public, max-age=3600"),
|
| 784 |
+
("mp4", "video/mp4", 206, "public, max-age=3600"),
|
| 785 |
+
):
|
| 786 |
+
with self.subTest(suffix=suffix, mime=mime, status=status):
|
| 787 |
+
headers = {"Content-Type": mime, "Cache-Control": "public, max-age=3600", "ETag": '"same"'}
|
| 788 |
+
result = app.reader_document_browser_headers(
|
| 789 |
+
"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book." + suffix, headers, status)
|
| 790 |
+
self.assertEqual(result["Cache-Control"], expected)
|
| 791 |
+
self.assertEqual(result["Content-Type"], mime)
|
| 792 |
+
self.assertEqual(result["ETag"], '"same"')
|
| 793 |
+
self.assertEqual(headers["Cache-Control"], "public, max-age=3600")
|
| 794 |
+
|
| 795 |
async def test_reader_content_does_not_reuse_range_cache_for_conditional_request(self):
|
| 796 |
first_upstream = FakeResponse(206, {
|
| 797 |
"Content-Type": "application/pdf", "Content-Length": "2",
|
tests/test_reader_pdf_loading.py
CHANGED
|
@@ -40,9 +40,6 @@ class PdfLoadingTests(unittest.TestCase):
|
|
| 40 |
self.page.on('request', lambda request: self.modules.append(request.url)
|
| 41 |
if '/vendor/pdf.min.' in request.url else None)
|
| 42 |
self.page.route('**/api/reader-content**', self.document)
|
| 43 |
-
cdp = self.context.new_cdp_session(self.page)
|
| 44 |
-
cdp.send('Network.enable')
|
| 45 |
-
cdp.send('Network.setCacheDisabled', {'cacheDisabled': True})
|
| 46 |
|
| 47 |
def document(self, route):
|
| 48 |
self.documents.append(route.request.url)
|
|
@@ -63,6 +60,92 @@ class PdfLoadingTests(unittest.TestCase):
|
|
| 63 |
self.assertEqual(len(self.modules), 1)
|
| 64 |
self.assertNotIn('reader-module-retry', self.modules[0])
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
def test_bucket_pdf_uses_same_origin_proxy_without_preparing_page_panel(self):
|
| 67 |
path = 'derived/test/' + 'a' * 32 + '/document.pdf'
|
| 68 |
source = self.origin + '/api/reader-bucket-resource?' + urllib.parse.urlencode({'path': path})
|
|
|
|
| 40 |
self.page.on('request', lambda request: self.modules.append(request.url)
|
| 41 |
if '/vendor/pdf.min.' in request.url else None)
|
| 42 |
self.page.route('**/api/reader-content**', self.document)
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
def document(self, route):
|
| 45 |
self.documents.append(route.request.url)
|
|
|
|
| 60 |
self.assertEqual(len(self.modules), 1)
|
| 61 |
self.assertNotIn('reader-module-retry', self.modules[0])
|
| 62 |
|
| 63 |
+
def test_pdf_range_policy_keeps_default_browser_cache_from_serializing_reads(self):
|
| 64 |
+
payload = b''.join(bytes([index]) * 128 for index in range(16))
|
| 65 |
+
metrics = {mode: {'active': 0, 'peak': 0} for mode in ('upstream', 'reader')}
|
| 66 |
+
lock = threading.Lock()
|
| 67 |
+
original = StaticHandler.do_GET
|
| 68 |
+
|
| 69 |
+
def serve(handler):
|
| 70 |
+
if not handler.path.startswith('/cache-lock-probe.pdf?'):
|
| 71 |
+
return original(handler)
|
| 72 |
+
mode = urllib.parse.parse_qs(urllib.parse.urlsplit(handler.path).query)['mode'][0]
|
| 73 |
+
match = re.fullmatch(r'bytes=(\d+)-(\d+)', handler.headers.get('Range', ''))
|
| 74 |
+
start, end = int(match[1]), int(match[2])
|
| 75 |
+
headers = {'Content-Type': 'application/pdf', 'Cache-Control': 'public, max-age=31536000',
|
| 76 |
+
'ETag': '"range-cache-probe"', 'Accept-Ranges': 'bytes',
|
| 77 |
+
'Content-Range': f'bytes {start}-{end}/{len(payload)}', 'Content-Length': str(end-start+1)}
|
| 78 |
+
with lock:
|
| 79 |
+
metrics[mode]['active'] += 1
|
| 80 |
+
metrics[mode]['peak'] = max(metrics[mode]['peak'], metrics[mode]['active'])
|
| 81 |
+
try:
|
| 82 |
+
time.sleep(.08)
|
| 83 |
+
handler.send_response(206)
|
| 84 |
+
for name, value in headers.items():
|
| 85 |
+
handler.send_header(name, value)
|
| 86 |
+
handler.end_headers()
|
| 87 |
+
handler.wfile.write(payload[start:end+1])
|
| 88 |
+
handler.wfile.flush()
|
| 89 |
+
finally:
|
| 90 |
+
with lock:
|
| 91 |
+
metrics[mode]['active'] -= 1
|
| 92 |
+
|
| 93 |
+
# Playwright routing also disables HTTP caching. Use an un-routed context.
|
| 94 |
+
with patch.object(StaticHandler, 'do_GET', serve), \
|
| 95 |
+
self.browser.new_context(service_workers='block') as context:
|
| 96 |
+
page = context.new_page()
|
| 97 |
+
page.goto(self.origin + '/static/manifest.json')
|
| 98 |
+
page.evaluate("async () => { window.__pdfNetwork = await import('/static/reader-pdf-network.mjs'); }")
|
| 99 |
+
for mode in ('upstream', 'reader'):
|
| 100 |
+
results = page.evaluate('''async mode => {
|
| 101 |
+
const url = '/cache-lock-probe.pdf?mode=' + mode;
|
| 102 |
+
const policy = mode === 'reader' ? __pdfNetwork.createPdfFetchPolicy() : null;
|
| 103 |
+
policy?.add([url]);
|
| 104 |
+
try { return await Promise.all(Array.from({length:16}, async (_, index) => {
|
| 105 |
+
const headers = {Range:'bytes=' + index*128 + '-' + (index*128+127)};
|
| 106 |
+
const response = await fetch(url, {headers});
|
| 107 |
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
| 108 |
+
return {status:response.status, range:response.headers.get('Content-Range'),
|
| 109 |
+
exact:bytes.length === 128 && bytes.every(value => value === index)};
|
| 110 |
+
})); } finally { policy?.dispose(); }
|
| 111 |
+
}''', mode)
|
| 112 |
+
self.assertEqual(results, [{'status':206, 'range':f'bytes {index*128}-{index*128+127}/2048',
|
| 113 |
+
'exact':True} for index in range(16)])
|
| 114 |
+
self.assertGreater(metrics['reader']['peak'], 1, metrics)
|
| 115 |
+
self.assertEqual(self.errors, [])
|
| 116 |
+
|
| 117 |
+
def test_pdf_fetch_policy_scopes_requests_preserves_options_and_restores_owner(self):
|
| 118 |
+
with self.browser.new_context(service_workers='block') as context:
|
| 119 |
+
page = context.new_page()
|
| 120 |
+
page.goto(self.origin + '/static/manifest.json')
|
| 121 |
+
result = page.evaluate('''async () => {
|
| 122 |
+
const {createPdfFetchPolicy} = await import('/static/reader-pdf-network.mjs');
|
| 123 |
+
const native = fetch, calls = [], signal = new AbortController().signal;
|
| 124 |
+
const init = {cache:'force-cache', signal, headers:{Range:'bytes=0-1'}};
|
| 125 |
+
const spy = (input, options) => {calls.push({input, options}); return Promise.resolve(new Response('ok'));};
|
| 126 |
+
globalThis.fetch = spy;
|
| 127 |
+
const policy = createPdfFetchPolicy();
|
| 128 |
+
try {
|
| 129 |
+
policy.add(['/document.pdf']);
|
| 130 |
+
await fetch('/document.pdf', init);
|
| 131 |
+
await fetch('/document.pdf?other=1', init);
|
| 132 |
+
policy.add(['/fallback.pdf']);
|
| 133 |
+
const request = new Request(new URL('/fallback.pdf', location.href));
|
| 134 |
+
await fetch(request, init);
|
| 135 |
+
policy.dispose();
|
| 136 |
+
const restored = fetch === spy;
|
| 137 |
+
await fetch('/document.pdf', init);
|
| 138 |
+
return {caches:calls.map(call => call.options.cache),
|
| 139 |
+
signals:calls.every(call => call.options.signal === signal),
|
| 140 |
+
headers:calls.every(call => call.options.headers === init.headers),
|
| 141 |
+
request:calls[2].input === request, outside:calls[1].options === init,
|
| 142 |
+
restored, originalCache:init.cache};
|
| 143 |
+
} finally { policy.dispose(); globalThis.fetch = native; }
|
| 144 |
+
}''')
|
| 145 |
+
self.assertEqual(result, {'caches':['no-store','force-cache','no-store','force-cache'],
|
| 146 |
+
'signals':True, 'headers':True, 'request':True, 'outside':True,
|
| 147 |
+
'restored':True, 'originalCache':'force-cache'})
|
| 148 |
+
|
| 149 |
def test_bucket_pdf_uses_same_origin_proxy_without_preparing_page_panel(self):
|
| 150 |
path = 'derived/test/' + 'a' * 32 + '/document.pdf'
|
| 151 |
source = self.origin + '/api/reader-bucket-resource?' + urllib.parse.urlencode({'path': path})
|