-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCooldownBucket.cs
More file actions
68 lines (54 loc) · 1.52 KB
/
CooldownBucket.cs
File metadata and controls
68 lines (54 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Threading;
namespace Ultz.Extensions.Commands.Cooldown
{
internal sealed class CooldownBucket
{
private int _remaining;
public CooldownBucket(Cooldown cooldown)
{
Cooldown = cooldown;
_remaining = Cooldown.Amount;
}
public Cooldown Cooldown { get; }
public int Remaining => Volatile.Read(ref _remaining);
public DateTimeOffset Window { get; private set; }
public DateTimeOffset LastCall { get; private set; }
public bool IsRateLimited(out TimeSpan retryAfter)
{
var now = DateTimeOffset.UtcNow;
LastCall = now;
if (Remaining == Cooldown.Amount)
{
Window = now;
}
if (now > Window + Cooldown.Per)
{
_remaining = Cooldown.Amount;
Window = now;
}
if (Remaining == 0)
{
retryAfter = Cooldown.Per - (now - Window);
return true;
}
retryAfter = default;
return false;
}
public void Decrement()
{
var now = DateTimeOffset.UtcNow;
Interlocked.Decrement(ref _remaining);
if (Remaining == 0)
{
Window = now;
}
}
public void Reset()
{
_remaining = Cooldown.Amount;
LastCall = default;
Window = default;
}
}
}