vomebook commited on
Commit ·
29376ff
1
Parent(s): 7549fd9
Strictly check PDF engine preloader
Browse files
jsconfig.strict.json
CHANGED
|
@@ -12,6 +12,8 @@
|
|
| 12 |
"static/reader/core/reader-diagnostics.mjs",
|
| 13 |
"static/reader/formats/reader-image-loader.mjs",
|
| 14 |
"static/reader/ui/reader-document-styles.mjs",
|
| 15 |
-
"static/search/search-session.js"
|
|
|
|
|
|
|
| 16 |
]
|
| 17 |
}
|
|
|
|
| 12 |
"static/reader/core/reader-diagnostics.mjs",
|
| 13 |
"static/reader/formats/reader-image-loader.mjs",
|
| 14 |
"static/reader/ui/reader-document-styles.mjs",
|
| 15 |
+
"static/search/search-session.js",
|
| 16 |
+
"static/reader/pdf/reader-engine-preload.js",
|
| 17 |
+
"typings/reader-globals.d.ts"
|
| 18 |
]
|
| 19 |
}
|
static/reader/pdf/reader-engine-preload.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
"use strict";
|
| 3 |
const params = new URLSearchParams(location.search);
|
| 4 |
let pdf = params.get("ext")?.toLowerCase() === "pdf";
|
| 5 |
-
try { pdf ||= new URL(params.get("url")).pathname.toLowerCase().endsWith(".pdf"); } catch (_) {}
|
| 6 |
const script = /** @type {HTMLScriptElement} */ (document.currentScript);
|
| 7 |
const base = new URL("../../", script.src).href;
|
| 8 |
const extension = pdf ? "pdf" : (params.get("ext") || "").toLowerCase();
|
|
|
|
| 2 |
"use strict";
|
| 3 |
const params = new URLSearchParams(location.search);
|
| 4 |
let pdf = params.get("ext")?.toLowerCase() === "pdf";
|
| 5 |
+
try { pdf ||= new URL(params.get("url") ?? "").pathname.toLowerCase().endsWith(".pdf"); } catch (_) {}
|
| 6 |
const script = /** @type {HTMLScriptElement} */ (document.currentScript);
|
| 7 |
const base = new URL("../../", script.src).href;
|
| 8 |
const extension = pdf ? "pdf" : (params.get("ext") || "").toLowerCase();
|
tests/test_reader_engine_preload.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exercise the actual early engine preloader in Chromium."""
|
| 2 |
+
import contextlib
|
| 3 |
+
import unittest
|
| 4 |
+
|
| 5 |
+
from playwright.sync_api import sync_playwright
|
| 6 |
+
from tests import test_reader_pdf_first_page as support
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ReaderEnginePreloadTests(unittest.TestCase):
|
| 10 |
+
@classmethod
|
| 11 |
+
def setUpClass(cls):
|
| 12 |
+
stack = contextlib.ExitStack()
|
| 13 |
+
cls.addClassCleanup(stack.close)
|
| 14 |
+
cls.playwright = stack.enter_context(sync_playwright())
|
| 15 |
+
cls.browser = cls.playwright.chromium.launch(headless=True, args=["--no-sandbox"])
|
| 16 |
+
cls.addClassCleanup(cls.browser.close)
|
| 17 |
+
|
| 18 |
+
def test_only_engine_assets_are_warmed_and_pending_fetches_are_cancelled(self):
|
| 19 |
+
payload = b"%PDF-1.7\n"
|
| 20 |
+
with support.range_source(payload) as (origin, _state, _lock):
|
| 21 |
+
prefix = "/search" if "/search/static/" in (support.ROOT / "static/reader.html").read_text() else ""
|
| 22 |
+
for mode in ("extension", "source", "save-data", "other", "missing"):
|
| 23 |
+
with self.subTest(mode=mode):
|
| 24 |
+
context = self.browser.new_context(service_workers="block")
|
| 25 |
+
try:
|
| 26 |
+
page = context.new_page()
|
| 27 |
+
page.route("**/engine-preload-fixture*", lambda route: route.fulfill(
|
| 28 |
+
status=200, content_type="text/html", body="<!doctype html><title>engine fixture</title>"))
|
| 29 |
+
page.route("**/static/engine.mjs", lambda route: route.fulfill(content_type="text/javascript", body="export {}"))
|
| 30 |
+
page.route("**/static/classic.js", lambda route: route.fulfill(content_type="text/javascript", body=""))
|
| 31 |
+
page.route("**/static/reader/pdf/pdf-worker-wrapper.mjs", lambda route: route.fulfill(
|
| 32 |
+
content_type="text/javascript", body="export {}"))
|
| 33 |
+
query = {"extension": "?ext=pdf", "source": "?url=https%3A%2F%2Fexample.test%2Fa.PDF",
|
| 34 |
+
"save-data": "?ext=pdf", "other": "?ext=txt", "missing": ""}[mode]
|
| 35 |
+
page.goto(origin + "/engine-preload-fixture" + query)
|
| 36 |
+
page.evaluate("""saveData=>{
|
| 37 |
+
Object.defineProperty(navigator,'connection',{configurable:true,value:{saveData}});
|
| 38 |
+
window.__warmRequests=[];window.__bodyReads=0;
|
| 39 |
+
window.VoiceOfMLReaderResources={
|
| 40 |
+
engineAssets:(ext,base,suffix,worker)=>{
|
| 41 |
+
window.__engineArgs={ext,base,suffix,worker};
|
| 42 |
+
return [worker,base+'engine.mjs',base+'classic.js'];
|
| 43 |
+
},
|
| 44 |
+
pdfSupportAssets:base=>[base+'support.bin']
|
| 45 |
+
};
|
| 46 |
+
window.VoiceOfMLReaderSecurity={readBytes:async()=>{window.__bodyReads++;}};
|
| 47 |
+
window.fetch=(url,options)=>{
|
| 48 |
+
window.__warmRequests.push({url,options});
|
| 49 |
+
return new Promise((resolve,reject)=>options.signal.addEventListener('abort',()=>reject(options.signal.reason),{once:true}));
|
| 50 |
+
};
|
| 51 |
+
}""", mode == "save-data")
|
| 52 |
+
page.add_script_tag(url=origin + prefix + "/static/reader/pdf/reader-engine-preload.js")
|
| 53 |
+
result = page.evaluate("""()=>({args:window.__engineArgs,requests:window.__warmRequests.map(x=>({
|
| 54 |
+
url:x.url,mode:x.options.mode,credentials:x.options.credentials,aborted:x.options.signal.aborted})),
|
| 55 |
+
links:[...document.querySelectorAll('link')].map(x=>({href:x.href,rel:x.rel,as:x.as})),
|
| 56 |
+
reads:window.__bodyReads})""")
|
| 57 |
+
is_pdf = mode in ("extension", "source", "save-data")
|
| 58 |
+
self.assertEqual(result["args"]["ext"], "pdf" if is_pdf else ("txt" if mode == "other" else ""))
|
| 59 |
+
base = origin + prefix + "/static/"
|
| 60 |
+
worker = base + "reader/pdf/pdf-worker-wrapper.mjs"
|
| 61 |
+
self.assertEqual(result["args"]["base"], base)
|
| 62 |
+
self.assertEqual(result["args"]["worker"], worker)
|
| 63 |
+
self.assertEqual(result["args"]["suffix"], "?reader-v1" if prefix else "")
|
| 64 |
+
expected_requests = [worker] if is_pdf else []
|
| 65 |
+
if is_pdf and mode != "save-data":
|
| 66 |
+
expected_requests.append(base + "support.bin")
|
| 67 |
+
self.assertEqual([item["url"] for item in result["requests"]], expected_requests)
|
| 68 |
+
self.assertEqual(result["reads"], 0)
|
| 69 |
+
for request in result["requests"]:
|
| 70 |
+
self.assertEqual((request["mode"], request["credentials"]), ("same-origin", "same-origin"))
|
| 71 |
+
self.assertFalse(request["aborted"])
|
| 72 |
+
self.assertFalse("reader-content" in request["url"] or "example.test/a.PDF" in request["url"])
|
| 73 |
+
link_types = {link["href"].rsplit("/", 1)[-1]: (link["rel"], link["as"]) for link in result["links"]}
|
| 74 |
+
self.assertEqual(link_types["engine.mjs"][0], "modulepreload")
|
| 75 |
+
self.assertEqual(link_types["classic.js"], ("preload", "script"))
|
| 76 |
+
if is_pdf:
|
| 77 |
+
self.assertNotIn("pdf-worker-wrapper.mjs", link_types)
|
| 78 |
+
page.evaluate("dispatchEvent(new Event('voice-reader-dispose'))")
|
| 79 |
+
self.assertTrue(page.evaluate("window.__warmRequests.every(item=>item.options.signal.aborted)"))
|
| 80 |
+
else:
|
| 81 |
+
self.assertEqual(link_types["pdf-worker-wrapper.mjs"][0], "modulepreload")
|
| 82 |
+
finally:
|
| 83 |
+
context.close()
|
| 84 |
+
|
| 85 |
+
def test_warm_fetch_success_http_failure_and_rejection_are_settled(self):
|
| 86 |
+
with support.range_source(b"%PDF-1.7\n") as (origin, _state, _lock):
|
| 87 |
+
prefix = "/search" if "/search/static/" in (support.ROOT / "static/reader.html").read_text() else ""
|
| 88 |
+
context = self.browser.new_context(service_workers="block")
|
| 89 |
+
try:
|
| 90 |
+
page = context.new_page()
|
| 91 |
+
page.route("**/engine-preload-fixture*", lambda route: route.fulfill(
|
| 92 |
+
content_type="text/html", body="<!doctype html><title>engine fixture</title>"))
|
| 93 |
+
page.goto(origin + "/engine-preload-fixture?ext=pdf")
|
| 94 |
+
page.evaluate("""()=>{
|
| 95 |
+
window.__reads=[];window.__cancels=0;window.__removed=[];
|
| 96 |
+
const remove=window.removeEventListener.bind(window);
|
| 97 |
+
window.removeEventListener=(type,...rest)=>{window.__removed.push(type);return remove(type,...rest);};
|
| 98 |
+
window.VoiceOfMLReaderResources={
|
| 99 |
+
engineAssets:()=>[],pdfSupportAssets:base=>[base+'failure.bin',base+'reject.bin']
|
| 100 |
+
};
|
| 101 |
+
window.VoiceOfMLReaderSecurity={readBytes:async(response,limit)=>window.__reads.push({url:response.url,limit})};
|
| 102 |
+
window.fetch=(url)=>{
|
| 103 |
+
if(url.endsWith('/reject.bin')) return Promise.reject(new Error('network failure'));
|
| 104 |
+
if(url.endsWith('/failure.bin')) return Promise.resolve({ok:false,body:{cancel:async()=>{window.__cancels++;}}});
|
| 105 |
+
return Promise.resolve({ok:true,url});
|
| 106 |
+
};
|
| 107 |
+
}""")
|
| 108 |
+
page.add_script_tag(url=origin + prefix + "/static/reader/pdf/reader-engine-preload.js")
|
| 109 |
+
page.wait_for_function("()=>window.__removed.includes('voice-reader-dispose')")
|
| 110 |
+
result = page.evaluate("()=>({reads:window.__reads,cancels:window.__cancels,removed:window.__removed})")
|
| 111 |
+
self.assertEqual(result["reads"], [{"url": origin + prefix + "/static/reader/pdf/pdf-worker-wrapper.mjs",
|
| 112 |
+
"limit": 1024 * 1024}])
|
| 113 |
+
self.assertEqual(result["cancels"], 1)
|
| 114 |
+
self.assertIn("pagehide", result["removed"])
|
| 115 |
+
self.assertIn("voice-reader-dispose", result["removed"])
|
| 116 |
+
finally:
|
| 117 |
+
context.close()
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
unittest.main()
|
tests/test_reader_pdf_loading.py
CHANGED
|
@@ -87,18 +87,22 @@ class PdfLoadingTests(unittest.TestCase):
|
|
| 87 |
def test_original_download_name_survives_title_change_and_button_handoff(self):
|
| 88 |
source='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/Sample%20.PDF'
|
| 89 |
checks=[]
|
|
|
|
| 90 |
self.page.route('**/api/reader-resolve?id=filename-click',lambda route:route.fulfill(json={
|
| 91 |
'url':source,'download':source,'extension':'txt','original_extension':'pdf',
|
| 92 |
'title':'Sample ','filename':'Sample .PDF'}))
|
| 93 |
self.page.route('**/api/reader-content**',lambda route:route.fulfill(content_type='text/plain',body='safe'))
|
| 94 |
self.page.route('**/api/download/check?**',lambda route:route.fulfill(json={'ok':True}))
|
| 95 |
-
self.page.route('**/api/download?**',lambda route:
|
| 96 |
self.page.goto(self.origin+'/static/reader.html?id=filename-click&ext=txt',wait_until='domcontentloaded')
|
| 97 |
self.page.locator('.reader-text').wait_for()
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
self.
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
| 102 |
self.assertEqual(query['file'],['Sample .PDF'])
|
| 103 |
self.assertEqual(query['link'],[source])
|
| 104 |
|
|
@@ -413,7 +417,13 @@ class PdfLoadingTests(unittest.TestCase):
|
|
| 413 |
const nativeFetch=fetch,nativeTimer=setTimeout;
|
| 414 |
window.__idLookups=0;window.__earlyCancelled=false;
|
| 415 |
const mode=new URLSearchParams(location.search).get('probe');
|
| 416 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
window.fetch=(url,init)=>{
|
| 418 |
if(!String(url).includes('/api/reader-resolve?'))return nativeFetch(url,init);
|
| 419 |
__idLookups++;
|
|
@@ -424,8 +434,13 @@ class PdfLoadingTests(unittest.TestCase):
|
|
| 424 |
}}),{headers:{'Content-Type':'application/json'}}));
|
| 425 |
};
|
| 426 |
})();''')
|
| 427 |
-
|
| 428 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
self.page.goto(self.origin+'/static/reader.html?id=398vk0yyy8m29&ext=pdf&probe=body',wait_until='domcontentloaded')
|
| 430 |
self.ready()
|
| 431 |
self.assertEqual(self.page.evaluate('__idLookups'),2)
|
|
|
|
| 87 |
def test_original_download_name_survives_title_change_and_button_handoff(self):
|
| 88 |
source='https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/Sample%20.PDF'
|
| 89 |
checks=[]
|
| 90 |
+
self.page.on('request',lambda request:checks.append(request.url) if '/api/download?' in request.url else None)
|
| 91 |
self.page.route('**/api/reader-resolve?id=filename-click',lambda route:route.fulfill(json={
|
| 92 |
'url':source,'download':source,'extension':'txt','original_extension':'pdf',
|
| 93 |
'title':'Sample ','filename':'Sample .PDF'}))
|
| 94 |
self.page.route('**/api/reader-content**',lambda route:route.fulfill(content_type='text/plain',body='safe'))
|
| 95 |
self.page.route('**/api/download/check?**',lambda route:route.fulfill(json={'ok':True}))
|
| 96 |
+
self.page.route('**/api/download?**',lambda route:route.fulfill(body='file'))
|
| 97 |
self.page.goto(self.origin+'/static/reader.html?id=filename-click&ext=txt',wait_until='domcontentloaded')
|
| 98 |
self.page.locator('.reader-text').wait_for()
|
| 99 |
+
# The UI reports that the iframe was appended, not that its request
|
| 100 |
+
# has reached Playwright. Await both independent observable events.
|
| 101 |
+
with self.page.expect_request('**/api/download?**') as requested:
|
| 102 |
+
self.page.locator('#download').click()
|
| 103 |
+
self.page.wait_for_function("()=>document.querySelector('#download-feedback')?.textContent.includes('已发起下载')")
|
| 104 |
+
self.assertEqual(checks,[requested.value.url])
|
| 105 |
+
query=urllib.parse.parse_qs(urllib.parse.urlsplit(requested.value.url).query)
|
| 106 |
self.assertEqual(query['file'],['Sample .PDF'])
|
| 107 |
self.assertEqual(query['link'],[source])
|
| 108 |
|
|
|
|
| 417 |
const nativeFetch=fetch,nativeTimer=setTimeout;
|
| 418 |
window.__idLookups=0;window.__earlyCancelled=false;
|
| 419 |
const mode=new URLSearchParams(location.search).get('probe');
|
| 420 |
+
// Expire only the first 10s timer: the early resolve deadline. The
|
| 421 |
+
// demand request manager's separate 10s idle timer must remain real.
|
| 422 |
+
let shortenedEarlyDeadline=false;
|
| 423 |
+
window.setTimeout=(callback,delay,...args)=>{
|
| 424 |
+
if(delay===10000&&!shortenedEarlyDeadline){shortenedEarlyDeadline=true;delay=100;}
|
| 425 |
+
return nativeTimer(callback,delay,...args);
|
| 426 |
+
};
|
| 427 |
window.fetch=(url,init)=>{
|
| 428 |
if(!String(url).includes('/api/reader-resolve?'))return nativeFetch(url,init);
|
| 429 |
__idLookups++;
|
|
|
|
| 434 |
}}),{headers:{'Content-Type':'application/json'}}));
|
| 435 |
};
|
| 436 |
})();''')
|
| 437 |
+
# A healthy demand lookup may take longer than the shortened early
|
| 438 |
+
# deadline; it must not inherit that deadline's artificial timeout.
|
| 439 |
+
def lookup(route):
|
| 440 |
+
time.sleep(.2)
|
| 441 |
+
route.fulfill(content_type='application/json',body=json.dumps({
|
| 442 |
+
'url':SOURCE,'download':SOURCE,'extension':'pdf'}))
|
| 443 |
+
self.page.route('**/api/reader-resolve?**',lookup)
|
| 444 |
self.page.goto(self.origin+'/static/reader.html?id=398vk0yyy8m29&ext=pdf&probe=body',wait_until='domcontentloaded')
|
| 445 |
self.ready()
|
| 446 |
self.assertEqual(self.page.evaluate('__idLookups'),2)
|
tests/test_static_checks.py
CHANGED
|
@@ -119,6 +119,11 @@ class StaticGateTests(unittest.TestCase):
|
|
| 119 |
source = self.root / config["files"][0]
|
| 120 |
source.write_text(source.read_text() + "\nfunction strictProbe(value) { return value; }\nstrictProbe(1);\n")
|
| 121 |
self.assert_check(self.run_check(*check), False, "TS7006")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
def test_reader_type_contract_rejects_wrong_arguments(self):
|
| 124 |
source = self.root / "static/reader-usage.js"
|
|
|
|
| 119 |
source = self.root / config["files"][0]
|
| 120 |
source.write_text(source.read_text() + "\nfunction strictProbe(value) { return value; }\nstrictProbe(1);\n")
|
| 121 |
self.assert_check(self.run_check(*check), False, "TS7006")
|
| 122 |
+
shutil.copyfile(ROOT / config["files"][0], source)
|
| 123 |
+
source = self.root / "static/reader/pdf/reader-engine-preload.js"
|
| 124 |
+
self.assertIn(str(source.relative_to(self.root)), config["files"])
|
| 125 |
+
source.write_text(source.read_text() + "\nfunction strictPreloadProbe(value) { return value; }\nstrictPreloadProbe(1);\n")
|
| 126 |
+
self.assert_check(self.run_check(*check), False, "TS7006")
|
| 127 |
|
| 128 |
def test_reader_type_contract_rejects_wrong_arguments(self):
|
| 129 |
source = self.root / "static/reader-usage.js"
|