Skip to content

Commit

Permalink
fix(http): add diagnostic logs to http requests
Browse files Browse the repository at this point in the history
Signed-off-by: JobaDiniz <[email protected]>
  • Loading branch information
JobaDiniz committed Apr 16, 2024
1 parent 9288c9c commit 4af86cf
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 17 deletions.
22 changes: 22 additions & 0 deletions src/Joba.IBM.RPA.Cli/Client/LogMessageHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace Joba.IBM.RPA.Cli
{
internal class LogMessageHandler : DelegatingHandler
{
private readonly ILogger logger;

public LogMessageHandler(ILogger logger, HttpMessageHandler innerHandler) : base(innerHandler) => this.logger = logger;

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var stopwatch = Stopwatch.StartNew();
logger.LogTrace("Request started [{METHOD}] {URI}", request.Method.Method, request.RequestUri);
var response = await base.SendAsync(request, cancellationToken);
stopwatch.Stop();
logger.LogTrace("Request ended [{METHOD}] {URI} ({TIME})", stopwatch.Elapsed, request.Method.Method, request.RequestUri);
return response;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ internal class RefreshTokenHttpMessageHandler : DelegatingHandler
private readonly IRenewExpiredSession sessionRenewal;

public RefreshTokenHttpMessageHandler(IRenewExpiredSession sessionRenewal, HttpMessageHandler innerHandler)
: base(innerHandler)
{
this.sessionRenewal = sessionRenewal;
}
: base(innerHandler) => this.sessionRenewal = sessionRenewal;

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellation)
{
Expand Down
21 changes: 9 additions & 12 deletions src/Joba.IBM.RPA.Cli/Client/RpaHttpClientFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public HttpClient Create(Uri address)
{
var handler = new ThrottlingHttpMessageHandler(MaxParallelism, CreateUserAgentHandler(logger));
var client = new HttpClient(handler) { BaseAddress = address };
ApplyDefaultRequestHeaders(client);
return client;
}

Expand All @@ -33,23 +32,19 @@ public HttpClient Create(Uri address, IRenewExpiredSession sessionRenewal)
var refreshTokenHandler = new RefreshTokenHttpMessageHandler(sessionRenewal, CreateUserAgentHandler(logger));
var handler = new ThrottlingHttpMessageHandler(MaxParallelism, refreshTokenHandler);
var client = new HttpClient(handler) { BaseAddress = address };
ApplyDefaultRequestHeaders(client);
return client;
}

private static void ApplyDefaultRequestHeaders(HttpClient client)
{
//TODO: invalid formats
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(RpaCommand.CommandName, RpaCommand.AssemblyVersion));
//client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(System.Environment.OSVersion.ToString()));
//client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(System.Environment.MachineName));
}

private static HttpMessageHandler CreatePolicyHandler(ILogger logger)
{
var policy = HttpPolicyExtensions.HandleTransientHttpError()
.WaitAndRetryAsync(Backoff.DecorrelatedJitterBackoffV2(TimeSpan.FromSeconds(2), 5));

return new PolicyHttpMessageHandler(policy) { InnerHandler = CreateLogHandler(logger) };
}

private static HttpClientHandler CreateCoreHandler(ILogger logger)
{
var coreHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, sslPolicyErrors) =>
Expand All @@ -67,13 +62,15 @@ private static HttpMessageHandler CreatePolicyHandler(ILogger logger)
return true; //TODO: add an option to allow users to opt-in to disregard certificate issues.
}
};
return new PolicyHttpMessageHandler(policy) { InnerHandler = coreHandler };
return coreHandler;
}

private static HttpMessageHandler CreateUserAgentHandler(ILogger logger)
{
var pollyHandler = CreatePolicyHandler(logger);
return new UserAgentHttpMessageHandler(pollyHandler);
}

private static HttpMessageHandler CreateLogHandler(ILogger logger) => new LogMessageHandler(logger, CreateCoreHandler(logger));
}
}
2 changes: 1 addition & 1 deletion src/Tests/Joba.IBM.RPA.Cli.Tests/EndToEndTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ private async Task RunAsync(string arguments, DirectoryInfo workingDirectory)
private async Task<int> StartProcessAsync(string arguments, DirectoryInfo workingDirectory)
{
logger.LogInformation($"rpa {arguments}");
arguments = $"{arguments} -v Detailed";
arguments = $"{arguments} -v Diagnostic";
var envVarName = "RPA_EXECUTABLE_PATH";
var path = System.Environment.GetEnvironmentVariable(envVarName) ?? throw new InvalidOperationException($"The environment variable {envVarName} was not set.");
var info = new ProcessStartInfo(Path.GetFullPath(path), arguments)
Expand Down

0 comments on commit 4af86cf

Please sign in to comment.