-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClientSideRateLimitedHandler.cs
More file actions
54 lines (44 loc) · 1.5 KB
/
Copy pathClientSideRateLimitedHandler.cs
File metadata and controls
54 lines (44 loc) · 1.5 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
using System.Globalization;
using System.Net;
using System.Threading.RateLimiting;
internal sealed class ClientSideRateLimitedHandler
: DelegatingHandler, IAsyncDisposable
{
private readonly RateLimiter _rateLimiter;
public ClientSideRateLimitedHandler(RateLimiter limiter)
: base(new HttpClientHandler()) => _rateLimiter = limiter;
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
using RateLimitLease lease = await _rateLimiter.AcquireAsync(
permitCount: 1, cancellationToken);
if (lease.IsAcquired)
{
return await base.SendAsync(request, cancellationToken);
}
var response = new HttpResponseMessage(HttpStatusCode.TooManyRequests);
if (lease.TryGetMetadata(
MetadataName.RetryAfter, out TimeSpan retryAfter))
{
response.Headers.Add(
"Retry-After",
((int)retryAfter.TotalSeconds).ToString(
NumberFormatInfo.InvariantInfo));
}
return response;
}
async ValueTask IAsyncDisposable.DisposeAsync()
{
await _rateLimiter.DisposeAsync().ConfigureAwait(false);
Dispose(disposing: false);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_rateLimiter.Dispose();
}
}
}