Skip to content

Commit

Permalink
Added retries after 502
Browse files Browse the repository at this point in the history
  • Loading branch information
nleanba committed Feb 5, 2024
1 parent 2e256ca commit 34aa2e3
Showing 1 changed file with 35 additions and 5 deletions.
40 changes: 35 additions & 5 deletions SynonymGroup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,13 @@ export type JustifiedSynonym = {
loading: boolean;
};

async function sleep(ms: number): Promise<void> {
const p = new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
return await p;
}

export class SparqlEndpoint {
constructor(private sparqlEnpointUri: string) {
}
Expand All @@ -251,11 +258,34 @@ export class SparqlEndpoint {
) {
fetchOptions.headers = fetchOptions.headers || {};
fetchOptions.headers["Accept"] = "application/sparql-results+json";
const response = await fetch(
this.sparqlEnpointUri + "?query=" + encodeURIComponent(query),
fetchOptions,
);
return await response.json();
let retryCount = 0;
// deno-lint-ignore no-explicit-any
const sendRequest = async (): Promise<any> => {
try {
const response = await fetch(
this.sparqlEnpointUri + "?query=" + encodeURIComponent(query),
fetchOptions,
);
if (!response.ok) {
throw new Error("Response not ok. Status " + response.status);
}
return await response.json();
} catch (error) {
if (error instanceof Error && error.message.endsWith("502")) {
if (retryCount < 5) {
++retryCount;
console.warn(
`!! Fetch Error: 502 Bad Gateway. Retrying in ${retryCount * 50}ms (${retryCount})`,
);
await sleep(retryCount * 50);
return await sendRequest();
}
}
console.warn("!! Fetch Error:", query, "\n---\n", error);
return {}; // as not to crash code expecting parsed json
}
};
return await sendRequest();
}
}

Expand Down

0 comments on commit 34aa2e3

Please sign in to comment.