forked from ringcentral/RingCentral.Net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRateLimitExtension.cs
37 lines (35 loc) · 1.44 KB
/
RateLimitExtension.cs
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
using System;
using System.Linq;
using System.Net;
using RingCentral.Net.Retry;
namespace RingCentral.Net.RateLimit
{
public class RateLimitExtension : RetryExtension
{
public RateLimitExtension(RateLimitOptions options = null) : base(DefaultOptions(options))
{
}
private static RetryOptions DefaultOptions(RateLimitOptions options)
{
options = options ?? RateLimitOptions.DefaultInstance;
return new RetryOptions
{
shouldRetry = (restException, retriesAttempted) =>
restException.httpResponseMessage.StatusCode == (HttpStatusCode) 429 &&
retriesAttempted < options.maxRetries,
retryInterval = (restException, retriesAttempted) =>
{
string rateLimitWindowHeader = default;
if (restException.httpResponseMessage.Headers
.TryGetValues("x-rate-limit-window", out var values))
rateLimitWindowHeader = values.FirstOrDefault();
var rateLimitWindow = rateLimitWindowHeader == default
? options.rateLimitWindow
: int.Parse(rateLimitWindowHeader);
return (int) (rateLimitWindow * 1000 *
Math.Pow(2, retriesAttempted)); // exponential back off
}
};
}
}
}