Skip to content

Commit

Permalink
[js/web] workaround NPM test fetch failure (microsoft#20020)
Browse files Browse the repository at this point in the history
### 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.
  • Loading branch information
fs-eire authored and Ted Themistokleous committed May 7, 2024
1 parent adc852e commit 51e4feb
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
3 changes: 2 additions & 1 deletion js/web/test/test-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
23 changes: 21 additions & 2 deletions js/web/test/test-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,33 @@ export function bufferToBase64(buffer: Uint8Array): string {
return base64.fromByteArray(buffer);
}

async function retry<T>(fn: () => Promise<T>, maxRetries = 3, delay = 100): Promise<T> {
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());
});
}
}

Expand Down

0 comments on commit 51e4feb

Please sign in to comment.