-
Notifications
You must be signed in to change notification settings - Fork 232
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
19 changed files
with
349 additions
and
6 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
using System; | ||
using NUnit.Framework; | ||
using RateLimiter.Exceptions; | ||
using RateLimiter.Implementations; | ||
|
||
namespace RateLimiter.Tests; | ||
|
||
[TestFixture] | ||
public class DelayRateLimiterRuleTests | ||
{ | ||
[Test] | ||
public void Validate_EnoughTime_Ok() | ||
{ | ||
// Arrange | ||
const int delay = 10; | ||
var token = Guid.NewGuid().ToString("N"); | ||
var previousRequests = Moq.RequestsDates(delay + delay / 2, delay * 2); | ||
var limiter = new DelayRateLimiterRule(TimeSpan.FromSeconds(delay)); | ||
// Act, Assert | ||
Assert.DoesNotThrow(() => limiter.Validate(token, previousRequests)); | ||
} | ||
|
||
[Test] | ||
public void Validate_NotEnoughTime_ThrowsException() | ||
{ | ||
// Arrange | ||
const int delay = 10; | ||
var token = Guid.NewGuid().ToString("N"); | ||
var previousRequests = Moq.RequestsDates(delay / 2); | ||
var limiter = new DelayRateLimiterRule(TimeSpan.FromSeconds(delay)); | ||
// Act, Assert | ||
Assert.Throws<RateLimitException>(() => limiter.Validate(token, previousRequests)); | ||
} | ||
|
||
[Test] | ||
public void Validate_NotEnoughTimeWithSelector_ThrowsException() | ||
{ | ||
// Arrange | ||
const int delay = 10; | ||
var token = "US-" + Guid.NewGuid().ToString("N"); | ||
var previousRequests = Moq.RequestsDates(delay / 2); | ||
var limiter = new DelayRateLimiterRule(TimeSpan.FromSeconds(delay), Moq.PrefixSelector("US-")); | ||
// Act, Assert | ||
Assert.Throws<RateLimitException>(() => limiter.Validate(token, previousRequests)); | ||
} | ||
|
||
[Test] | ||
public void Validate_NotApplicable_Ok() | ||
{ | ||
// Arrange | ||
const int delay = 10; | ||
var token = "EU-" + Guid.NewGuid().ToString("N"); | ||
var previousRequests = Moq.RequestsDates(delay / 2); | ||
var limiter = new DelayRateLimiterRule(TimeSpan.FromSeconds(delay), Moq.PrefixSelector("US-")); | ||
// Act, Assert | ||
Assert.DoesNotThrow(() => limiter.Validate(token, previousRequests)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using Moq; | ||
using RateLimiter.Abstractions; | ||
using RateLimiter.Exceptions; | ||
using RateLimiter.Infrastructure; | ||
|
||
namespace RateLimiter.Tests; | ||
|
||
public static class Moq | ||
{ | ||
public static IRateLimiterRule Rule(bool isSuccess) | ||
{ | ||
var mock = new Mock<IRateLimiterRule>(); | ||
if (!isSuccess) | ||
{ | ||
mock.Setup(x => x.Validate(It.IsAny<string>(), It.IsAny<IReadOnlyCollection<DateTime>>())) | ||
.Throws(new RateLimitException(string.Empty, string.Empty)); | ||
} | ||
return mock.Object; | ||
} | ||
|
||
public static Func<string, bool> PrefixSelector(string prefix) => x => x.StartsWith(prefix); | ||
|
||
public static IRequestsRepository RepositoryFromDelays(params int[] delays) | ||
{ | ||
var mock = new Mock<IRequestsRepository>(); | ||
mock.Setup(x => x.GetPreviousRequests(It.IsAny<string>())) | ||
.Returns(RequestsDates(delays)); | ||
return mock.Object; | ||
} | ||
|
||
public static List<DateTime> RequestsDates(params int[] delays) => delays.Select(x => DateTime.UtcNow.AddSeconds(-x)).ToList(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,35 @@ | ||
using NUnit.Framework; | ||
using System; | ||
using Microsoft.Extensions.Logging; | ||
using Moq; | ||
using NUnit.Framework; | ||
using RateLimiter.Exceptions; | ||
|
||
namespace RateLimiter.Tests; | ||
|
||
[TestFixture] | ||
public class RateLimiterTest | ||
{ | ||
[Test] | ||
public void Example() | ||
{ | ||
Assert.That(true, Is.True); | ||
} | ||
[Test] | ||
public void LimitRequestsForToken_Ok() | ||
{ | ||
// Arrange | ||
var token = Guid.NewGuid().ToString("N"); | ||
var limiter = new Implementations.RateLimiter([Moq.Rule(true)], | ||
Moq.RepositoryFromDelays(), | ||
Mock.Of<ILogger<Implementations.RateLimiter>>()); | ||
// Act, Assert | ||
Assert.DoesNotThrow(() => limiter.LimitRequestsForToken(token)); | ||
} | ||
|
||
[Test] | ||
public void LimitRequestsForToken_Fails() | ||
{ | ||
// Arrange | ||
var token = Guid.NewGuid().ToString("N"); | ||
var limiter = new Implementations.RateLimiter([Moq.Rule(false)], | ||
Moq.RepositoryFromDelays(), | ||
Mock.Of<ILogger<Implementations.RateLimiter>>()); | ||
// Act, Assert | ||
Assert.Throws<RateLimitException>(() => limiter.LimitRequestsForToken(token)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
using System; | ||
using NUnit.Framework; | ||
using RateLimiter.Exceptions; | ||
using RateLimiter.Implementations; | ||
|
||
namespace RateLimiter.Tests; | ||
|
||
[TestFixture] | ||
public class TimeWindowRateLimiterRuleTests | ||
{ | ||
[Test] | ||
public void Validate_EnoughTime_Ok() | ||
{ | ||
// Arrange | ||
const int delay = 10; | ||
const int maxRequests = 3; | ||
var token = Guid.NewGuid().ToString("N"); | ||
var previousRequests = Moq.RequestsDates(delay / 2, delay / 2, delay * 2); | ||
var limiter = new TimeWindowRateLimiterRule(TimeSpan.FromSeconds(delay), maxRequests); | ||
// Act, Assert | ||
Assert.DoesNotThrow(() => limiter.Validate(token, previousRequests)); | ||
} | ||
|
||
[Test] | ||
public void Validate_NotEnoughTime_ThrowsException() | ||
{ | ||
// Arrange | ||
const int delay = 10; | ||
const int maxRequests = 3; | ||
var token = Guid.NewGuid().ToString("N"); | ||
var previousRequests = Moq.RequestsDates(delay / 2, delay / 2, delay / 2); | ||
var limiter = new TimeWindowRateLimiterRule(TimeSpan.FromSeconds(delay), maxRequests); | ||
// Act, Assert | ||
Assert.Throws<RateLimitException>(() => limiter.Validate(token, previousRequests)); | ||
} | ||
|
||
[Test] | ||
public void Validate_NotEnoughTimeWithSelector_ThrowsException() | ||
{ | ||
// Arrange | ||
const int delay = 10; | ||
const int maxRequests = 3; | ||
var token = "US-" + Guid.NewGuid().ToString("N"); | ||
var previousRequests = Moq.RequestsDates(delay / 2, delay / 2, delay / 2); | ||
var limiter = new TimeWindowRateLimiterRule(TimeSpan.FromSeconds(delay), maxRequests, Moq.PrefixSelector("US-")); | ||
// Act, Assert | ||
Assert.Throws<RateLimitException>(() => limiter.Validate(token, previousRequests)); | ||
} | ||
|
||
[Test] | ||
public void Validate_NotApplicable_Ok() | ||
{ | ||
// Arrange | ||
const int delay = 10; | ||
const int maxRequests = 3; | ||
var token = "EU-" + Guid.NewGuid().ToString("N"); | ||
var previousRequests = Moq.RequestsDates(delay / 2, delay / 2, delay / 2); | ||
var limiter = new TimeWindowRateLimiterRule(TimeSpan.FromSeconds(delay), maxRequests, Moq.PrefixSelector("US-")); | ||
// Act, Assert | ||
Assert.DoesNotThrow(() => limiter.Validate(token, previousRequests)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> | ||
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=623d5d3a_002D67d2_002D4d1c_002Db3d7_002Dcabda30b9e25/@EntryIndexedValue"><SessionState ContinuousTestingMode="0" IsActive="True" Name="DelayRateLimiterRuleTests" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session">
 | ||
<TestAncestor>
 | ||
<TestId>NUnit3x::C4F9249B-010E-46BE-94B8-DD20D82F1E60::net6.0::RateLimiter.Tests.DelayRateLimiterRuleTests</TestId>
 | ||
<TestId>NUnit3x::C4F9249B-010E-46BE-94B8-DD20D82F1E60::net6.0::RateLimiter.Tests.TimeWindowRateLimiterRuleTests</TestId>
 | ||
<TestId>NUnit3x::C4F9249B-010E-46BE-94B8-DD20D82F1E60::net6.0::RateLimiter.Tests.RateLimiterTest</TestId>
 | ||
</TestAncestor>
 | ||
</SessionState></s:String></wpf:ResourceDictionary> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
namespace RateLimiter.Abstractions; | ||
|
||
public interface IRateLimiter | ||
{ | ||
public void LimitRequestsForToken(string token); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
|
||
namespace RateLimiter.Abstractions; | ||
|
||
public interface IRateLimiterRule | ||
{ | ||
void Validate(string token, IReadOnlyCollection<DateTime> previousRequests); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
using System; | ||
|
||
namespace RateLimiter.Exceptions; | ||
|
||
public class RateLimitException(string message, string ruleType) : Exception(message) | ||
{ | ||
public string RuleType => ruleType; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using RateLimiter.Exceptions; | ||
|
||
namespace RateLimiter.Implementations; | ||
|
||
public class DelayRateLimiterRule(TimeSpan timeSpan, Func<string, bool>? selector = null) : SpecificRateLimiterRule(selector) | ||
{ | ||
protected override void ValidateIfRequired(string token, IReadOnlyCollection<DateTime> previousRequests) | ||
{ | ||
if (previousRequests.Any(x => x + timeSpan >= DateTime.UtcNow)) | ||
{ | ||
throw new RateLimitException("Not enough Time since last request", nameof(DelayRateLimiterRule)); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
using System.Collections.Generic; | ||
using Microsoft.Extensions.Logging; | ||
using RateLimiter.Abstractions; | ||
using RateLimiter.Exceptions; | ||
using RateLimiter.Infrastructure; | ||
|
||
namespace RateLimiter.Implementations; | ||
|
||
public class RateLimiter : IRateLimiter | ||
{ | ||
private readonly ILogger<RateLimiter> _logger; | ||
private readonly IRequestsRepository _requestsRepository; | ||
private readonly IEnumerable<IRateLimiterRule> _rules; | ||
|
||
public RateLimiter(IEnumerable<IRateLimiterRule> rules, IRequestsRepository requestsRepository, ILogger<RateLimiter> logger) | ||
{ | ||
_rules = rules; | ||
_requestsRepository = requestsRepository; | ||
_logger = logger; | ||
} | ||
|
||
public void LimitRequestsForToken(string token) | ||
{ | ||
var previousRequests = _requestsRepository.GetPreviousRequests(token); | ||
|
||
try | ||
{ | ||
foreach (var rule in _rules) | ||
{ | ||
rule.Validate(token, previousRequests); | ||
} | ||
} | ||
catch (RateLimitException ex) | ||
{ | ||
_logger.LogInformation("Too many Attempts for Token: {Token}; Rule: {Rule}.", token, ex.RuleType); | ||
throw; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using RateLimiter.Abstractions; | ||
|
||
namespace RateLimiter.Implementations; | ||
|
||
public abstract class SpecificRateLimiterRule(Func<string, bool>? selector = null) : IRateLimiterRule | ||
{ | ||
private readonly Func<string, bool> _appliedRule = selector ?? (_ => true); | ||
|
||
public void Validate(string token, IReadOnlyCollection<DateTime> previousRequests) | ||
{ | ||
if (!_appliedRule(token)) | ||
{ | ||
return; | ||
} | ||
|
||
ValidateIfRequired(token, previousRequests); | ||
} | ||
|
||
protected abstract void ValidateIfRequired(string token, IReadOnlyCollection<DateTime> previousRequests); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using RateLimiter.Exceptions; | ||
|
||
namespace RateLimiter.Implementations; | ||
|
||
public class TimeWindowRateLimiterRule(TimeSpan timeSpan, int maxRequests, Func<string, bool>? selector = null) : SpecificRateLimiterRule(selector) | ||
{ | ||
protected override void ValidateIfRequired(string token, IReadOnlyCollection<DateTime> previousRequests) | ||
{ | ||
if (previousRequests.Count(x => DateTime.UtcNow - x <= timeSpan) >= maxRequests) | ||
{ | ||
throw new RateLimitException("Expected less requests", nameof(TimeWindowRateLimiterRule)); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
|
||
namespace RateLimiter.Infrastructure; | ||
|
||
public interface IRequestsRepository | ||
{ | ||
public IReadOnlyCollection<DateTime> GetPreviousRequests(string token); | ||
public void AddRequest(string token, DateTime date); | ||
} |
Oops, something went wrong.