Adding RateLimit Feature ...

This commit is contained in:
2026-11-09 15:40:10 +03:30
parent 0a8f9692dd
commit cba7637255
17 changed files with 787 additions and 10 deletions
+117
View File
@@ -0,0 +1,117 @@
using System;
using xCommons.Models;
using xCommons.Constants;
using xCommons.Extensions;
using xCommons.Interfaces;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
namespace xCommons.Attributes
{
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Method,
AllowMultiple = false,
Inherited = true
)]
public partial class XRateLimitAttribute : Attribute, IActionFilter, IOrderedFilter
{
public int Limit { get; set; } = 0;
public int Order { get; set; } = -1000;
public int PeriodSeconds { get; set; } = 0;
public string KeyPrefix { get; set; } = null;
public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip;
public void OnActionExecuting(ActionExecutingContext context)
{
//
var provider = context.HttpContext.RequestServices
.GetService<IXRateLimitProvider>();
var configuration = context.HttpContext.RequestServices
.GetService<XRateLimitConfiguration>();
//
if (provider.IsNull() ||
configuration.IsNull() ||
!provider.IsEnabled)
{
return;
}
//
var limit = Limit > 0
? Limit
: configuration.DefaultLimit;
//
var periodSeconds = PeriodSeconds > 0
? PeriodSeconds
: configuration.DefaultPeriodSeconds;
//
var key = context.HttpContext.GetXRateLimitKey(KeyMode);
if (!KeyPrefix.IsNullOrEmpty())
{
key = string.Format("{0}:{1}", KeyPrefix, key);
}
//
var result = provider.TryConsume(
key: key,
limit: limit,
periodSeconds: periodSeconds
);
//
context.HttpContext.Items[XRateLimitConstants.AppliedItemKey] = true;
WriteHeaders(context.HttpContext, result);
//
if (!result.IsAllowed)
{
//
context.Result = new ObjectResult(new
{
resetOn = result.ResetOn,
retryAfter = result.RetryAfterSeconds,
message = "Too many requests. Please try again later.",
})
{
StatusCode = configuration.StatusCode
};
}
}
public void OnActionExecuted(ActionExecutedContext context)
{ }
private static void WriteHeaders(
HttpContext context,
XRateLimitResult result
)
{
//
context.Response.Headers[XRateLimitConstants.LimitHeader] =
result.Limit.ToString();
//
context.Response.Headers[XRateLimitConstants.RemainingHeader] =
result.Remaining.ToString();
//
context.Response.Headers[XRateLimitConstants.ResetHeader] =
result.ResetOn.ToUnixTimeSeconds().ToString();
//
if (!result.IsAllowed)
{
//
context.Response.Headers[XRateLimitConstants.RetryAfterHeader] =
result.RetryAfterSeconds.ToString();
}
}
}
}
+26
View File
@@ -0,0 +1,26 @@
using xCommons.Constants;
using System.Collections.Generic;
namespace xCommons.Configurations
{
public class XRateLimitConfiguration
{
public bool Enabled { get; set; } = false;
public int StatusCode { get; set; } = 429;
public int DefaultLimit { get; set; } = 60;
public int DefaultPeriodSeconds { get; set; } = 60;
public bool ApplyToAllRoutes { get; set; } = false;
public ICollection<XRateLimitRule> Rules { get; set; } = [];
public XRateLimitKeyMode DefaultKeyMode { get; set; } = XRateLimitKeyMode.Ip;
}
public partial class XRateLimitRule
{
public int Limit { get; set; } = 60;
public bool Enabled { get; set; } = true;
public int PeriodSeconds { get; set; } = 60;
public string PathPrefix { get; set; } = "/";
public string Name { get; set; } = string.Empty;
public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip;
}
}
+1
View File
@@ -2,6 +2,7 @@ namespace xCommons.Constants {
public partial struct ConfigurationNodeNames { public partial struct ConfigurationNodeNames {
public const string CERTIFICATES_NODE = "Certificates"; public const string CERTIFICATES_NODE = "Certificates";
public const string SWAGGER_NODE = "SwaggerConfiguration"; public const string SWAGGER_NODE = "SwaggerConfiguration";
public const string RATE_LIMIT_NODE = "RateLimitConfiguration";
public const string FILE_TYPE_DETECTOR_NODE = "FileTypeDetectorConfiguration"; public const string FILE_TYPE_DETECTOR_NODE = "FileTypeDetectorConfiguration";
public const string MESSAGE_RESOURCE_TITLES_NODE = "MessageResourceTitles"; public const string MESSAGE_RESOURCE_TITLES_NODE = "MessageResourceTitles";
} }
+16
View File
@@ -0,0 +1,16 @@
namespace xCommons.Constants
{
/// <summary>
/// RateLimit Implementation Constants ...
/// </summary>
public partial struct XRateLimitConstants
{
public const string CacheKeyPrefix = "xratelimit";
public const string ClientIdHeader = "X-ClientId";
public const string RetryAfterHeader = "Retry-After";
public const string LimitHeader = "X-RateLimit-Limit";
public const string ResetHeader = "X-RateLimit-Reset";
public const string AppliedItemKey = "X-RateLimit-Applied";
public const string RemainingHeader = "X-RateLimit-Remaining";
}
}
+25
View File
@@ -0,0 +1,25 @@
using xExceptions.Attributes;
namespace xCommons.Constants
{
/// <summary>
/// RateLimiting Modes ...
/// </summary>
public enum XRateLimitKeyMode
{
[StringValue("Ip")]
Ip = 0,
[StringValue("ClientId")]
ClientId = 1,
[StringValue("User")]
User = 2,
[StringValue("Route")]
Route = 3,
[StringValue("Custom")]
Custom = 4
}
}
-1
View File
@@ -28,5 +28,4 @@ public static partial class XDIHelperExtension
services.AddXCommons(); services.AddXCommons();
services.AddXFileTypeDetector(configuration); services.AddXFileTypeDetector(configuration);
} }
} }
+88 -2
View File
@@ -14,6 +14,7 @@ using Swashbuckle.AspNetCore.SwaggerUI;
using Swashbuckle.AspNetCore.SwaggerGen; using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using xExceptions.Constants;
namespace xCommons.Extensions namespace xCommons.Extensions
{ {
@@ -39,7 +40,7 @@ namespace xCommons.Extensions
/// <param name="configuration"></param> /// <param name="configuration"></param>
/// <param name="environment"></param> /// <param name="environment"></param>
public static void AddXAppConfiguration( public static void AddXAppConfiguration(
this IServiceCollection services, this IServiceCollection services,
IConfiguration configuration, IConfiguration configuration,
string environment = null string environment = null
) )
@@ -52,6 +53,41 @@ namespace xCommons.Extensions
services.AddSingleton(appConfiguration); services.AddSingleton(appConfiguration);
} }
/// <summary>
/// Retrieve Rate Limit Configurations and Register it ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
public static void AddXRateLimitConfiguration(
this IServiceCollection source,
IConfiguration configuration
)
{
//
var config = configuration.GetXRateLimitConfiguration();
source.AddXRateLimitConfiguration(config);
}
/// <summary>
/// Register Rate Limit Configuration ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
public static void AddXRateLimitConfiguration(
this IServiceCollection source,
XRateLimitConfiguration configuration
)
{
//
if (source.IsNull())
{
XException.InvalidConfiguration.Throw();
}
//
source.AddSingleton(configuration);
}
/// <summary> /// <summary>
/// Add Environment name to XAppConfiguration ... /// Add Environment name to XAppConfiguration ...
/// </summary> /// </summary>
@@ -74,7 +110,7 @@ namespace xCommons.Extensions
{ {
appConfiguration.Environment = environmentName; appConfiguration.Environment = environmentName;
} }
} }
} }
/// <summary> /// <summary>
@@ -509,6 +545,56 @@ namespace xCommons.Extensions
}); });
} }
/// <summary>
/// Register RateLimit Service ...
/// </summary>
/// <param name="source"></param>
public static void AddXRateLimit(
this IServiceCollection source
)
{
//
source.AddMemoryCache();
source.AddSingleton<IXRateLimitProvider, XRateLimitProvider>();
}
/// <summary>
/// Register RateLimit Service ...
/// Configs Retrieved from AppSettings ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
public static void AddXRateLimit(
this IServiceCollection source,
IConfiguration configuration
)
{
//
var config = configuration.GetXRateLimitConfiguration();
source.AddXRateLimit(config);
}
/// <summary>
/// Register RateLimit Service ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
public static void AddXRateLimit(
this IServiceCollection source,
XRateLimitConfiguration configuration
)
{
//
if (configuration.IsNull())
{
XException.InvalidConfiguration.Throw();
}
//
source.AddXRateLimitConfiguration(configuration);
source.AddXRateLimit();
}
public static void AddXFileTypeDetector( public static void AddXFileTypeDetector(
this IServiceCollection source, this IServiceCollection source,
IConfiguration configuration IConfiguration configuration
+16
View File
@@ -51,6 +51,22 @@ namespace xCommons.Extensions
return xSwaggerConfigSection.Get<XSwaggerConfiguration>(); return xSwaggerConfigSection.Get<XSwaggerConfiguration>();
} }
/// <summary>
/// Retrieve RateLimit Configurations ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static XRateLimitConfiguration GetXRateLimitConfiguration(this IConfiguration source)
{
//
var section = source
.GetSection(ConfigurationNodeNames.RATE_LIMIT_NODE);
//
var result = section.Get<XRateLimitConfiguration>();
return result;
}
/// <summary> /// <summary>
/// Retrieve File Type Detector Configuration ... /// Retrieve File Type Detector Configuration ...
/// </summary> /// </summary>
+67
View File
@@ -0,0 +1,67 @@
using System.Linq;
using xCommons.Configurations;
namespace xCommons.Extensions
{
public static class XCommonsExtensions
{
/// <summary>
/// Extract RateLimit Rule based on given Path ...
/// </summary>
/// <param name="source"></param>
/// <param name="path"></param>
/// <returns></returns>
public static XRateLimitRule GetMatchingRule(
this XRateLimitConfiguration source,
string path
)
{
//
if (!source.Enabled)
{
return null;
}
//
var normalizedPath = path.IsNullOrEmpty()
? "/"
: path.ToNormalString();
//
var rule = source.Rules.IsNull()
? null
: source.Rules
.Where(r =>
!r.IsNull() &&
r.Enabled &&
!r.PathPrefix.IsNullOrEmpty() &&
normalizedPath.StartsWith(r.PathPrefix.ToNormalString()))
.OrderByDescending(r => r.PathPrefix.Length)
.FirstOrDefault();
//
if (!rule.IsNull())
{
return rule;
}
//
if (source.ApplyToAllRoutes)
{
//
return new XRateLimitRule
{
Enabled = true,
Name = "Default",
PathPrefix = "/",
Limit = source.DefaultLimit,
KeyMode = source.DefaultKeyMode,
PeriodSeconds = source.DefaultPeriodSeconds,
};
}
//
return null;
}
}
}
+88 -5
View File
@@ -1,22 +1,105 @@
using System.IO; using System.IO;
using xCommons.Constants;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
namespace xCommons.Extensions { namespace xCommons.Extensions
public static partial class XHttpContextExtensions { {
public static partial class XHttpContextExtensions
{
/// <summary> /// <summary>
/// Convert IFormFile to Bytes Array /// Convert IFormFile to Bytes Array
/// </summary> /// </summary>
/// <param name="source"></param> /// <param name="source"></param>
/// <returns></returns> /// <returns></returns>
public static byte[] ToByteArray (this IFormFile source) { public static byte[] ToByteArray(this IFormFile source)
{
// //
byte[] data; byte[] data;
using (var br = new BinaryReader (source.OpenReadStream ())) { using (var br = new BinaryReader(source.OpenReadStream()))
data = br.ReadBytes ((int) source.OpenReadStream ().Length); {
data = br.ReadBytes((int)source.OpenReadStream().Length);
} }
// //
return data; return data;
} }
/// <summary>
/// Extract Rate Limit Key ...
/// </summary>
/// <param name="source"></param>
/// <param name="keyMode"></param>
/// <returns></returns>
public static string GetXRateLimitKey(
this HttpContext source,
XRateLimitKeyMode keyMode
)
{
//
if (source.IsNull())
{
return "unknown";
}
//
switch (keyMode)
{
//
case XRateLimitKeyMode.ClientId:
{
//
var clientId = source.Request.Headers[XRateLimitConstants.ClientIdHeader].ToString();
return clientId.IsNullOrEmpty()
? "anonymous"
: clientId.ToNormalString();
}
//
case XRateLimitKeyMode.User:
{
//
var userId = source.User?.FindFirst(XCustomClaims.UserId)?.Value;
if (userId.IsNullOrEmpty())
{
userId = source.User?.Identity?.Name;
}
//
return userId.IsNullOrEmpty()
? "anonymous"
: userId.ToNormalString();
}
//
case XRateLimitKeyMode.Route:
{
//
return string.Format(
"{0}:{1}",
source.Request.Method,
source.Request.Path
).ToNormalString();
}
//
case XRateLimitKeyMode.Custom:
{
return "custom";
}
//
case XRateLimitKeyMode.Ip:
default:
{
//
return source.Connection.RemoteIpAddress
.IsNull()
? "unknown"
: source.Connection.RemoteIpAddress
.ToString()
.ToNormalString();
}
}
}
} }
} }
+17 -2
View File
@@ -1,5 +1,20 @@
using xCommons.Middlewares;
using Microsoft.AspNetCore.Builder;
namespace xCommons.Extensions namespace xCommons.Extensions
{ {
public static class XMiddlewareExtensions public static partial class XMiddlewareExtensions
{ } {
/// <summary>
/// Use XRateLimit Middleware ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static IApplicationBuilder UseXRateLimit(
this IApplicationBuilder source
)
{
return source.UseMiddleware<XRateLimitMiddleware>();
}
}
} }
+21
View File
@@ -0,0 +1,21 @@
using xCommons.Models;
using xCommons.Configurations;
namespace xCommons.Interfaces
{
public interface IXRateLimitProvider
{
bool IsEnabled { get; }
XRateLimitResult TryConsume(
string key,
int limit,
int periodSeconds
);
XRateLimitResult TryConsume(
string key,
XRateLimitRule rule
);
}
}
+115
View File
@@ -0,0 +1,115 @@
using System.Net;
using xCommons.Models;
using xCommons.Constants;
using xCommons.Attributes;
using xCommons.Extensions;
using xCommons.Interfaces;
using System.Threading.Tasks;
using xCommons.Configurations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
namespace xCommons.Middlewares
{
public class XRateLimitMiddleware
{
//
private readonly RequestDelegate next;
private readonly IXRateLimitProvider provider;
private readonly XRateLimitConfiguration configuration;
public XRateLimitMiddleware(
RequestDelegate next,
IXRateLimitProvider provider,
XRateLimitConfiguration configuration
)
{
//
this.next = next;
this.provider = provider;
this.configuration = configuration;
}
public async Task InvokeAsync(HttpContext context)
{
//
if (!provider.IsEnabled)
{
await next(context);
return;
}
//
var endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;
if (!endpoint.IsNull() &&
!endpoint.Metadata
.GetMetadata<XRateLimitAttribute>()
.IsNull()
)
{
//
await next(context);
return;
}
//
var rule = configuration.GetMatchingRule(context.Request.Path);
if (rule.IsNull())
{
await next(context);
return;
}
//
var key = context.GetXRateLimitKey(rule.KeyMode);
var result = provider.TryConsume(key, rule);
//
WriteHeaders(context, result);
//
if (!result.IsAllowed)
{
//
await context.WriteResponseAsJsonAsync(
status: (HttpStatusCode)configuration.StatusCode,
data: new
{
message = "Too many requests. Please try again later.",
retryAfter = result.RetryAfterSeconds,
resetOn = result.ResetOn
}
);
return;
}
//
await next(context);
}
private static void WriteHeaders(
HttpContext context,
XRateLimitResult result
)
{
//
context.Response.Headers[XRateLimitConstants.LimitHeader] =
result.Limit.ToString();
//
context.Response.Headers[XRateLimitConstants.RemainingHeader] =
result.Remaining.ToString();
//
context.Response.Headers[XRateLimitConstants.ResetHeader] =
result.ResetOn.ToUnixTimeSeconds().ToString();
//
if (!result.IsAllowed)
{
context.Response.Headers[XRateLimitConstants.RetryAfterHeader] =
result.RetryAfterSeconds.ToString();
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
using System;
namespace xCommons.Models
{
public class XRateLimitCounter
{
public int Count { get; set; }
public int Limit { get; set; }
public DateTimeOffset ResetOn { get; set; }
}
}
+14
View File
@@ -0,0 +1,14 @@
using System;
namespace xCommons.Models
{
public class XRateLimitResult
{
public int Limit { get; set; }
public string Key { get; set; }
public int Remaining { get; set; }
public bool IsAllowed { get; set; }
public int RetryAfterSeconds { get; set; }
public DateTimeOffset ResetOn { get; set; }
}
}
+164
View File
@@ -0,0 +1,164 @@
using System;
using xCommons.Models;
using xCommons.Constants;
using xCommons.Extensions;
using xCommons.Interfaces;
using xExceptions.Constants;
using xCommons.Configurations;
using System.Collections.Concurrent;
using Microsoft.Extensions.Caching.Memory;
namespace xCommons.Providers
{
public class XRateLimitProvider : IXRateLimitProvider
{
//
private readonly IMemoryCache cache;
private readonly XRateLimitConfiguration configuration;
private readonly ConcurrentDictionary<string, object> syncRoots = new();
public XRateLimitProvider(
IMemoryCache cache,
XRateLimitConfiguration configuration
)
{
//
this.cache = cache;
this.configuration = configuration;
}
public bool IsEnabled
{
get
{
return !configuration.IsNull() && configuration.Enabled;
}
}
public XRateLimitResult TryConsume(
string key,
XRateLimitRule rule
)
{
//
if (rule.IsNull())
{
XException.InvalidArgs.Throw();
}
//
return TryConsume(
key: key,
limit: rule.Limit,
periodSeconds: rule.PeriodSeconds
);
}
public XRateLimitResult TryConsume(
string key,
int limit,
int periodSeconds
)
{
//
if (limit <= 0 || periodSeconds <= 0)
{
XException.InvalidArgs.Throw();
}
//
var normalizedKey = BuildCacheKey(key);
var now = DateTimeOffset.UtcNow;
//
if (!IsEnabled)
{
//
return new XRateLimitResult
{
Limit = limit,
IsAllowed = true,
Remaining = limit,
Key = normalizedKey,
RetryAfterSeconds = 0,
ResetOn = now.AddSeconds(periodSeconds)
};
}
//
var syncRoot = syncRoots.GetOrAdd(
key: normalizedKey,
valueFactory: _ => new object()
);
//
lock (syncRoot)
{
//
var counter = cache.Get<XRateLimitCounter>(normalizedKey);
if (counter.IsNull() || counter.ResetOn <= now)
{
//
counter = new XRateLimitCounter
{
Count = 0,
Limit = limit,
ResetOn = now.AddSeconds(periodSeconds)
};
}
//
counter.Count++;
counter.Limit = limit;
//
var remaining = Math.Max(0, limit - counter.Count);
var isAllowed = counter.Count <= limit;
var retryAfter = isAllowed
? 0
: (int)Math.Ceiling((counter.ResetOn - now).TotalSeconds);
//
var options = new MemoryCacheEntryOptions
{
AbsoluteExpiration = counter.ResetOn
};
//
options.RegisterPostEvictionCallback((cacheKey, value, reason, state) =>
{
syncRoots.TryRemove(cacheKey.ToString(), out _);
});
//
cache.Set(normalizedKey, counter, options);
//
return new XRateLimitResult
{
Limit = limit,
Key = normalizedKey,
IsAllowed = isAllowed,
Remaining = remaining,
ResetOn = counter.ResetOn,
RetryAfterSeconds = retryAfter,
};
}
}
private static string BuildCacheKey(string key)
{
//
var normalized = key.IsNullOrEmpty()
? "anonymous"
: key.ToNormalString();
//
return string.Format(
"{0}:{1}",
XRateLimitConstants.CacheKeyPrefix,
normalized
);
}
}
}
+1
View File
@@ -47,6 +47,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />
<PackageReference Include="Microsoft.IO.RecyclableMemoryStream" Version="1.4.0" /> <PackageReference Include="Microsoft.IO.RecyclableMemoryStream" Version="1.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="4.1.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="4.1.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="3.1.32" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authorization.Policy" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authorization.Policy" Version="2.2.0" />