From 51e4feb49f0f3cf40e90de2ffcc14b2f0cb528de Mon Sep 17 00:00:00 2001 From: Yulong Wang <7679871+fs-eire@users.noreply.github.com> Date: Tue, 26 Mar 2024 21:35:49 -0700 Subject: [PATCH] [js/web] workaround NPM test fetch failure (#20020) ### Description Sometimes the `npm test` failed with an error of "TypeError: Failed to fetch". I checked the callback entry of the localhost server started by karma. When the "Failed to fetch" happens, no request is reflected on the server side. The root cause is still not identified. However, as this issue only happens sometimes when the browser is just launched by karma runner, doing retry can workaround this issue for most of the time. --- js/web/test/test-runner.ts | 3 ++- js/web/test/test-shared.ts | 23 +++++++++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/js/web/test/test-runner.ts b/js/web/test/test-runner.ts index 7c03e5b915fd7..d8ee5ef953209 100644 --- a/js/web/test/test-runner.ts +++ b/js/web/test/test-runner.ts @@ -159,7 +159,8 @@ async function initializeSession( if (preloadModelData) { session = await ort.InferenceSession.create(preloadModelData, sessionConfig); } else { - session = await ort.InferenceSession.create(modelFilePath, sessionConfig); + const modelData = await readFile(modelFilePath); + session = await ort.InferenceSession.create(modelData, sessionConfig); } } catch (e) { Logger.error( diff --git a/js/web/test/test-shared.ts b/js/web/test/test-shared.ts index 7c327e7c97ac4..55beb66e37e6e 100644 --- a/js/web/test/test-shared.ts +++ b/js/web/test/test-shared.ts @@ -15,14 +15,33 @@ export function bufferToBase64(buffer: Uint8Array): string { return base64.fromByteArray(buffer); } +async function retry(fn: () => Promise, maxRetries = 3, delay = 100): Promise { + let retries = maxRetries; + do { + try { + return await fn(); + } catch (err) { + if (retries-- === 0) { + throw err; + } + await new Promise(resolve => setTimeout(resolve, delay)); + } + // eslint-disable-next-line no-constant-condition + } while (true); +} + export async function readFile(file: string) { if (typeof process !== 'undefined' && process.versions && process.versions.node) { // node return fs.readFile(file); } else { // browser - const response = await fetch(file); - return new Uint8Array(await response.arrayBuffer()); + // + // use "retry" to workaround the error "TypeError: Failed to fetch" in some test environments + return retry(async () => { + const response = await fetch(file); + return new Uint8Array(await response.arrayBuffer()); + }); } }