mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 19:21:10 +00:00
Caches the theme API responses
This commit is contained in:
1 parent
88db2e0801
commit
60b551558f
5 files changed
+385
-2
No files matched your search
+4
-1
@@ -292,10 +292,13 @@ public static class PresentationWebLayerServices
|
||||
// register the HTTP typed client used for the API interaction
|
||||
services.AddHttpClient<IApiHttpClient, ApiHttpClient>()
|
||||
.AddHttpMessageHandler<CachedAuthorizationHandler>()
|
||||
.AddHttpMessageHandler<CachedThemeHandler>()
|
||||
.AddPolicyHandler(retryPolicy)
|
||||
.AddPolicyHandler(circuitBreakerPolicy);
|
||||
|
||||
services.AddScoped<CachedAuthorizationHandler>();
|
||||
services.AddScoped<CachedThemeHandler>();
|
||||
services.AddScoped<ThemeCachePreferenceService>();
|
||||
|
||||
// enable access to the current HTTP context in non-controller classes
|
||||
services.AddHttpContextAccessor();
|
||||
@@ -314,7 +317,7 @@ public static class PresentationWebLayerServices
|
||||
services.AddScoped<Authorization.IAuthorizationService, AuthorizationService>();
|
||||
services.AddSingleton<ICryptographyService, CryptographyService>();
|
||||
services.AddSingleton<IUrlService, UrlService>();
|
||||
services.AddHybridCache(); // used for caching authorization roles, permissions and policies
|
||||
services.AddHybridCache(); // used for caching authorization roles, permissions, policies and theme data
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -12,10 +12,20 @@ namespace Lumina.Presentation.Web.Common.Services;
|
||||
public class CachedResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the content of the cached HTTP response.
|
||||
/// Gets or sets the textual content of the cached HTTP response.
|
||||
/// </summary>
|
||||
public string Content { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the raw bytes of the cached HTTP response.
|
||||
/// </summary>
|
||||
public byte[] Bytes { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the content type of the cached HTTP response.
|
||||
/// </summary>
|
||||
public string? ContentType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the HTTP status code of the cached response.
|
||||
/// </summary>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CachedThemeHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="hybridCache">The hybrid caching mechanism used to store and retrieve the theme responses.</param>
|
||||
/// <param name="httpContextAccessor">The <see cref="IHttpContextAccessor"/> used to access the currently authenticated user.</param>
|
||||
/// <param name="themeCachePreferenceService">The service used to read the per-user theme cache preference.</param>
|
||||
public CachedThemeHandler(HybridCache hybridCache, IHttpContextAccessor httpContextAccessor, ThemeCachePreferenceService themeCachePreferenceService)
|
||||
{
|
||||
_hybridCache = hybridCache;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_themeCachePreferenceService = themeCachePreferenceService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="request">The HTTP request message to process.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The HTTP response message from either the cache or the original API call.</returns>
|
||||
protected override async Task<HttpResponseMessage> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the unique identifier of the currently authenticated user, when there is one.
|
||||
/// </summary>
|
||||
/// <returns>The unique identifier of the current user, or <see langword="null"/> when the request is anonymous.</returns>
|
||||
private Guid? GetCurrentUserId()
|
||||
{
|
||||
string? userId = _httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
return Guid.TryParse(userId, out Guid parsedUserId) ? parsedUserId : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the given status code represents a successful HTTP response.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The status code to check.</param>
|
||||
/// <returns><see langword="true"/> when the status code is a successful one, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsSuccessful(HttpStatusCode statusCode)
|
||||
{
|
||||
return statusCode >= HttpStatusCode.OK && statusCode < HttpStatusCode.MultipleChoices;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the HTTP response message from the cached response data.
|
||||
/// </summary>
|
||||
/// <param name="cached">The cached response data.</param>
|
||||
/// <returns>The rebuilt HTTP response message.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeCachePreferenceService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="hybridCache">The hybrid caching mechanism used to store and retrieve the theme cache preference.</param>
|
||||
public ThemeCachePreferenceService(HybridCache hybridCache)
|
||||
{
|
||||
_hybridCache = hybridCache;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the theme cache is enabled for the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The unique identifier of the user whose preference is read.</param>
|
||||
/// <param name="defaultValue">The value used when the user did not express a preference yet.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns><see langword="true"/> when the theme cache is enabled for the user, <see langword="false"/> otherwise.</returns>
|
||||
public async Task<bool> GetAsync(Guid userId, bool defaultValue, CancellationToken cancellationToken = default)
|
||||
{
|
||||
bool? preference = await _hybridCache.GetOrCreateAsync(
|
||||
BuildKey(userId),
|
||||
(cancellationToken) => new ValueTask<bool?>(defaultValue),
|
||||
new HybridCacheEntryOptions()
|
||||
{
|
||||
Expiration = s_preferenceLifetime
|
||||
},
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
return preference ?? defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets whether the theme cache is enabled for the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The unique identifier of the user whose preference is written.</param>
|
||||
/// <param name="isEnabled">Whether the theme cache is enabled for the user, or not.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An awaitable task representing the asynchronous operation.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the cache key of the theme cache preference of the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The unique identifier of the user.</param>
|
||||
/// <returns>The cache key of the preference.</returns>
|
||||
private static string BuildKey(Guid userId)
|
||||
{
|
||||
return $"{PREFERENCE_KEY_PREFIX}{userId}";
|
||||
}
|
||||
}
|
||||
+157
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CachedThemeHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CachedThemeHandlerTests
|
||||
{
|
||||
private readonly HybridCache _hybridCache;
|
||||
private readonly ThemeCachePreferenceService _themeCachePreferenceService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CachedThemeHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public CachedThemeHandlerTests()
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddHybridCache();
|
||||
_hybridCache = services.BuildServiceProvider().GetRequiredService<HybridCache>();
|
||||
_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<IHttpContextAccessor>();
|
||||
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")
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user