public async Task ConcurrentLimiterLimitsConcurrency() { var limiter = new ConcurrentLimiter(3); var nums = new[] { 1, 2, 3, 4 }; var stopwatch = Stopwatch.StartNew(); var results = await nums.Select( limiter, async x => { var time = stopwatch.ElapsedMilliseconds; await Task.Delay(500); return(time); }); stopwatch.Stop(); Assert.True(results[0].IsNear(0, 100)); Assert.True(results[1].IsNear(0, 100)); Assert.True(results[2].IsNear(0, 100)); Assert.True(results[3].IsNear(500, 100)); }
public HttpRequestRateLimiterMiddleware(RequestDelegate next, IOptions <HttpRequestRateLimiterOptions <TKey> > options, IConfiguration config, ILoggerFactory loggerFactory) { Next = next ?? throw new ArgumentNullException(nameof(next)); Config = config ?? throw new ArgumentNullException(nameof(config)); Options = options?.Value ?? throw new ArgumentNullException(nameof(options)); RateLimiter = new RateLimiter <TKey>(RateLimiterOptions); ConcurrentLimiter = new ConcurrentLimiter <TKey>(Options.MaxConcurrentRequestsPerSrcSubnet); }
public IpConnectionRateLimiter(string hiveName) { hiveName._NotEmptyCheck(nameof(hiveName)); this.HiveName = hiveName; using var config = new HiveData <IpConnectionRateLimiterOptions>(Hive.SharedLocalConfigHive, $"NetworkSettings/IpConnectionRateLimiter/{hiveName}", () => new IpConnectionRateLimiterOptions(), policy: HiveSyncPolicy.None); lock (config.DataLock) { this.Options = config.ManagedData; } this.RateLimiter = new RateLimiter <HashKeys.SingleIPAddress>(new RateLimiterOptions(this.Options.RateLimiter_Burst, this.Options.RateLimiter_LimitPerSecond, this.Options.RateLimiter_ExpiresMsec, this.Options.RateLimiter_EnablePenalty ? RateLimiterMode.Penalty : RateLimiterMode.NoPenalty, this.Options.RateLimiter_MaxEntries, this.Options.RateLimiter_GcIntervalMsec)); this.ConcurrentLimiter = new ConcurrentLimiter <HashKeys.SingleIPAddress>(this.Options.ConcurrentLimiter_MaxConcurrentRequestsPerSrcSubnet); if (this.Options.Common_ReportDebugLog) { this.RateLimiter.EventListener.RegisterCallback((a, b, c, d) => { string?str = d as string; if (str._IsFilled()) { Dbg.WriteLine($"IpConnectionRateLimiter[{this.HiveName}]: {str}"); } }); this.ConcurrentLimiter.EventListener.RegisterCallback((a, b, c, d) => { string?str = d as string; if (str._IsFilled()) { Dbg.WriteLine($"IpConnectionRateLimiter[{this.HiveName}]: {str}"); } }); } }