|
| 1 | +using System; |
| 2 | +using System.Net; |
| 3 | +using System.Net.Http; |
| 4 | +using System.Runtime.ExceptionServices; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using ManagedCode.Communication.Commands; |
| 8 | +using ManagedCode.Communication.Commands.Execution; |
| 9 | +using ManagedCode.Communication.Constants; |
| 10 | +using Microsoft.Extensions.Logging; |
| 11 | + |
| 12 | +namespace ManagedCode.Communication.Extensions.Http; |
| 13 | + |
| 14 | +internal sealed class CommunicationResilienceHandler : DelegatingHandler |
| 15 | +{ |
| 16 | + private readonly CommandExecutionRuntime _runtime; |
| 17 | + private readonly Func<HttpRequestMessage, bool> _shouldHandle; |
| 18 | + |
| 19 | + public CommunicationResilienceHandler(CommandHttpClientOptions options, ILogger logger) |
| 20 | + { |
| 21 | + ArgumentNullException.ThrowIfNull(options); |
| 22 | + ArgumentNullException.ThrowIfNull(logger); |
| 23 | + ArgumentNullException.ThrowIfNull(options.ShouldHandle); |
| 24 | + |
| 25 | + _shouldHandle = options.ShouldHandle; |
| 26 | + _runtime = new CommandExecutionRuntime(options.Execution, logger: logger); |
| 27 | + } |
| 28 | + |
| 29 | + protected override async Task<HttpResponseMessage> SendAsync( |
| 30 | + HttpRequestMessage request, |
| 31 | + CancellationToken cancellationToken) |
| 32 | + { |
| 33 | + ArgumentNullException.ThrowIfNull(request); |
| 34 | + if (request.Content is not null || !_shouldHandle(request)) |
| 35 | + { |
| 36 | + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| 37 | + } |
| 38 | + |
| 39 | + var command = Command.Create(HttpCommandExecutionConstants.CommandType); |
| 40 | + command.CorrelationId = ResolveAuthority(request.RequestUri); |
| 41 | + |
| 42 | + HttpResponseMessage? lastResponse = null; |
| 43 | + ExceptionDispatchInfo? lastException = null; |
| 44 | + var result = await CommandExecutor.ExecuteResultAsync<Command, HttpResponseMessage>( |
| 45 | + command, |
| 46 | + async (_, token) => |
| 47 | + { |
| 48 | + lastResponse?.Dispose(); |
| 49 | + lastResponse = null; |
| 50 | + lastException = null; |
| 51 | + |
| 52 | + using var attempt = CloneRequest(request); |
| 53 | + try |
| 54 | + { |
| 55 | + var response = await base.SendAsync(attempt, token).ConfigureAwait(false); |
| 56 | + response.RequestMessage = request; |
| 57 | + lastResponse = response; |
| 58 | + if (response.IsSuccessStatusCode) |
| 59 | + { |
| 60 | + return Result<HttpResponseMessage>.Succeed(response); |
| 61 | + } |
| 62 | + |
| 63 | + return Result<HttpResponseMessage>.Fail(CreateProblem(response)); |
| 64 | + } |
| 65 | + catch (Exception exception) when (exception is not OperationCanceledException |
| 66 | + || !cancellationToken.IsCancellationRequested) |
| 67 | + { |
| 68 | + lastException = ExceptionDispatchInfo.Capture(exception); |
| 69 | + throw; |
| 70 | + } |
| 71 | + }, |
| 72 | + _runtime, |
| 73 | + cancellationToken) |
| 74 | + .ConfigureAwait(false); |
| 75 | + |
| 76 | + if (result.IsSuccess) |
| 77 | + { |
| 78 | + return result.Value!; |
| 79 | + } |
| 80 | + |
| 81 | + if (lastResponse is not null) |
| 82 | + { |
| 83 | + return lastResponse; |
| 84 | + } |
| 85 | + |
| 86 | + lastException?.Throw(); |
| 87 | + throw new HttpRequestException( |
| 88 | + result.Problem?.Detail ?? HttpCommandExecutionConstants.ExecutionFailedDetail, |
| 89 | + null, |
| 90 | + HttpStatusCode.ServiceUnavailable); |
| 91 | + } |
| 92 | + |
| 93 | + private static HttpRequestMessage CloneRequest(HttpRequestMessage source) |
| 94 | + { |
| 95 | + var clone = new HttpRequestMessage(source.Method, source.RequestUri) |
| 96 | + { |
| 97 | + Version = source.Version, |
| 98 | + VersionPolicy = source.VersionPolicy |
| 99 | + }; |
| 100 | + |
| 101 | + foreach (var header in source.Headers) |
| 102 | + { |
| 103 | + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); |
| 104 | + } |
| 105 | + |
| 106 | + foreach (var option in source.Options) |
| 107 | + { |
| 108 | + clone.Options.Set(new HttpRequestOptionsKey<object?>(option.Key), option.Value); |
| 109 | + } |
| 110 | + |
| 111 | + return clone; |
| 112 | + } |
| 113 | + |
| 114 | + private static Problem CreateProblem(HttpResponseMessage response) |
| 115 | + { |
| 116 | + var problem = Problem.Create( |
| 117 | + response.ReasonPhrase ?? HttpCommandExecutionConstants.FailureTitle, |
| 118 | + HttpCommandExecutionConstants.FailureDetail, |
| 119 | + response.StatusCode); |
| 120 | + PromoteRetryAfter(response, problem); |
| 121 | + return problem; |
| 122 | + } |
| 123 | + |
| 124 | + private static void PromoteRetryAfter(HttpResponseMessage response, Problem problem) |
| 125 | + { |
| 126 | + var retryAfter = response.Headers.RetryAfter; |
| 127 | + if (retryAfter?.Delta is { } delta && delta >= TimeSpan.Zero) |
| 128 | + { |
| 129 | + problem.Extensions[ProblemConstants.ExtensionKeys.RetryAfter] = delta; |
| 130 | + return; |
| 131 | + } |
| 132 | + |
| 133 | + if (retryAfter?.Date is { } date) |
| 134 | + { |
| 135 | + var remaining = date - DateTimeOffset.UtcNow; |
| 136 | + problem.Extensions[ProblemConstants.ExtensionKeys.RetryAfter] = |
| 137 | + remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero; |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + private static string ResolveAuthority(Uri? requestUri) |
| 142 | + { |
| 143 | + return requestUri is { IsAbsoluteUri: true } |
| 144 | + ? requestUri.GetLeftPart(UriPartial.Authority) |
| 145 | + : HttpCommandExecutionConstants.UnknownAuthority; |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +internal static class HttpCommandExecutionConstants |
| 150 | +{ |
| 151 | + public const string CommandType = "http.client.send"; |
| 152 | + public const string UnknownAuthority = "unknown-authority"; |
| 153 | + public const string FailureTitle = "HTTP request failed"; |
| 154 | + public const string FailureDetail = "The HTTP dependency returned a non-success status code."; |
| 155 | + public const string ExecutionFailedDetail = "HTTP command execution failed before a response was received."; |
| 156 | +} |
0 commit comments