From 56fe0113c3e0ed30d5646d551c8e81af5104ee25 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 22 Dec 2025 15:11:02 +0000 Subject: [PATCH 1/3] Initial plan From 45f60a8fe9b5ed11800109831e5283ffd5944887 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 22 Dec 2025 15:15:48 +0000 Subject: [PATCH 2/3] Implement reflection caching for GenerateToken and ValidateAndDeserialize methods Co-authored-by: jeanlrnt <63308635+jeanlrnt@users.noreply.github.com> --- src/MiniJwt.Core/Services/MiniJwtService.cs | 58 +++++++-- .../MiniJwtTests.ReflectionCache.cs | 112 ++++++++++++++++++ 2 files changed, 157 insertions(+), 13 deletions(-) create mode 100644 src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs diff --git a/src/MiniJwt.Core/Services/MiniJwtService.cs b/src/MiniJwt.Core/Services/MiniJwtService.cs index a51c370..acd8d5b 100644 --- a/src/MiniJwt.Core/Services/MiniJwtService.cs +++ b/src/MiniJwt.Core/Services/MiniJwtService.cs @@ -8,6 +8,7 @@ using System.Globalization; using Microsoft.Extensions.Logging; using MiniJwt.Core.Models; +using System.Collections.Concurrent; namespace MiniJwt.Core.Services; @@ -25,6 +26,21 @@ public class MiniJwtService : IMiniJwtService, IDisposable private const int MinimumKeyLengthBytes = 32; // 256 bits for HS256 + // Reflection cache: stores property metadata for each type to avoid repeated reflection operations + private static readonly ConcurrentDictionary _reflectionCache = new(); + + private sealed class PropertyClaimInfo + { + public PropertyInfo Property { get; } + public string ClaimType { get; } + + public PropertyClaimInfo(PropertyInfo property, string claimType) + { + Property = property; + ClaimType = claimType; + } + } + public MiniJwtService(IOptionsMonitor optionsMonitor, ILogger logger, JwtSecurityTokenHandler tokenHandler) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); @@ -78,6 +94,26 @@ private void RefreshFromOptions(MiniJwtOptions opts) }; } + private static PropertyClaimInfo[] GetOrComputePropertyClaimInfos(Type type) + { + return _reflectionCache.GetOrAdd(type, t => + { + var props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public); + var claimInfos = new List(props.Length); + + foreach (var prop in props) + { + var attr = prop.GetCustomAttribute(); + if (attr is not null) + { + claimInfos.Add(new PropertyClaimInfo(prop, attr.ClaimType)); + } + } + + return claimInfos.ToArray(); + }); + } + /// public string? GenerateToken(T payload) { @@ -95,16 +131,14 @@ private void RefreshFromOptions(MiniJwtOptions opts) return null; } - var props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); - var claims = new List(props.Length + 1); + var propertyClaimInfos = GetOrComputePropertyClaimInfos(typeof(T)); + var claims = new List(propertyClaimInfos.Length + 1); - foreach (var prop in props) + foreach (var info in propertyClaimInfos) { - var attr = prop.GetCustomAttribute(); - if (attr is null) continue; - var raw = prop.GetValue(payload); + var raw = info.Property.GetValue(payload); if (raw is null) continue; - claims.Add(new Claim(attr.ClaimType, raw.ToString() ?? string.Empty)); + claims.Add(new Claim(info.ClaimType, raw.ToString() ?? string.Empty)); } claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); @@ -184,15 +218,13 @@ private void RefreshFromOptions(MiniJwtOptions opts) if (principal == null) return default; var result = new T(); - var props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); + var propertyClaimInfos = GetOrComputePropertyClaimInfos(typeof(T)); - foreach (var prop in props) + foreach (var info in propertyClaimInfos) { - var attr = prop.GetCustomAttribute(); - if (attr == null) continue; - var claim = principal.Claims.FirstOrDefault(c => c.Type == attr.ClaimType); + var claim = principal.Claims.FirstOrDefault(c => c.Type == info.ClaimType); if (claim == null) continue; - TrySetProperty(result, prop, claim.Value); + TrySetProperty(result, info.Property, claim.Value); } return result; diff --git a/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs b/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs new file mode 100644 index 0000000..fd87630 --- /dev/null +++ b/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs @@ -0,0 +1,112 @@ +using System; +using System.Diagnostics; +using System.Linq; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using MiniJwt.Core.Attributes; +using MiniJwt.Core.Models; +using MiniJwt.Core.Services; +using Xunit; + +namespace MiniJwt.Tests; + +public partial class MiniJwtTests +{ + private class CacheTestPayload + { + [MiniJwtClaim("test_id")] + public int Id { get; set; } + + [MiniJwtClaim("test_name")] + public string? Name { get; set; } + } + + [Fact] + public void ReflectionCache_ShouldReuseMetadata_AcrossMultipleGenerateTokenCalls() + { + // Arrange + var svc = CreateService(); + var payload1 = new CacheTestPayload { Id = 1, Name = "First" }; + var payload2 = new CacheTestPayload { Id = 2, Name = "Second" }; + + // Act - Generate multiple tokens with the same type + var token1 = svc.GenerateToken(payload1); + var token2 = svc.GenerateToken(payload2); + + // Assert - Both tokens should be generated successfully + Assert.NotNull(token1); + Assert.NotNull(token2); + + // Validate that both tokens deserialize correctly (proving cache is working) + var deserialized1 = svc.ValidateAndDeserialize(token1); + var deserialized2 = svc.ValidateAndDeserialize(token2); + + Assert.NotNull(deserialized1); + Assert.NotNull(deserialized2); + Assert.Equal(payload1.Id, deserialized1.Id); + Assert.Equal(payload1.Name, deserialized1.Name); + Assert.Equal(payload2.Id, deserialized2.Id); + Assert.Equal(payload2.Name, deserialized2.Name); + } + + [Fact] + public void ReflectionCache_ShouldWorkWithDifferentTypes() + { + // Arrange + var svc = CreateService(); + var testUser = new TestUser { Id = 1, Email = "test@test.com", Name = "User" }; + var cachePayload = new CacheTestPayload { Id = 2, Name = "Payload" }; + + // Act - Generate tokens for different types + var userToken = svc.GenerateToken(testUser); + var payloadToken = svc.GenerateToken(cachePayload); + + // Assert - Both should work correctly + Assert.NotNull(userToken); + Assert.NotNull(payloadToken); + + var deserializedUser = svc.ValidateAndDeserialize(userToken); + var deserializedPayload = svc.ValidateAndDeserialize(payloadToken); + + Assert.NotNull(deserializedUser); + Assert.NotNull(deserializedPayload); + Assert.Equal(testUser.Id, deserializedUser.Id); + Assert.Equal(testUser.Email, deserializedUser.Email); + Assert.Equal(cachePayload.Id, deserializedPayload.Id); + Assert.Equal(cachePayload.Name, deserializedPayload.Name); + } + + [Fact] + public void ReflectionCache_PerformanceTest_ShouldBeFasterOnSecondCall() + { + // This test demonstrates that the cache improves performance + // Note: This is a basic performance test and may have variability + + var svc = CreateService(); + var payload = new CacheTestPayload { Id = 1, Name = "Performance Test" }; + + // First call - will populate the cache + var sw1 = Stopwatch.StartNew(); + for (int i = 0; i < 100; i++) + { + var token = svc.GenerateToken(new CacheTestPayload { Id = i, Name = $"Test{i}" }); + Assert.NotNull(token); + } + sw1.Stop(); + + // Second batch - should use cached metadata + var sw2 = Stopwatch.StartNew(); + for (int i = 0; i < 100; i++) + { + var token = svc.GenerateToken(new CacheTestPayload { Id = i + 100, Name = $"Test{i + 100}" }); + Assert.NotNull(token); + } + sw2.Stop(); + + // The cache should make subsequent calls faster or at least not slower + // We're being lenient here as performance can vary in test environments + // The important thing is that it works correctly, not that it's always faster + Assert.True(sw2.Elapsed <= sw1.Elapsed * 2, + $"Second batch took significantly longer ({sw2.ElapsedMilliseconds}ms) than first batch ({sw1.ElapsedMilliseconds}ms), suggesting cache may not be working"); + } +} From a1f75dd8c9bf9942c765bd2536e7245ba0cd6d38 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 22 Dec 2025 16:39:18 +0000 Subject: [PATCH 3/3] Remove flaky performance test that caused CI failure Co-authored-by: jeanlrnt <63308635+jeanlrnt@users.noreply.github.com> --- .../MiniJwtTests.ReflectionCache.cs | 35 ------------------- 1 file changed, 35 deletions(-) diff --git a/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs b/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs index fd87630..0e1754e 100644 --- a/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs +++ b/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -75,38 +74,4 @@ public void ReflectionCache_ShouldWorkWithDifferentTypes() Assert.Equal(cachePayload.Id, deserializedPayload.Id); Assert.Equal(cachePayload.Name, deserializedPayload.Name); } - - [Fact] - public void ReflectionCache_PerformanceTest_ShouldBeFasterOnSecondCall() - { - // This test demonstrates that the cache improves performance - // Note: This is a basic performance test and may have variability - - var svc = CreateService(); - var payload = new CacheTestPayload { Id = 1, Name = "Performance Test" }; - - // First call - will populate the cache - var sw1 = Stopwatch.StartNew(); - for (int i = 0; i < 100; i++) - { - var token = svc.GenerateToken(new CacheTestPayload { Id = i, Name = $"Test{i}" }); - Assert.NotNull(token); - } - sw1.Stop(); - - // Second batch - should use cached metadata - var sw2 = Stopwatch.StartNew(); - for (int i = 0; i < 100; i++) - { - var token = svc.GenerateToken(new CacheTestPayload { Id = i + 100, Name = $"Test{i + 100}" }); - Assert.NotNull(token); - } - sw2.Stop(); - - // The cache should make subsequent calls faster or at least not slower - // We're being lenient here as performance can vary in test environments - // The important thing is that it works correctly, not that it's always faster - Assert.True(sw2.Elapsed <= sw1.Elapsed * 2, - $"Second batch took significantly longer ({sw2.ElapsedMilliseconds}ms) than first batch ({sw1.ElapsedMilliseconds}ms), suggesting cache may not be working"); - } }