Implement retry mechanism (#187)

* Implement retry mechanism

* Set retry count to 3

* web app cache key

* Changelog
This commit is contained in:
Brahim Hadriche authored and GitHub committed 2023-11-05 15:11:19 -05:00
1 parent 4233f30dec
commit 8f59e3648e
6 files changed
+111 -28

No files matched your search

+53 -14
View File
@@ -154,7 +154,14 @@ export class InvidiousApi {
cacheSeconds = endpoint.cacheSeconds
}
const responseJson = await this.cachedFetch(url, cacheSeconds);
let tryCount = 1;
if (feedSource.tryCount !== undefined) {
tryCount = feedSource.tryCount
} else if (endpoint.tryCount !== undefined) {
tryCount = endpoint.tryCount
}
const responseJson = await this.cachedFetch(url, cacheSeconds, tryCount);
let responseHandler = endpoint.responseHandler !== undefined ? this.responseHandlers[endpoint.responseHandler] : this.responseHandlers["DefaultHandler"];
if (!responseHandler) {
@@ -222,26 +229,53 @@ export class InvidiousApi {
return encodedUrl.toString();
}
private async cachedFetch(url: string, cacheSeconds?: number) {
if (!cacheSeconds) {
private async cachedFetch(url: string, cacheSeconds?: number, tryCount: number = 1) {
if (cacheSeconds) {
const cache = this.getCache(url, cacheSeconds);
if (cache) {
return cache;
}
}
try {
tryCount -= 1;
const response = await fetch(url);
return await response.json();
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
this.setCache(url, data);
return data;
} catch (error) {
console.error(error);
}
const cache = this.getCache(url, cacheSeconds);
if (cache) {
return cache;
}
while (tryCount > 0) {
tryCount -= 1;
let backOffMs = 1000 + Math.floor(Math.random() * (3000 - 1000));
console.log(`Retrying ${url} in ${backOffMs}ms`);
await new Promise(resolve => setTimeout(resolve, backOffMs));
const response = await fetch(url);
const data = await response.json();
this.setCache(url, data);
return data;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
this.setCache(url, data);
return data;
} catch (error) {
console.error(error);
}
}
}
// TODO:P2 use more appropriate cache storage
private getCache(url: string, cacheSeconds: number) {
const cache = localStorage.getItem(url);
const cacheKey = this.getCacheKey(url);
const cache = localStorage.getItem(cacheKey);
if (!cache) {
return null;
}
@@ -260,12 +294,17 @@ export class InvidiousApi {
}
private setCache(url: string, data: any) {
const cacheKey = this.getCacheKey(url);
const cacheData = {
__version: 1,
timestamp: Date.now(),
data
};
localStorage.setItem(url, JSON.stringify(cacheData));
localStorage.setItem(cacheKey, JSON.stringify(cacheData));
}
private getCacheKey(url: string) {
return `v1:${url}`;
}
}