| | | 1 | | using System.Reflection; |
| | | 2 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 3 | | namespace Kestrun.Utilities; |
| | | 4 | | /// <summary> |
| | | 5 | | /// Provides extension methods for copying rate limiter options and policies. |
| | | 6 | | /// </summary> |
| | | 7 | | public static class RateLimiterOptionsExtensions |
| | | 8 | | { |
| | 0 | 9 | | private static readonly MethodInfo AddPolicyMethod = |
| | 0 | 10 | | typeof(RateLimiterOptions) |
| | 0 | 11 | | .GetMethods() |
| | 0 | 12 | | .Single(m => m.Name == "AddPolicy" && m.GetParameters().Length == 2); |
| | | 13 | | |
| | 0 | 14 | | private static readonly FieldInfo PolicyMapField = |
| | 0 | 15 | | typeof(RateLimiterOptions).GetField("PolicyMap", |
| | 0 | 16 | | BindingFlags.Instance | BindingFlags.NonPublic)!; |
| | | 17 | | |
| | 0 | 18 | | private static readonly FieldInfo UnactivatedPolicyMapField = |
| | 0 | 19 | | typeof(RateLimiterOptions).GetField("UnactivatedPolicyMap", |
| | 0 | 20 | | BindingFlags.Instance | BindingFlags.NonPublic)!; |
| | | 21 | | |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Copies all rate limiter options and policies from the source to the target <see cref="RateLimiterOptions"/>. |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="target">The target <see cref="RateLimiterOptions"/> to copy to.</param> |
| | | 27 | | /// <param name="source">The source <see cref="RateLimiterOptions"/> to copy from.</param> |
| | | 28 | | public static void CopyFrom(this RateLimiterOptions target, RateLimiterOptions source) |
| | | 29 | | { |
| | 0 | 30 | | ArgumentNullException.ThrowIfNull(source); |
| | | 31 | | |
| | | 32 | | // ───── scalar props ───── |
| | 0 | 33 | | target.GlobalLimiter = source.GlobalLimiter; |
| | 0 | 34 | | target.OnRejected = source.OnRejected; |
| | 0 | 35 | | target.RejectionStatusCode = source.RejectionStatusCode; |
| | | 36 | | |
| | | 37 | | // ───── activated policies ───── |
| | 0 | 38 | | var policyMap = (IDictionary<string, object>)PolicyMapField.GetValue(source)!; |
| | 0 | 39 | | foreach (var kvp in policyMap) |
| | | 40 | | { |
| | | 41 | | // AddPolicy(string, IRateLimiterPolicy<HttpContext>) |
| | 0 | 42 | | _ = AddPolicyMethod.Invoke(target, [kvp.Key, kvp.Value]); |
| | | 43 | | } |
| | | 44 | | |
| | | 45 | | // ───── factories awaiting DI (un-activated) ───── |
| | 0 | 46 | | var factoryMap = (IDictionary<string, object>)UnactivatedPolicyMapField.GetValue(source)!; |
| | 0 | 47 | | foreach (var kvp in factoryMap) |
| | | 48 | | { |
| | | 49 | | // AddPolicy(string, Func<IServiceProvider, IRateLimiterPolicy<HttpContext>>) |
| | 0 | 50 | | _ = AddPolicyMethod.Invoke(target, [kvp.Key, kvp.Value]); |
| | | 51 | | } |
| | 0 | 52 | | } |
| | | 53 | | } |