From db1a1a79a21fffbf9ed70e35435f4b0aeab697eb Mon Sep 17 00:00:00 2001 From: Oleksandr Turevskiy Date: Thu, 16 Nov 2023 13:31:19 +0100 Subject: [PATCH] Adding timeout and retries --- src/GitHubActions.Teams.ConsoleApp/Program.cs | 9 +++- .../RetryHandler.cs | 42 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 src/GitHubActions.Teams.ConsoleApp/RetryHandler.cs diff --git a/src/GitHubActions.Teams.ConsoleApp/Program.cs b/src/GitHubActions.Teams.ConsoleApp/Program.cs index 8054264..7f12127 100644 --- a/src/GitHubActions.Teams.ConsoleApp/Program.cs +++ b/src/GitHubActions.Teams.ConsoleApp/Program.cs @@ -15,6 +15,13 @@ namespace Aliencube.GitHubActions.Teams.ConsoleApp /// public static class Program { + static Program() { + HttpClient = new HttpClient(new RetryHandler(new HttpClientHandler())) + { + Timeout = TimeSpan.FromSeconds(100) // Default one, just to be easier to customize + }; + } + /// /// Gets or sets the instance. /// @@ -23,7 +30,7 @@ public static class Program /// /// Gets or sets the instance. /// - public static HttpClient HttpClient { get; set; } = new HttpClient(); + public static HttpClient HttpClient { get; set; } private static JsonSerializerSettings settings { get; } = new JsonSerializerSettings() diff --git a/src/GitHubActions.Teams.ConsoleApp/RetryHandler.cs b/src/GitHubActions.Teams.ConsoleApp/RetryHandler.cs new file mode 100644 index 0000000..539d3bd --- /dev/null +++ b/src/GitHubActions.Teams.ConsoleApp/RetryHandler.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using CommandLine; + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Aliencube.GitHubActions.Teams.ConsoleApp +{ + public class RetryHandler : DelegatingHandler + { + // Strongly consider limiting the number of retries - "retry forever" is + // probably not the most user friendly way you could respond to "the + // network cable got pulled out." + private const int MaxRetries = 3; + + public RetryHandler(HttpMessageHandler innerHandler) + : base(innerHandler) + { } + + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + HttpResponseMessage response = null; + for (int i = 0; i < MaxRetries; i++) + { + response = await base.SendAsync(request, cancellationToken); + if (response.IsSuccessStatusCode) + { + return response; + } + } + + return response; + } + } +}