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

+1
View File
@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A bug where casting from web included timestamp even if the "Start at" check box is unchecked - A bug where casting from web included timestamp even if the "Start at" check box is unchecked
- A leak where channel screens would reload data even when closed - A leak where channel screens would reload data even when closed
- A crash when fetching subscriptions - A crash when fetching subscriptions
- Fetching errors by adding a retry mechanism to web requests
## [0.14.0] - 2023-10-25 ## [0.14.0] - 2023-10-25
@@ -88,7 +88,7 @@ namespace Invidious
url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}` url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}`
request = HttpClient.Post(url, "") request = HttpClient.Post(url, "")
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.SendAndForget() request.Send()
end function end function
function SearchSuggestions(q as string, cancellation = invalid as object) as object function SearchSuggestions(q as string, cancellation = invalid as object) as object
@@ -149,6 +149,7 @@ namespace Invidious
request.QueryParams(m.DefaultQueryParams()) request.QueryParams(m.DefaultQueryParams())
request.Cancellation(cancellation) request.Cancellation(cancellation)
request.CacheSeconds(60 * 60 * 24)' 24 hours request.CacheSeconds(60 * 60 * 24)' 24 hours
request.TryCount(3)
return request.Await() return request.Await()
end function end function
@@ -250,6 +251,12 @@ namespace Invidious
request.CacheSeconds(endpoint.cacheSeconds) request.CacheSeconds(endpoint.cacheSeconds)
end if end if
if feedSource.tryCount <> invalid
request.TryCount(feedSource.tryCount)
else if endpoint.tryCount <> invalid
request.TryCount(endpoint.tryCount)
end if
if feedSource.queryParams <> invalid if feedSource.queryParams <> invalid
request.QueryParams(feedSource.queryParams) request.QueryParams(feedSource.queryParams)
end if end if
@@ -475,7 +482,7 @@ namespace Invidious
request.Headers(m.GetAuthenticationHeaders(authToken.token)) request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Header("Content-Type", "application/json") request.Header("Content-Type", "application/json")
request.SendAndForget() request.Send()
end function end function
function GetAuthorizeTokenLink() as dynamic function GetAuthorizeTokenLink() as dynamic
@@ -84,7 +84,7 @@ namespace SponsorBlock
end if end if
url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}` url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}`
HttpClient.Post(url, "").SendAndForget() HttpClient.Post(url, "").Send()
end function end function
function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string) function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string)
@@ -142,6 +142,7 @@ channel_info:
url: /api/v1/channels/{ucid} url: /api/v1/channels/{ucid}
responseHandler: ChannelInfoHandler responseHandler: ChannelInfoHandler
cacheSeconds: 259200 # 3 days cacheSeconds: 259200 # 3 days
tryCount: 3
# Channel endpoints # Channel endpoints
channel_videos: channel_videos:
@@ -149,6 +150,7 @@ channel_videos:
url: /api/v1/channels/{ucid}/videos url: /api/v1/channels/{ucid}/videos
responseHandler: ChannelVideosHandler responseHandler: ChannelVideosHandler
paginationType: Continuation paginationType: Continuation
tryCount: 3
queryParams: queryParams:
sort_by: sort_by:
# defaults to newest # defaults to newest
@@ -162,6 +164,7 @@ channel_playlists:
url: /api/v1/channels/{ucid}/playlists url: /api/v1/channels/{ucid}/playlists
responseHandler: ChannelPlaylistsHandler responseHandler: ChannelPlaylistsHandler
paginationType: Continuation paginationType: Continuation
tryCount: 3
queryParams: queryParams:
sort_by: sort_by:
required: false required: false
@@ -175,21 +178,25 @@ channel_shorts:
url: /api/v1/channels/{ucid}/shorts url: /api/v1/channels/{ucid}/shorts
responseHandler: ChannelVideosHandler responseHandler: ChannelVideosHandler
paginationType: Continuation paginationType: Continuation
tryCount: 3
channel_streams: channel_streams:
title: Channel streams title: Channel streams
url: /api/v1/channels/{ucid}/streams url: /api/v1/channels/{ucid}/streams
responseHandler: ChannelVideosHandler responseHandler: ChannelVideosHandler
paginationType: Continuation paginationType: Continuation
tryCount: 3
channel_podcasts: channel_podcasts:
title: Channel podcasts title: Channel podcasts
url: /api/v1/channels/{ucid}/podcasts url: /api/v1/channels/{ucid}/podcasts
responseHandler: ChannelPlaylistsHandler responseHandler: ChannelPlaylistsHandler
paginationType: Continuation paginationType: Continuation
tryCount: 3
channel_channels: channel_channels:
title: Related channels title: Related channels
url: /api/v1/channels/{ucid}/channels url: /api/v1/channels/{ucid}/channels
responseHandler: ChannelRelatedChannelsHandler responseHandler: ChannelRelatedChannelsHandler
paginationType: Continuation paginationType: Continuation
tryCount: 3
+40 -11
View File
@@ -46,6 +46,7 @@ namespace HttpClient
function new() function new()
m._timeoutSeconds = 30 m._timeoutSeconds = 30
m._tryCount = 1
end function end function
function Method(method as string) as HttpRequest function Method(method as string) as HttpRequest
@@ -141,6 +142,14 @@ namespace HttpClient
return m return m
end function end function
function TryCount(tryCount as integer) as HttpRequest
m._tryCount = ValidInt(tryCount)
if m._tryCount < 1
m._tryCount = 1
end if
return m
end function
function NoCache() as HttpRequest function NoCache() as HttpRequest
m._noCache = true m._noCache = true
return m return m
@@ -179,14 +188,6 @@ namespace HttpClient
end function end function
function Send() as HttpRequest function Send() as HttpRequest
return m.DoSend(false)
end function
function SendAndForget() as HttpRequest
return m.DoSend(true)
end function
private function DoSend(forget as boolean) as HttpRequest
if m.urlTransfer <> invalid or m._cache <> invalid if m.urlTransfer <> invalid or m._cache <> invalid
return m return m
end if end if
@@ -215,9 +216,7 @@ namespace HttpClient
m.urlTransfer.SetHeaders(m._headers) m.urlTransfer.SetHeaders(m._headers)
end if end if
if not forget m.urlTransfer.SetMessagePort(CreateObject("roMessagePort"))
m.urlTransfer.SetMessagePort(CreateObject("roMessagePort"))
end if
LogInfo("Sending", m._method, m.urlTransfer.GetURL(), "ID:", m.urlTransfer.GetIdentity()) LogInfo("Sending", m._method, m.urlTransfer.GetURL(), "ID:", m.urlTransfer.GetIdentity())
@@ -268,6 +267,36 @@ namespace HttpClient
end function end function
function Await() as HttpResponse function Await() as HttpResponse
tryCount = m._tryCount
response = invalid
response = m.AwaitInternal()
if response.IsSuccess() or response.TimedOut() or response.IsCancelled() or response.StatusCode() < 500
return response
end if
tryCount -= 1
while tryCount > 0
backoffMs = 1000 + Rnd(2000)
LogInfo("Request failed with status code:", response.StatusCode(), "ID:", m.urlTransfer.GetIdentity(), `\nRetrying:`, m._tryCount - tryCount, "in", backoffMs, "ms")
m.urlTransfer = invalid
m._cache = invalid
m._sent = invalid
sleep(backoffMs)
response = m.AwaitInternal()
if response.IsSuccess() or response.TimedOut() or response.IsCancelled() or response.StatusCode() < 500
return response
end if
tryCount -= 1
end while
return response
end function
private function AwaitInternal() as HttpResponse
if m.urlTransfer = invalid and m._cache = invalid if m.urlTransfer = invalid and m._cache = invalid
m.Send() m.Send()
end if end if
+53 -14
View File
@@ -154,7 +154,14 @@ export class InvidiousApi {
cacheSeconds = endpoint.cacheSeconds 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"]; let responseHandler = endpoint.responseHandler !== undefined ? this.responseHandlers[endpoint.responseHandler] : this.responseHandlers["DefaultHandler"];
if (!responseHandler) { if (!responseHandler) {
@@ -222,26 +229,53 @@ export class InvidiousApi {
return encodedUrl.toString(); return encodedUrl.toString();
} }
private async cachedFetch(url: string, cacheSeconds?: number) { private async cachedFetch(url: string, cacheSeconds?: number, tryCount: number = 1) {
if (!cacheSeconds) { if (cacheSeconds) {
const cache = this.getCache(url, cacheSeconds);
if (cache) {
return cache;
}
}
try {
tryCount -= 1;
const response = await fetch(url); 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); while (tryCount > 0) {
if (cache) { tryCount -= 1;
return cache; 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); try {
const data = await response.json(); const response = await fetch(url);
this.setCache(url, data); if (!response.ok) {
return data; 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 // TODO:P2 use more appropriate cache storage
private getCache(url: string, cacheSeconds: number) { private getCache(url: string, cacheSeconds: number) {
const cache = localStorage.getItem(url); const cacheKey = this.getCacheKey(url);
const cache = localStorage.getItem(cacheKey);
if (!cache) { if (!cache) {
return null; return null;
} }
@@ -260,12 +294,17 @@ export class InvidiousApi {
} }
private setCache(url: string, data: any) { private setCache(url: string, data: any) {
const cacheKey = this.getCacheKey(url);
const cacheData = { const cacheData = {
__version: 1, __version: 1,
timestamp: Date.now(), timestamp: Date.now(),
data data
}; };
localStorage.setItem(url, JSON.stringify(cacheData)); localStorage.setItem(cacheKey, JSON.stringify(cacheData));
}
private getCacheKey(url: string) {
return `v1:${url}`;
} }
} }