Compare commits

...
12 Commits
Author SHA1 Message Date
saherelm d89acf612c last ... 2026-11-27 19:21:23 +03:30
saherelm 2970815270 last ... 2026-11-26 19:37:01 +03:30
saherelm 6757b2eaf6 last works on KeyedServices Feature ... 2026-11-24 10:44:27 +03:30
saherelm e2de55e8ef last works on Keyed Services ... 2026-11-24 08:25:21 +03:30
saherelm d5da835b71 add Support for XKeyedService ... 2026-11-23 16:33:11 +03:30
saherelm 939366fbb4 last ... 2026-11-16 23:11:57 +03:30
saherelm d1f940c44b Update App Configurations ... 2026-11-15 21:25:57 +03:30
saherelm a9f92c751f Fix IsExpired TTL Extensions Method ... 2026-11-13 19:00:02 +03:30
saherelm 61d8ad831e last ... 2026-11-13 13:48:10 +03:30
saherelm 5e31f8f99a add extensions method ... 2026-11-12 23:48:33 +03:30
saherelm cba7637255 Adding RateLimit Feature ... 2026-11-09 15:40:10 +03:30
saherelm 0a8f9692dd 1.1) حذف XRequestLogger Middleware
- حذف: Modules/xCommons/Middlewares/XRequestLogger.cs (144 خط)
- دلیل: منتقل شده به xLoggingService با بهبوری

1.2) تغییر Extensions
- فایل: XMiddlewareExtensions.cs
- تغییر: حذف متد UseXRequestLogger()
- نتیجه: کلاس اکنون خالی است

1.3) بهبود XLoggerModel
- اضافه: Exception property = null
- تنظیم: ترتیب Properties
2026-11-09 12:49:36 +03:30
23 changed files with 1989 additions and 180 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();
}
}
}
}
+8 -4
View File
@@ -1,21 +1,25 @@
using System.Collections.Generic; using System.Collections.Generic;
namespace xCommons.Configurations { namespace xCommons.Configurations
{
/// <summary> /// <summary>
/// represent an xBackend Application /// represent an xBackend Application
/// </summary> /// </summary>
public partial class XAppConfiguration { public partial class XAppConfiguration
{
public string Name { get; set; } public string Name { get; set; }
public string Version { get; set; } public string Version { get; set; }
public string Environment { get; set; } public string Environment { get; set; }
public string XPoweredValue { get; set; } public string XPoweredValue { get; set; }
public IEnumerable<string> AllowedOrigins { get; set; }
public string WelcomeMessage { get; set; } public string WelcomeMessage { get; set; }
public string DefaultLanguage { get; set; } public string DefaultLanguage { get; set; }
public int DefaultCacheTtlMinutes { get; set; } = 15;
public IEnumerable<string> AllowedOrigins { get; set; }
public XMessageResourceTitles MessageResourceTitles { get; set; } public XMessageResourceTitles MessageResourceTitles { get; set; }
} }
public partial class XMessageResourceTitles { public partial class XMessageResourceTitles
{
public string Terms { get; set; } public string Terms { get; set; }
public string Invite { get; set; } public string Invite { get; set; }
public string RegistrationApprove { get; set; } public string RegistrationApprove { get; set; }
+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);
} }
} }
+136 -3
View File
@@ -21,6 +21,7 @@ using System.Security.Cryptography;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using xCommons.Configurations;
namespace xCommons.Extensions namespace xCommons.Extensions
{ {
@@ -974,7 +975,7 @@ namespace xCommons.Extensions
result.Add(updateWith); result.Add(updateWith);
// //
return source; return result;
} }
/// <summary> /// <summary>
@@ -1012,7 +1013,7 @@ namespace xCommons.Extensions
result.Add(updateWith); result.Add(updateWith);
// //
return source; return result;
} }
/// <summary> /// <summary>
@@ -1050,7 +1051,27 @@ namespace xCommons.Extensions
result.Add(updateWith); result.Add(updateWith);
// //
return source; return result;
}
/// <summary>
/// Converts an Enumerable to HashSet ...
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
//
var result = new HashSet<T>();
if (source.IsNull())
{
return result;
}
//
result = [.. source];
return result;
} }
/// <summary> /// <summary>
@@ -1628,6 +1649,26 @@ namespace xCommons.Extensions
return time.IsExPired(); return time.IsExPired();
} }
/// <summary>
/// Check Specified Time is Expired or not ...
/// </summary>
/// <param name="source"></param>
/// <param name="ttlSeconds"></param>
/// <returns></returns>
public static bool IsExpiredTTL(
this DateTime source,
int ttlSeconds
)
{
//
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var result = now < new DateTimeOffset(source)
.ToUnixTimeSeconds() + ttlSeconds;
//
return result;
}
/// <summary> /// <summary>
/// Determines a File Type is Image Kind or not /// Determines a File Type is Image Kind or not
/// </summary> /// </summary>
@@ -1800,6 +1841,65 @@ namespace xCommons.Extensions
return result; return result;
} }
/// <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;
}
// //
#region Int Id Extensions ... #region Int Id Extensions ...
public static bool IsValidIntId(this int source) public static bool IsValidIntId(this int source)
@@ -1905,6 +2005,39 @@ namespace xCommons.Extensions
return Convert.ToBase64String(hash); return Convert.ToBase64String(hash);
} }
} }
/// <summary>
/// Apply Templates on provided String ...
/// </summary>
/// <param name="source"></param>
/// <param name="templates"></param>
/// <returns></returns>
public static string ApplyTemplates(
this string source,
IDictionary<string, string> templates = null
)
{
//
// Validate ...
if (source.IsNullOrEmpty() ||
!templates.HasChild())
{
return source;
}
//
var existsTemplates = templates.Where(
x => source.Contains(x.Key)
);
var result = source;
foreach (var template in existsTemplates)
{
result = result.Replace(template.Key, template.Value);
}
//
return result;
}
#endregion #endregion
// //
+99
View File
@@ -5,6 +5,7 @@ using xCommons.Filters;
using xCommons.Constants; using xCommons.Constants;
using xCommons.Providers; using xCommons.Providers;
using xCommons.Interfaces; using xCommons.Interfaces;
using xExceptions.Constants;
using xCommons.Configurations; using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
@@ -32,6 +33,19 @@ namespace xCommons.Extensions
return serviceProvider.GetService<T>(); return serviceProvider.GetService<T>();
} }
/// <summary>
/// Inject Specific Registered Services from IServiceCollection
/// </summary>
/// <param name="source"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<T> GetRegisteredServices<T>(this IServiceCollection source)
{
//
var serviceProvider = source.BuildServiceProvider();
return serviceProvider.GetServices<T>();
}
/// <summary> /// <summary>
/// Register App Configuration as a Service /// Register App Configuration as a Service
/// </summary> /// </summary>
@@ -52,6 +66,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>
@@ -509,6 +558,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
+3
View File
@@ -63,6 +63,9 @@ namespace xCommons.Extensions {
// //
var idContainer = parts[0]; var idContainer = parts[0];
var messageContainer = parts[1]; var messageContainer = parts[1];
//
// TODO: Fix this ...
} }
// //
+21
View File
@@ -19,9 +19,14 @@ namespace xCommons.Extensions
var xMessageResourceTitlesConfigSection = source var xMessageResourceTitlesConfigSection = source
.GetSection(ConfigurationNodeNames.MESSAGE_RESOURCE_TITLES_NODE); .GetSection(ConfigurationNodeNames.MESSAGE_RESOURCE_TITLES_NODE);
//
// Read TTL ...
int.TryParse(source[nameof(XAppConfiguration.DefaultCacheTtlMinutes)], out int defTTL);
// //
var result = new XAppConfiguration var result = new XAppConfiguration
{ {
DefaultCacheTtlMinutes = defTTL,
Name = source[nameof(XAppConfiguration.Name)], Name = source[nameof(XAppConfiguration.Name)],
Version = source[nameof(XAppConfiguration.Version)], Version = source[nameof(XAppConfiguration.Version)],
XPoweredValue = source[nameof(XAppConfiguration.XPoweredValue)], XPoweredValue = source[nameof(XAppConfiguration.XPoweredValue)],
@@ -51,6 +56,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>
File diff suppressed because it is too large Load Diff
+87 -4
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();
}
}
}
} }
} }
+9 -5
View File
@@ -3,14 +3,18 @@ using Microsoft.AspNetCore.Builder;
namespace xCommons.Extensions namespace xCommons.Extensions
{ {
public static class XMiddlewareExtensions public static partial class XMiddlewareExtensions
{ {
/// <summary> /// <summary>
/// Use XRequestLogger Middleware for log Requests ... /// Use XRateLimit Middleware ...
/// </summary> /// </summary>
/// <param name="app"></param> /// <param name="source"></param>
public static void UseXRequestLogger(this IApplicationBuilder app) { /// <returns></returns>
app.UseMiddleware<XRequestLogger>(); public static IApplicationBuilder UseXRateLimit(
this IApplicationBuilder source
)
{
return source.UseMiddleware<XRateLimitMiddleware>();
} }
} }
} }
-13
View File
@@ -1,13 +0,0 @@
using System;
namespace xCommons.Helpers {
public partial class XDateHelper {
/// <summary>
/// retrieve utc now timestam unix like representation ...
/// </summary>
/// <returns></returns>
public static long UtcNowTimespan () {
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds ();
}
}
}
+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();
}
}
}
}
-144
View File
@@ -1,144 +0,0 @@
using System;
using System.IO;
using xCommons.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace xCommons.Middlewares {
public partial class XRequestLogger {
private readonly ILogger logger;
private readonly RequestDelegate next;
public XRequestLogger (
RequestDelegate next,
ILoggerFactory loggerFactory
) {
//
this.next = next;
this.logger = loggerFactory
.CreateLogger<XRequestLogger> ();
}
public async Task InvokeAsync (HttpContext context) {
//
var logModel = new XLoggerModel ();
//
logModel.Path = context.Request.Path;
logModel.Schema = context.Request.Scheme;
logModel.Method = context.Request.Method;
logModel.Headers = context.Request.Headers;
logModel.Host = context.Request.Host.ToString ();
logModel.QueryString = context.Request.QueryString.ToString ();
logModel.UserID = context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Not Authenticated";
//
logModel.Connection = new XLoggerHttpConnection {
Id = context.Connection.Id,
RemoteIpAddress = context.Connection.RemoteIpAddress.ToString (),
RemotePort = context.Connection.RemotePort.ToString (),
LocalIpAddress = context.Connection.LocalIpAddress.ToString (),
LocalPort = context.Connection.LocalPort.ToString (),
};
//
// Check if a request is a Post Call so read data from Body ...
if (context.Request.Method.ToNormalString () == "post") {
//
context.Request.EnableBuffering ();
var request = await new StreamReader (context.Request.Body)
.ReadToEndAsync ();
//
context.Request.Body.Position = 0;
logModel.Request = request;
}
//
logModel.RequestedOn = DateTime.UtcNow;
//
// Do Request ...
await next.Invoke (context);
//
using (Stream originalRequest = context.Response.Body) {
try {
using (var memStream = new MemoryStream ()) {
//
context.Response.Body = memStream;
//
// All the Request processing as described above
// happens from here.
// Response handling starts from here
// set the pointer to the beginning of the
// memory stream to read
memStream.Position = 0;
//
// read the memory stream till the end
var response = await new StreamReader (memStream)
.ReadToEndAsync ();
//
logModel.Response = response;
logModel.RespondedOn = DateTime.UtcNow;
logModel.StatusCode = context.Response.StatusCode;
logModel.IsSucceed = context.Response.StatusCode >= 200 && context.Response.StatusCode <= 299;
//
// since we have read till the end of the stream,
// reset it onto the first position
memStream.Position = 0;
//
// now copy the content of the temporary memory
// stream we have passed to the actual response body
// which will carry the response out.
await memStream.CopyToAsync (originalRequest);
}
} catch (Exception ex) {
//
// Log Exception ...
logger.LogError ($"Error on Logging Request/Response ... {ex.ToJSON()}");
} finally {
//
// assign the response body to the actual context
context.Response.Body = originalRequest;
}
}
//
// Log Response ...
logger.LogCritical ($"Http Response/Response Information:{Environment.NewLine}" +
$"Schema:{logModel.Schema} " + Environment.NewLine +
$"Host: {logModel.Host} " + Environment.NewLine +
$"Path: {logModel.Path} " + Environment.NewLine +
$"Method: {logModel.Method} " + Environment.NewLine +
$"UserID: {logModel.UserID} " + Environment.NewLine +
$"QueryString: {context.Request.QueryString} " + Environment.NewLine +
$"Headers: {logModel.Headers.ToJSON()}" + Environment.NewLine +
$"" + Environment.NewLine +
$"Http Connection: " + Environment.NewLine +
$"Id: {logModel.Connection.Id}" + Environment.NewLine +
$"RemoteIpAddress: {logModel.Connection.RemoteIpAddress}" + Environment.NewLine +
$"RemotePort: {logModel.Connection.RemotePort}" + Environment.NewLine +
$"LocalIpAddress: {logModel.Connection.LocalIpAddress}" + Environment.NewLine +
$"LocalPort: {logModel.Connection.LocalPort}" + Environment.NewLine +
$"" + Environment.NewLine +
$"Request Body: {logModel.Request}" + Environment.NewLine +
$"RequestedOn: {logModel.RequestedOn}" + Environment.NewLine +
$"" + Environment.NewLine +
$"IsSucceed: {logModel.IsSucceed}" + Environment.NewLine +
$"StatucCode: {logModel.StatusCode}" + Environment.NewLine +
$"Response Body: {logModel.Response}" + Environment.NewLine +
$"RespondedOn: {logModel.RespondedOn}" + Environment.NewLine +
$"" + Environment.NewLine
);
}
}
}
+4 -3
View File
@@ -3,19 +3,20 @@ using Microsoft.AspNetCore.Http;
namespace xCommons.Models { namespace xCommons.Models {
public class XLoggerModel { public class XLoggerModel {
public string Schema { get; set; }
public string Host { get; set; } public string Host { get; set; }
public string Path { get; set; } public string Path { get; set; }
public string Schema { get; set; }
public string Method { get; set; } public string Method { get; set; }
public string UserID { get; set; } public string UserID { get; set; }
public string QueryString { get; set; }
public IHeaderDictionary Headers { get; set; }
public string Request { get; set; } public string Request { get; set; }
public int StatusCode { get; set; } public int StatusCode { get; set; }
public bool IsSucceed { get; set; } public bool IsSucceed { get; set; }
public string Response { get; set; } public string Response { get; set; }
public string QueryString { get; set; }
public DateTime RequestedOn { get; set; } public DateTime RequestedOn { get; set; }
public DateTime RespondedOn { get; set; } public DateTime RespondedOn { get; set; }
public IHeaderDictionary Headers { get; set; }
public Exception Exception { get; set; } = null;
public XLoggerHttpConnection Connection { get; set; } public XLoggerHttpConnection Connection { get; set; }
} }
+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" />