Files
xCommons/Providers/XRateLimitProvider.cs
2026-11-09 15:40:10 +03:30

164 lines
4.4 KiB
C#

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
);
}
}
}