From 901bad534159e35c48bb4e42d1b49491542800ca Mon Sep 17 00:00:00 2001 From: Casper Sparre Date: Sat, 28 Feb 2026 11:34:17 +0100 Subject: [PATCH] Added retry on TooManyRequests with 1sec delay. Also added logging when it happens, with body and headers as context. --- Cajetan.OF-DL/Services/CajetanApiService.cs | 41 +++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/Cajetan.OF-DL/Services/CajetanApiService.cs b/Cajetan.OF-DL/Services/CajetanApiService.cs index fcc5d5f..7c1b8ca 100644 --- a/Cajetan.OF-DL/Services/CajetanApiService.cs +++ b/Cajetan.OF-DL/Services/CajetanApiService.cs @@ -459,4 +459,45 @@ public class CajetanApiService(IAuthService authService, IConfigService configSe MediasCount = userDto.MediasCount, }; } + + protected new async Task BuildHeaderAndExecuteRequests(Dictionary getParams, string endpoint, HttpClient client, HttpMethod? method = null, object? reqBody = null) + { + const int RETRY_ATTEMPTS = 3; + + Log.Debug("Calling BuildHeaderAndExecuteRequests"); + + for (int i = 0; i < RETRY_ATTEMPTS; i++) + { + using HttpResponseMessage response = await BuildAndExecuteAsync(); + + if (response.IsSuccessStatusCode) + return await ReadBodyAsync(response); + + if (response.StatusCode != System.Net.HttpStatusCode.TooManyRequests) + response.EnsureSuccessStatusCode(); + + string errorBody = await response.Content.ReadAsStringAsync(); + Log.ForContext("ErrorBody", errorBody) + .ForContext("ErrorHeaders", response.Headers) + .Warning("Too Many Requests -- Waiting and retrying"); + await Task.Delay(1000); + continue; + } + + throw new Exception($"Request failed after {RETRY_ATTEMPTS} attempts!"); + + async Task BuildAndExecuteAsync() + { + HttpRequestMessage request = await BuildHttpRequestMessage(getParams, endpoint, method, reqBody); + HttpResponseMessage response = await client.SendAsync(request); + return response; + } + + async Task ReadBodyAsync(HttpResponseMessage response) + { + string body = await response.Content.ReadAsStringAsync(); + Log.Debug(body); + return body; + } + } }