sharp-chat/SharpChat.Common/RateLimiting/RateLimiter.cs

39 lines
1.4 KiB
C#
Raw Permalink Normal View History

2022-08-30 15:05:29 +00:00
using System;
namespace SharpChat.RateLimiting {
public class RateLimiter {
private int Size { get; }
private int WarnSize { get; }
private int MinimumDelay { get; }
private long[] Times { get; }
public RateLimiter(int size, int warnSize, int minimumDelay) {
if(size < 3)
throw new ArgumentException(@"Size must be more than 1.", nameof(size));
if(warnSize >= size && warnSize > 0)
throw new ArgumentException(@"Warning Size must be less than Size, or less than 0 to be disabled.", nameof(warnSize));
if(minimumDelay < 1000)
throw new ArgumentException(@"Minimum Delay must be more than 999 milliseconds.", nameof(minimumDelay));
Size = size;
WarnSize = warnSize;
MinimumDelay = minimumDelay;
Times = new long[Size];
}
private bool IsSeeding
=> (Times[0] < 1 && Times[1] < 1);
public bool ShouldKick
=> !IsSeeding && Times[0] + MinimumDelay >= Times[Size - 1];
public bool ShouldWarn
=> WarnSize > 0 && !IsSeeding && Times[0] + MinimumDelay >= Times[WarnSize - 1];
public void Update() {
for(int i = 0; i < Size - 1; ++i)
Times[i] = Times[i + 1];
Times[Size - 1] = DateTimeOffset.Now.ToUnixTimeMilliseconds();
}
}
}