vomebook commited on
Commit ·
58fdd73
1
Parent(s): d888607
Keep reader retries on the proxied URL.
Browse filesA failed PDF, image, or media load used to fall back to the dataset host, which does not connect from networks that can reach the Space proxy.
Files changed (6)
- static/reader/core/reader-document-loader.mjs+4-7
- static/reader/formats/reader-media-format.mjs+7-2
- static/reader/pdf/reader-pdf-engine.mjs+3-6
- tests/gates/test_static_contract.py+2-3
- tests/reader/media/test_reader_media_metadata.mjs+18-2
- tests/reader/transport/test_reader_document_loader_contract.mjs+8-8
158 unmodified lines159160161162163164165166167168169170171158 unmodified linesimage.className = "reader-image";image.alt = readerContext.documentState.title;image.decoding = "async";try {return await readerContext.imageLoader.load(image, readerContext.readerContentUrl(target), readerContext.readerAbortController.signal, deadline);} catch (error) {readerContext.assertReaderActive();if (/** @type {ReaderLoaderError | null | undefined} */ (error)?.code === "READER_RESOURCE_LIMIT") throw error;return readerContext.imageLoader.load(image, target, readerContext.readerAbortController.signal, deadline);}}function loadChapterManifestDocument() {158 unmodified lines159160161162163164165166167168158 unmodified linesimage.className = "reader-image";image.alt = readerContext.documentState.title;image.decoding = "async";readerContext.assertReaderActive();// Do not fall through to the dataset URL. huggingface.co does not open on// this network, so a failed proxy must stay on the proxied URL.return readerContext.imageLoader.load(image, readerContext.readerContentUrl(target), readerContext.readerAbortController.signal, deadline);}function loadChapterManifestDocument() {
97 unmodified lines989910010110210310410510697 unmodified lines// The runtime capability helper stringifies unknown metadata; its ambient// declaration is narrower. This assertion preserves the original argument.const originalMode = VoiceOfMLReader.capability(/** @type {string} */ (readerContext.resolvedReaderData?.original_extension || readerContext.extension)).mode;const retryUrl = originalMode === mode && readerContext.validSource(readerContext.downloadUrl) ? readerContext.downloadUrl : readerContext.sourceUrl;const retryOriginal = () => {if (sourceRetried || retryUrl === media.src || !readerContext.validSource(retryUrl)) return false;readerContext.saveProgress();retryPosition = readerContext.documentState.restorationReady? {time:media.currentTime, playing:!media.paused, rate:media.playbackRate} : null;97 unmodified lines989910010110210310410510610710810911011197 unmodified lines// The runtime capability helper stringifies unknown metadata; its ambient// declaration is narrower. This assertion preserves the original argument.const originalMode = VoiceOfMLReader.capability(/** @type {string} */ (readerContext.resolvedReaderData?.original_extension || readerContext.extension)).mode;// A stalled proxy used to assign the dataset URL to the media element. That// URL is on huggingface.co, which this network cannot open, so the retry// never reaches metadata. Reload the same proxied URL instead.const directSource = originalMode === mode && readerContext.validSource(readerContext.downloadUrl) ? readerContext.downloadUrl : readerContext.sourceUrl;const retryUrl = readerContext.contentUrl && readerContext.contentUrl !== directSource ? readerContext.contentUrl : directSource;const retryOriginal = () => {if (sourceRetried || !readerContext.validSource(retryUrl)) return false;if (retryUrl === media.src && retryUrl === directSource) return false;readerContext.saveProgress();retryPosition = readerContext.documentState.restorationReady? {time:media.currentTime, playing:!media.paused, rate:media.playbackRate} : null;
84 unmodified lines85868788899091929394959684 unmodified lines/** @param {PdfModule} pdfjs @param {(url: string) => PdfOptions} options @param {string} originalUrl @param {string} proxyUrl @param {(url: string) => Initial} takeInitial */function loadPdfWithTimeout(pdfjs, options, originalUrl = readerContext.sourceUrl, proxyUrl = readerContext.contentUrl, takeInitial = (_url) => null) {return readerContext.retryReaderProxy(() => readerContext.loadPdfTaskWithTimeout(pdfjs, options, proxyUrl, takeInitial(proxyUrl))).catch((error) => {readerContext.assertReaderActive();if (error && (/** @type {{name?: string}} */ (error)).name === "AbortError") throw error;if (readerContext.retryableReaderProxyError(error)) throw error;return readerContext.loadPdfTaskWithTimeout(pdfjs, options, originalUrl);});}function preloadPdfEngine() {84 unmodified lines85868788899091929384 unmodified lines/** @param {PdfModule} pdfjs @param {(url: string) => PdfOptions} options @param {string} originalUrl @param {string} proxyUrl @param {(url: string) => Initial} takeInitial */function loadPdfWithTimeout(pdfjs, options, originalUrl = readerContext.sourceUrl, proxyUrl = readerContext.contentUrl, takeInitial = (_url) => null) {// Keep a failed proxy on the proxied URL. Falling through to originalUrl// opens huggingface.co directly, which does not connect on this network.return readerContext.retryReaderProxy(() => readerContext.loadPdfTaskWithTimeout(pdfjs, options, proxyUrl, takeInitial(proxyUrl)));}function preloadPdfEngine() {
665 unmodified lines666667668669670671672673674665 unmodified linesself.assertIn('method: readerId ? "GET" : "HEAD", cache: "no-store"', self.js)reader = read_reader_source(ROOT)image_loader = re.search(r'^async function loadImageDocument\([\s\S]*?^}', reader, re.M).group()assert_source_contains(self, 'return await imageLoader.load(image, readerContentUrl(target), readerAbortController.signal, deadline)', image_loader)assert_source_contains(self, 'if (/** @type {ReaderLoaderError | null | undefined} */ (error)?.code === "READER_RESOURCE_LIMIT") throw error', image_loader)assert_source_contains(self, 'return imageLoader.load(image, target, readerAbortController.signal, deadline)', image_loader)def test_image_pages_prioritize_visible_pages_without_document_image_race(self):reader = read_reader_source(ROOT)665 unmodified lines666667668669670671672673665 unmodified linesself.assertIn('method: readerId ? "GET" : "HEAD", cache: "no-store"', self.js)reader = read_reader_source(ROOT)image_loader = re.search(r'^async function loadImageDocument\([\s\S]*?^}', reader, re.M).group()assert_source_contains(self, 'return imageLoader.load(image, readerContentUrl(target), readerAbortController.signal, deadline)', image_loader)self.assertNotIn('return imageLoader.load(image, target, readerAbortController.signal, deadline)', image_loader)def test_image_pages_prioritize_visible_pages_without_document_image_race(self):reader = read_reader_source(ROOT)
47 unmodified lines4849505152535455565734 unmodified lines9293949596979847 unmodified lines} finally {f.restore();}});test('media source retries only once and restores position on metadata', async () => {const f=fixture();try {const promise=f.context.renderMedia('audio');await tick();f.media.dispatchEvent(new Event('error'));assert.equal(f.media.src,'https://test/original');assert.equal(f.media.loads,1);f.media.currentTime=0;f.media.readyState=1;f.media.dispatchEvent(new Event('loadedmetadata'));await promise;assert.equal(f.media.currentTime,4);assert.equal(f.media._readerSourceRetry,false);f.media.dispatchEvent(new Event('error'));assert.equal(f.media.loads,1);34 unmodified linesconst promise=f.context.renderMedia('audio');const hard=[...callbacks].find(([,item])=>item.delay===20000)[0];const idle=[...callbacks].find(([,item])=>item.delay===15000)[1];idle.callback();assert.equal(f.media.src,'https://test/original');assert.equal(f.media.loads,1);assert.ok(callbacks.has(hard));assert.equal([...callbacks.values()].filter(item=>item.delay===20000).length,1);f.media.readyState=1;f.media.dispatchEvent(new Event('loadedmetadata'));await promise;assert.equal(callbacks.size,0);47 unmodified lines484950515253545556575859606162636465666768697071727334 unmodified lines10810911011111211311447 unmodified lines} finally {f.restore();}});test('stalled proxy retries the proxy instead of the blocked dataset host', async () => {const f=fixture();try {f.context.sourceUrl=f.context.downloadUrl='https://huggingface.co/datasets/VoiceOfML/VOMEBOOK/resolve/main/audio.mp3';f.context.contentUrl='https://voiceofml-search.hf.space/api/reader-content?url=audio';const promise=f.context.renderMedia('audio');await tick();f.media.dispatchEvent(new Event('error'));assert.equal(f.media.src,f.context.contentUrl);assert.equal(f.media.src.includes('huggingface.co'),false);f.media.dispatchEvent(new Event('error'));assert.equal(f.media.loads,1);assert.ok(f.events.some(value=>Array.isArray(value)&&value[0]==='fail'&&value[2]==='READER_MEDIA'));f.media.readyState=1;f.media.dispatchEvent(new Event('loadedmetadata'));await assert.rejects(promise,{name:'AbortError'});} finally {f.restore();}});test('media source retries only once and restores position on metadata', async () => {const f=fixture();try {const promise=f.context.renderMedia('audio');await tick();f.media.dispatchEvent(new Event('error'));assert.equal(f.media.src,'https://test/proxy');assert.equal(f.media.loads,1);f.media.currentTime=0;f.media.readyState=1;f.media.dispatchEvent(new Event('loadedmetadata'));await promise;assert.equal(f.media.currentTime,4);assert.equal(f.media._readerSourceRetry,false);f.media.dispatchEvent(new Event('error'));assert.equal(f.media.loads,1);34 unmodified linesconst promise=f.context.renderMedia('audio');const hard=[...callbacks].find(([,item])=>item.delay===20000)[0];const idle=[...callbacks].find(([,item])=>item.delay===15000)[1];idle.callback();assert.equal(f.media.src,'https://test/proxy');assert.equal(f.media.loads,1);assert.ok(callbacks.has(hard));assert.equal([...callbacks.values()].filter(item=>item.delay===20000).length,1);f.media.readyState=1;f.media.dispatchEvent(new Event('loadedmetadata'));await promise;assert.equal(callbacks.size,0);
170 unmodified lines171172173174175176177178179180181182183184185186187188189190191192193194170 unmodified lines} finally {globalThis.document = oldDocument; globalThis.setTimeout = oldSet; globalThis.clearTimeout = oldClear;}});test("image fallback is not used for budget failures or closed readers", {timeout: 10000}, async () => {const oldImage = globalThis.Image;globalThis.Image = class {};try {const h = fixture(), calls = [];h.context.imageLoader = {load: async (image, url, signal, deadline) => {calls.push({image, url, signal, deadline});if (calls.length === 1) throw new Error("proxy unsupported");return image;}};const image = await h.loader.loadImageDocument();assert.equal(image.alt, "book"); assert.equal(calls.length, 2);assert.equal(calls[1].url, h.context.sourceUrl); assert.equal(calls[0].deadline, calls[1].deadline);let limitCalls = 0;h.context.imageLoader.load = async () => {limitCalls++; throw Object.assign(new Error("limit"), {code:"READER_RESOURCE_LIMIT"});};await assert.rejects(h.loader.loadImageDocument(), {code:"READER_RESOURCE_LIMIT"});assert.equal(limitCalls, 1, "resource-limit errors cannot start a direct fallback");h.close(); h.context.imageLoader.load = async () => {throw new Error("failed");};await assert.rejects(h.loader.loadImageDocument(), {name:"AbortError"});} finally {globalThis.Image = oldImage;}});170 unmodified lines171172173174175176177178179180181182183184185186187188189190191192193194170 unmodified lines} finally {globalThis.document = oldDocument; globalThis.setTimeout = oldSet; globalThis.clearTimeout = oldClear;}});test("image load stays on the proxy when the dataset host is unreachable", {timeout: 10000}, async () => {const oldImage = globalThis.Image;globalThis.Image = class {};try {const h = fixture(), calls = [];h.context.sourceUrl = "https://huggingface.co/datasets/VoiceOfML/VOMEBOOK/resolve/main/page.webp";h.context.imageLoader = {load: async (image, url, signal, deadline) => {calls.push({image, url, signal, deadline});if (url === h.context.sourceUrl) throw new Error("direct dataset request");return image;}};const image = await h.loader.loadImageDocument();assert.equal(image.alt, "book"); assert.equal(calls.length, 1);assert.notEqual(calls[0].url, h.context.sourceUrl);assert.equal(calls[0].url, h.context.readerContentUrl(h.context.sourceUrl));h.context.imageLoader.load = async () => {throw Object.assign(new Error("limit"), {code:"READER_RESOURCE_LIMIT"});};await assert.rejects(h.loader.loadImageDocument(), {code:"READER_RESOURCE_LIMIT"});h.close();await assert.rejects(h.loader.loadImageDocument(), {name:"AbortError"});} finally {globalThis.Image = oldImage;}});
static/reader/core/reader-document-loader.mjs+4-7
static/reader/formats/reader-media-format.mjs+7-2
static/reader/pdf/reader-pdf-engine.mjs+3-6
tests/gates/test_static_contract.py+2-3
tests/reader/media/test_reader_media_metadata.mjs+18-2
tests/reader/transport/test_reader_document_loader_contract.mjs+8-8