From 4301b0a3eebba2542d7d02bf1bdcc1cb25d15071 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 7 Sep 2024 17:15:30 +0300 Subject: [PATCH] Adds typed HTTP client to the Web client, for interacting with the API. --- .../PresentationApiLayerServices.cs | 9 + src/Lumina.Presentation.Api/Program.cs | 2 + .../Common/Api/ApiHttpClient.cs | 178 ++++++++++++++++++ .../Common/Api/IApiHttpClient.cs | 66 +++++++ .../PresentationWebLayerConfiguration.cs | 46 +++++ .../PresentationWebLayerServices.cs | 52 +++++ .../Common/Exceptions/ApiException.cs | 37 ++++ .../Lumina.Presentation.Web.csproj | 11 +- src/Lumina.Presentation.Web/Program.cs | 15 +- 9 files changed, 409 insertions(+), 7 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs create mode 100644 src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs create mode 100644 src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs create mode 100644 src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs create mode 100644 src/Lumina.Presentation.Web/Common/Exceptions/ApiException.cs diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index b7c8f07b..a4298d23 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -24,6 +24,15 @@ public static class PresentationApiLayerServices /// The updated . public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services) { + services.AddCors(options => + { + options.AddPolicy("AllowAll", + builder => builder + .AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader()); + }); + // add services to the container services.AddControllers().AddJsonOptions(options => { diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 7685e315..0a6c3d00 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -31,6 +31,8 @@ public class Program var app = builder.Build(); + app.UseCors("AllowAll"); + app.UseExceptionHandler("/error"); // uses a middleware which reexecutes the request to the error path // configure the HTTP request pipeline. diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs new file mode 100644 index 00000000..2200aaf1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -0,0 +1,178 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Models.Common; +using Lumina.Presentation.Web.Common.Models.Configuration; +using Lumina.Presentation.Web.Common.Models.FileSystem; +using Microsoft.Extensions.Options; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Presentation.Web.Common.Api; + +/// +/// Typed client for API access. +/// +public class ApiHttpClient : IApiHttpClient +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly HttpClient _httpClient; + private readonly JsonSerializerOptions _jsonOptions; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// Injected HttpClient for interacting with the API. + /// Injected server configuration application settings. + public ApiHttpClient(HttpClient httpClient, IOptionsSnapshot serverConfigurationOptions) + { + _httpClient = httpClient; + // read the API server configuration values from the configuration, and assign them to the injected client + var serverConfigurationModel = serverConfigurationOptions.Value; + httpClient.BaseAddress = new Uri(serverConfigurationModel.BaseAddress + ":" + serverConfigurationModel.Port + "/api/v1/"); + + _jsonOptions = new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the GET request. + public async Task GetAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) + { + using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); + if (!string.IsNullOrEmpty(token)) + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + return await SendRequestAsync(request, cancellationToken); + } + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result. + /// + /// The API endpoint where the request is being sent. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// A model containing the deserialized blob. + public async Task GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) + { + using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); + if (!string.IsNullOrEmpty(token)) + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + using var response = await _httpClient.SendAsync(request, cancellationToken); + if (!response.IsSuccessStatusCode) + { + // read the content as a string, for error messages + var content = await response.Content.ReadAsStringAsync(cancellationToken); + ProblemDetailsModel? problemDetails = null; + try + { + problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + } + catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } + throw new ApiException(problemDetails, response.StatusCode); + } + // if the response is successful, read it as a byte array + byte[] responseContent = await response.Content.ReadAsByteArrayAsync(cancellationToken); + string contentType = response.Content.Headers.ContentType?.ToString() ?? "application/octet-stream"; + return new BlobDataModel { Data = responseContent, ContentType = contentType }; + } + + /// + /// Sends a DELETE request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the DELETE request. + public async Task DeleteAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default) + { + using var request = new HttpRequestMessage(HttpMethod.Delete, endpoint); + if (!string.IsNullOrEmpty(token)) + _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + return await SendRequestAsync(request, cancellationToken); + } + + /// + /// Sends a PUT request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and send to the API. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the PUT request. + public async Task PutAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) + { + using var request = new HttpRequestMessage(HttpMethod.Put, endpoint); + if (!string.IsNullOrEmpty(token)) + _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); + return await SendRequestAsync(request, cancellationToken); + } + + /// + /// Sends a POST request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the POST request. + public async Task PostAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default) + { + using var request = new HttpRequestMessage(HttpMethod.Post, endpoint); + if (!string.IsNullOrEmpty(token)) + _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); + return await SendRequestAsync(request, cancellationToken); + } + + /// + /// Sends an HTTP request and deserializes the response into the specified type if the request is successful. + /// If the request fails, it attempts to deserialize the response content into a and throws an . + /// + /// The expected type of the response content. + /// The to be sent. + /// A token to cancel the operation. + /// The deserialized response content as an object of type . + /// Thrown if the response is not successful, with the if available. + private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + // send the HTTP request and read the response + var response = await _httpClient.SendAsync(request, cancellationToken); + var content = await response.Content.ReadAsStringAsync(cancellationToken); + // if the response is successful, deserialize the content to TResponse and return it + if (response.IsSuccessStatusCode) + return JsonSerializer.Deserialize(content, _jsonOptions)!; + else + { + ProblemDetailsModel? problemDetails = null; + // attempt to deserialize the response content to ProblemDetailsModel if the request fails + try + { + problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + } + catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } + throw new ApiException(problemDetails, response.StatusCode); + } + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs new file mode 100644 index 00000000..12c004a0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Models.FileSystem; +#endregion + +namespace Lumina.Presentation.Web.Common.Api; + +/// +/// Interface for typed clients for API access. +/// +public interface IApiHttpClient +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the GET request. + Task GetAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default); + + /// + /// Sends a GET request to the specified as an asynchronous operation and returns the result. + /// + /// The API endpoint where the request is being sent. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// A model containing the deserialized blob. + Task GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default); + + /// + /// Sends a DELETE request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the DELETE request. + Task DeleteAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default); + + /// + /// Sends a PUT request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and send to the API. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the PUT request. + Task PutAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default); + + /// + /// Sends a POST request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// The token used for authentication with the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the POST request. + Task PostAsync(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default); + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs new file mode 100644 index 00000000..a5d777ce --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs @@ -0,0 +1,46 @@ +using Lumina.Presentation.Web.Common.Models.Configuration; +using Lumina.Presentation.Web.Common.Utilities; +using Lumina.Presentation.Web.Common.Validators; +using Microsoft.AspNetCore.Components.WebAssembly.Hosting; + +namespace Lumina.Presentation.Web.Common.DependencyInjection; + +/// +/// Class containing the configuration bindings of the Lumina.Presentation.Web project. +/// +internal static class PresentationWebLayerConfiguration +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Extension method for adding the Lumina.Presentation.Web configuration to the . + /// + /// The to add the configuration to. + /// The updated . + public static WebAssemblyHostBuilder AddConfiguration(this WebAssemblyHostBuilder builder) + { + // add the configuration sources to the configuration builder + builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); + builder.Configuration.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true); + + builder.Services.BindConfiguration(builder.Configuration); + + return builder; + } + + /// + /// Extension method for registering the configuration options of the Lumina.Presentation.Web project into the Dependency Injection container. + /// + /// The to bind the configuration options to. + /// The configuration to be bound. + /// The updated . + internal static IServiceCollection BindConfiguration(this IServiceCollection serviceCollection, IConfiguration configuration) + { + serviceCollection.AddOptions() + .Bind(configuration.GetRequiredSection(ServerConfigurationModel.SectionName)) + .ValidateFluently() + .ValidateOnStart(); + return serviceCollection; + } + #endregion +} + diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs new file mode 100644 index 00000000..860c8141 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Services.UI; +using Lumina.Presentation.Web.Common.Api; +using Polly; +using System.Net; +using FluentValidation; +#endregion + +namespace Lumina.Presentation.Web.Common.DependencyInjection; + +/// +/// Contains all services of the Presentation Web layer. +/// +public static class PresentationWebLayerServices +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Registers the services of the Presentation Web layer into the dependency injection container. + /// + /// The service collection to add the services to. + /// The updated . + public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services) + { + // scan the current assembly for validators and register them to the DI container + services.AddValidatorsFromAssemblyContaining(ServiceLifetime.Singleton); + + // handle transient errors like network timeouts or intermittent failures + var retryPolicy = Policy + .Handle() + .OrResult(r => !r.IsSuccessStatusCode) + .WaitAndRetryAsync(3, retryAttempt => + TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); + + // use a circuit breaker to prevent repeatedly calling a failing service + var circuitBreakerPolicy = Policy + .Handle() + .OrResult(r => r.StatusCode == HttpStatusCode.InternalServerError) + .CircuitBreakerAsync(3, TimeSpan.FromSeconds(30)); + + var policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); + + // register the typed client used for the API interaction + services.AddHttpClient() + .AddPolicyHandler(retryPolicy) + .AddPolicyHandler(circuitBreakerPolicy); + + services.AddSingleton(); + + return services; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Common/Exceptions/ApiException.cs b/src/Lumina.Presentation.Web/Common/Exceptions/ApiException.cs new file mode 100644 index 00000000..51da0043 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Exceptions/ApiException.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Models.Common; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.Common.Exceptions; + +/// +/// Custom exception for interaction with the remote API. +/// +public class ApiException : Exception +{ + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets or sets the values of status codes defined for HTTP defined in RFC 2616 for HTTP 1.1. + /// + public HttpStatusCode HttpStatusCode { get; set; } + + /// + /// Gets or sets the problem details represented by this exception. + /// + public ProblemDetailsModel? ProblemDetails { get; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The problem details object returned by the API. + /// The HTTP status code returned by the API. + public ApiException(ProblemDetailsModel? problemDetails, HttpStatusCode httpStatusCode) : base(problemDetails?.Title ?? "An error occurred.") + { + ProblemDetails = problemDetails; + HttpStatusCode = httpStatusCode; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index e0ee943c..e52cf5b4 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -1,4 +1,4 @@ - + net8.0 @@ -7,15 +7,20 @@ ..\..\bin\ false - + - + + + + + + diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index f6f7b5f8..869dd6dc 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Core.Services.UI; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; +using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Application.Common.Models.FileSystem; #endregion namespace Lumina.Presentation.Web; @@ -19,13 +21,18 @@ public class Program public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); + builder.RootComponents.Add("#app"); builder.RootComponents.Add("head::after"); - builder.Services.AddSingleton(); - builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); + builder.AddConfiguration(); + builder.Services.AddPresentationWebLayerServices(); - await builder.Build().RunAsync(); + //builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); + + var webAssemblyHost = builder.Build(); + + await webAssemblyHost.RunAsync(); } #endregion } \ No newline at end of file