From 60b551558fad3756b1f961b6fe0f9b48e7d5dac4 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 04:04:26 -0700 Subject: [PATCH] Caches the theme API responses --- .../PresentationWebLayerServices.cs | 5 +- .../Common/Services/CachedResponse.cs | 12 +- .../Common/Services/CachedThemeHandler.cs | 138 +++++++++++++++ .../Services/ThemeCachePreferenceService.cs | 75 +++++++++ .../Services/CachedThemeHandlerTests.cs | 157 ++++++++++++++++++ 5 files changed, 385 insertions(+), 2 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs create mode 100644 src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedThemeHandlerTests.cs diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 757dc241..f409b4eb 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -292,10 +292,13 @@ public static class PresentationWebLayerServices // register the HTTP typed client used for the API interaction services.AddHttpClient() .AddHttpMessageHandler() + .AddHttpMessageHandler() .AddPolicyHandler(retryPolicy) .AddPolicyHandler(circuitBreakerPolicy); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); // enable access to the current HTTP context in non-controller classes services.AddHttpContextAccessor(); @@ -314,7 +317,7 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddSingleton(); services.AddSingleton(); - services.AddHybridCache(); // used for caching authorization roles, permissions and policies + services.AddHybridCache(); // used for caching authorization roles, permissions, policies and theme data return services; } diff --git a/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs b/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs index 156cc880..93182587 100644 --- a/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs +++ b/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs @@ -12,10 +12,20 @@ namespace Lumina.Presentation.Web.Common.Services; public class CachedResponse { /// - /// Gets or sets the content of the cached HTTP response. + /// Gets or sets the textual content of the cached HTTP response. /// public string Content { get; set; } = string.Empty; + /// + /// Gets or sets the raw bytes of the cached HTTP response. + /// + public byte[] Bytes { get; set; } = []; + + /// + /// Gets or sets the content type of the cached HTTP response. + /// + public string? ContentType { get; set; } + /// /// Gets or sets the HTTP status code of the cached response. /// diff --git a/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs b/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs new file mode 100644 index 00000000..4ec993a2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Hybrid; +using System; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Services; + +/// +/// Delegating handler that intercepts the HTTP requests to the theme endpoints of the remote API and caches their responses, +/// because the theme data is read on every page render and is only changed by the theme management operations. +/// All other requests are forwarded directly. +/// +public class CachedThemeHandler : DelegatingHandler +{ + private const string THEMES_SEGMENT = "/api/v1/themes"; + private const string THEME_CACHE_TAG = "themes"; + // responses above this size are never kept in the cache, so large binary assets do not bloat the memory + private const int MAX_CACHEABLE_BYTES = 512 * 1024; + // themes only change when the user switches, reinstalls or deletes them, so the cached responses stay valid for a long time + private static readonly TimeSpan s_cacheExpiration = TimeSpan.FromMinutes(30); + + private readonly HybridCache _hybridCache; + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly ThemeCachePreferenceService _themeCachePreferenceService; + + /// + /// Initializes a new instance of the class. + /// + /// The hybrid caching mechanism used to store and retrieve the theme responses. + /// The used to access the currently authenticated user. + /// The service used to read the per-user theme cache preference. + public CachedThemeHandler(HybridCache hybridCache, IHttpContextAccessor httpContextAccessor, ThemeCachePreferenceService themeCachePreferenceService) + { + _hybridCache = hybridCache; + _httpContextAccessor = httpContextAccessor; + _themeCachePreferenceService = themeCachePreferenceService; + } + + /// + /// Processes the HTTP request, caching the responses of the GET requests to theme endpoints and invalidating the cached + /// responses whenever a theme mutation is performed. All other requests are forwarded to the next handler in the pipeline. + /// + /// The HTTP request message to process. + /// Cancellation token that can be used to stop the execution. + /// The HTTP response message from either the cache or the original API call. + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + string requestPath = request.RequestUri!.AbsolutePath; + if (!requestPath.StartsWith(THEMES_SEGMENT, StringComparison.OrdinalIgnoreCase)) + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + + // a theme mutation replaces the theme files or the active selection, so every cached theme response becomes stale + if (!request.Method.Equals(HttpMethod.Get)) + { + HttpResponseMessage mutationResponse = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + if (mutationResponse.IsSuccessStatusCode) + await _hybridCache.RemoveByTagAsync(THEME_CACHE_TAG, cancellationToken).ConfigureAwait(false); + return mutationResponse; + } + + // the current user can switch off the theme cache from the settings page, so their requests always receive the freshly edited theme files + Guid? userId = GetCurrentUserId(); + if (userId is not null) + { + bool isCachingEnabledForUser = await _themeCachePreferenceService.GetAsync(userId.Value, defaultValue: true, cancellationToken).ConfigureAwait(false); + if (!isCachingEnabledForUser) + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + } + + // key the cached responses by the full request path and query, since each theme endpoint identifies a distinct resource + string cacheKey = $"themes:{request.RequestUri.PathAndQuery}"; + CachedResponse cached = await _hybridCache.GetOrCreateAsync( + cacheKey, + async (cancellationToken) => + { + HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + byte[] bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); + return new CachedResponse + { + Bytes = bytes, + StatusCode = response.StatusCode, + ContentType = response.Content.Headers.ContentType?.ToString() + }; + }, + new HybridCacheEntryOptions() + { + Expiration = s_cacheExpiration + }, + [THEME_CACHE_TAG], + cancellationToken); + + // failed responses are only served from the call that produced them, so a temporary failure can never be served from a stale entry + if (!IsSuccessful(cached.StatusCode) || cached.Bytes.Length > MAX_CACHEABLE_BYTES) + await _hybridCache.RemoveAsync(cacheKey, cancellationToken).ConfigureAwait(false); + + return BuildResponse(cached); + } + + /// + /// Gets the unique identifier of the currently authenticated user, when there is one. + /// + /// The unique identifier of the current user, or when the request is anonymous. + private Guid? GetCurrentUserId() + { + string? userId = _httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + return Guid.TryParse(userId, out Guid parsedUserId) ? parsedUserId : null; + } + + /// + /// Checks whether the given status code represents a successful HTTP response. + /// + /// The status code to check. + /// when the status code is a successful one, otherwise. + private static bool IsSuccessful(HttpStatusCode statusCode) + { + return statusCode >= HttpStatusCode.OK && statusCode < HttpStatusCode.MultipleChoices; + } + + /// + /// Rebuilds the HTTP response message from the cached response data. + /// + /// The cached response data. + /// The rebuilt HTTP response message. + private static HttpResponseMessage BuildResponse(CachedResponse cached) + { + HttpResponseMessage response = new(cached.StatusCode) { Content = new ByteArrayContent(cached.Bytes) }; + if (!string.IsNullOrWhiteSpace(cached.ContentType)) + response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(cached.ContentType); + return response; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs b/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs new file mode 100644 index 00000000..d6990cdb --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Caching.Hybrid; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Services; + +/// +/// Service that stores and retrieves the per-user preference for the theme cache, so the theme caching can be toggled for a user from the settings page. +/// The preference is stored in the user settings and kept in the cache so the theme cache handler can apply it on every request without querying the database. +/// +public class ThemeCachePreferenceService +{ + private const string PREFERENCE_KEY_PREFIX = "theme-cache-enabled:"; + private static readonly TimeSpan s_preferenceLifetime = TimeSpan.FromDays(30); + + private readonly HybridCache _hybridCache; + + /// + /// Initializes a new instance of the class. + /// + /// The hybrid caching mechanism used to store and retrieve the theme cache preference. + public ThemeCachePreferenceService(HybridCache hybridCache) + { + _hybridCache = hybridCache; + } + + /// + /// Gets whether the theme cache is enabled for the user identified by . + /// + /// The unique identifier of the user whose preference is read. + /// The value used when the user did not express a preference yet. + /// Cancellation token that can be used to stop the execution. + /// when the theme cache is enabled for the user, otherwise. + public async Task GetAsync(Guid userId, bool defaultValue, CancellationToken cancellationToken = default) + { + bool? preference = await _hybridCache.GetOrCreateAsync( + BuildKey(userId), + (cancellationToken) => new ValueTask(defaultValue), + new HybridCacheEntryOptions() + { + Expiration = s_preferenceLifetime + }, + cancellationToken: cancellationToken).ConfigureAwait(false); + return preference ?? defaultValue; + } + + /// + /// Sets whether the theme cache is enabled for the user identified by . + /// + /// The unique identifier of the user whose preference is written. + /// Whether the theme cache is enabled for the user, or not. + /// Cancellation token that can be used to stop the execution. + /// An awaitable task representing the asynchronous operation. + public async Task SetAsync(Guid userId, bool isEnabled, CancellationToken cancellationToken = default) + { + // the value is stored as a nullable bool, matching the read type, since HybridCache keys entries by their stored type + await _hybridCache.SetAsync(BuildKey(userId), (bool?)isEnabled, new HybridCacheEntryOptions() + { + Expiration = s_preferenceLifetime + }, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Builds the cache key of the theme cache preference of the user identified by . + /// + /// The unique identifier of the user. + /// The cache key of the preference. + private static string BuildKey(Guid userId) + { + return $"{PREFERENCE_KEY_PREFIX}{userId}"; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedThemeHandlerTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedThemeHandlerTests.cs new file mode 100644 index 00000000..c3579c3b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedThemeHandlerTests.cs @@ -0,0 +1,157 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Security.Claims; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CachedThemeHandlerTests +{ + private readonly HybridCache _hybridCache; + private readonly ThemeCachePreferenceService _themeCachePreferenceService; + + /// + /// Initializes a new instance of the class. + /// + public CachedThemeHandlerTests() + { + ServiceCollection services = new(); + services.AddHybridCache(); + _hybridCache = services.BuildServiceProvider().GetRequiredService(); + _themeCachePreferenceService = new ThemeCachePreferenceService(_hybridCache); + } + + [Fact] + public async Task SendAsync_WhenThemeGetRequestIsServedTwice_ShouldCallInnerHandlerOnlyOnce() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}""")); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/templates/shared/layout", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/templates/shared/layout", CancellationToken.None); + + // Assert + Assert.Single(messageHandler.Requests); + } + + [Fact] + public async Task SendAsync_WhenNonThemeGetRequestIsServedTwice_ShouldCallInnerHandlerTwice() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]""")); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenThemeMutationIsPerformed_ShouldInvalidateCachedThemeResponses() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}""")); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + await client.PutAsync("http://localhost:5214/api/v1/themes/current", new StringContent("""{"themeId":"lumina-default"}""", Encoding.UTF8, "application/json"), CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + + // Assert + Assert.Equal(3, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenThemeGetRequestFails_ShouldNotRetainTheFailedResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.InternalServerError)); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenThemeGetResponseExceedsMaxCacheableSize_ShouldNotCacheIt() + { + // Arrange + byte[] largeContent = new byte[600 * 1024]; + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(largeContent) }); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/assets/preview.png", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/assets/preview.png", CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenUserDisablesThemeCaching_ShouldCallInnerHandlerForEveryRequest() + { + // Arrange + Guid userId = Guid.NewGuid(); + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}""")); + HttpClient client = CreateClient(messageHandler, userId: userId); + await _themeCachePreferenceService.SetAsync(userId, isEnabled: false, CancellationToken.None); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + private HttpClient CreateClient(TestApiHttpMessageHandler messageHandler, Guid? userId = null) + { + IHttpContextAccessor httpContextAccessor = Substitute.For(); + if (userId is not null) + { + DefaultHttpContext httpContext = new(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuthentication")); + httpContextAccessor.HttpContext.Returns(httpContext); + } + CachedThemeHandler themeHandler = new(_hybridCache, httpContextAccessor, _themeCachePreferenceService) + { + InnerHandler = messageHandler + }; + return new HttpClient(themeHandler); + } + + private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json) + { + return new HttpResponseMessage(statusCode) + { + Content = new StringContent(json, Encoding.UTF8, "application/json") + }; + } +}