Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

James Evers #258

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions RateLimiter.Tests/RateLimiter.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.4.2" />
</ItemGroup>
Expand Down
13 changes: 0 additions & 13 deletions RateLimiter.Tests/RateLimiterTest.cs

This file was deleted.

80 changes: 80 additions & 0 deletions RateLimiter.Tests/RejectRateLimiterTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using NUnit.Framework;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace RateLimiter.Tests;

[TestFixture]
public class RejectRateLimiterTest
{
[Test]
public void Example()
{
Assert.That(true, Is.True);
}

[Test]
public void AllowedLimitTest()
{
var callLimiter = new RejectRateLimiter(2,TimeSpan.FromSeconds(5));
var limiterToken = "1:1";

Assert.That(callLimiter.CheckRequest(limiterToken), Is.True);
Assert.That(callLimiter.CheckRequest(limiterToken), Is.True);
Assert.That(callLimiter.CheckRequest(limiterToken), Is.False);
Thread.Sleep(TimeSpan.FromSeconds(5));
Assert.That(callLimiter.CheckRequest(limiterToken), Is.True);
}

[Test]
public void IntervalTest() {
var callLimiter = new RejectRateLimiter(1, TimeSpan.FromSeconds(5));
var limiterToken = "1:1";
Assert.That(callLimiter.CheckRequest(limiterToken), Is.True);
Assert.That(callLimiter.CheckRequest(limiterToken), Is.False);
Assert.That(callLimiter.CheckRequest(limiterToken), Is.False);
Thread.Sleep(TimeSpan.FromSeconds(5));
Assert.That(callLimiter.CheckRequest(limiterToken), Is.True);
}

[Test]
public void Multithreaded_Test_For_RejectRateLimiter()
{
var callLimiter = new RejectRateLimiter(2, TimeSpan.FromSeconds(5));
var limiterToken = "1:1";

int successfulRequests = 0;
int failedRequests = 0;

// Define a multithreaded task
var tasks = new Task[10];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Run(() =>
{
if (callLimiter.CheckRequest(limiterToken))
{
Interlocked.Increment(ref successfulRequests);
}
else
{
Interlocked.Increment(ref failedRequests);
}
});
}

// Wait for all tasks to complete
Task.WaitAll(tasks);

// Validate the results
Assert.That(successfulRequests, Is.EqualTo(2)); // Only 2 requests should succeed
Assert.That(failedRequests, Is.EqualTo(8)); // The rest should fail

// Sleep for the time limit to reset
Thread.Sleep(TimeSpan.FromSeconds(5));

// Validate that after the time reset, a request succeeds
Assert.That(callLimiter.CheckRequest(limiterToken), Is.True);
}
}
27 changes: 27 additions & 0 deletions RateLimiter.Tests/UserRateLimiter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Moq;
using NUnit.Framework;
using RateLimiter.ExampleUserSetup;
using System;
using System.Threading;

namespace RateLimiter.Tests;

[TestFixture]
public class UserRateLimiterTest
{
[Test]
public void Test_User_Resource()
{
var rateLimiter = new RejectRateLimiter(2,TimeSpan.FromSeconds(5));

var userRateLimiter = new UsersRateLimiter(rateLimiter);

var mockUser = new Mock<IUser>();
mockUser.SetupGet(x => x.Name).Returns("Mary");
var user = mockUser.Object;

Assert.That(userRateLimiter.CheckRequest(user, "DoSomething"), Is.True);
Assert.That(userRateLimiter.CheckRequest(user, "DoSomething"), Is.True);
Assert.That(userRateLimiter.CheckRequest(user, "DoSomething"), Is.False);
}
}
13 changes: 13 additions & 0 deletions RateLimiter/ExampleUserSetup/IUser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RateLimiter.ExampleUserSetup
{
public interface IUser
{
string Name { get; }
}
}
24 changes: 24 additions & 0 deletions RateLimiter/ExampleUserSetup/UserRateLimiter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading.Tasks;

namespace RateLimiter.ExampleUserSetup
{
public class UsersRateLimiter
{
private IRateLimiter RateLimiter { get; }
public UsersRateLimiter(IRateLimiter rateLimiter)
{
RateLimiter = rateLimiter;
}
public bool CheckRequest(IUser user, string route)
{
return RateLimiter.CheckRequest($"{user.Name}:{route}");
}


}
}
15 changes: 15 additions & 0 deletions RateLimiter/IRateLimiter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RateLimiter
{
public interface IRateLimiter
{
int RequestLimit { get; }
TimeSpan Interval { get; }
bool CheckRequest(string limiterToken);
}
}
3 changes: 3 additions & 0 deletions RateLimiter/RateLimiter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EntityFramework" Version="6.5.1" />
</ItemGroup>
</Project>
46 changes: 46 additions & 0 deletions RateLimiter/RejectRateLimiter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace RateLimiter
{
public class RejectRateLimiter : IRateLimiter
{
private readonly ConcurrentDictionary<string, List<DateTime>> requests = new();
private readonly ConcurrentDictionary<string, object> tokenLocks = new();

private readonly object lockObject = new();
public int RequestLimit { get; }
public TimeSpan Interval { get; }
public RejectRateLimiter(int requestLimit = 10, TimeSpan interval = default)
{
RequestLimit = requestLimit;
if (interval == default)
Interval = TimeSpan.FromMinutes(1);
Interval = interval;
}
public bool CheckRequest(string limiterToken)
{
var tokenLock = tokenLocks.GetOrAdd(limiterToken, _ => new object());

lock (tokenLock) // Lock for this specific token
{
var currentRequests = requests.GetOrAdd(limiterToken, new List<DateTime>());
currentRequests = currentRequests
.Where(x => x > DateTime.Now.Subtract(Interval))
.ToList();

if (currentRequests.Count < RequestLimit)
{
currentRequests.Add(DateTime.Now);
requests[limiterToken] = currentRequests; // Update the dictionary with the filtered list
return true;
}

return false;
}
}
}
}