public DrapiHttpClientHandler() { InnerHandler = new HttpClientHandler(); // Denari API doesn't publish rate limits. Impose a limit of 100 requests every 10 seconds anyways. m_rateLimiter = SimpleRateLimiter.MaxRequestsPerInterval(100, TimeSpan.FromSeconds(10)); }
public void Invoke_FiveCallsInOneSecond_OnlyTwoGetThrough() { var maximumAllowedCalls = 2; var executedCount = 0; var sut = new SimpleRateLimiter(maximumAllowedCalls); for (int times = 0; times < 10; times++) { executedCount += sut.Invoke(SomeExpensiveFunction); } Assert.Equal(maximumAllowedCalls, executedCount); }
public HubspotService(IConfiguration configuration, IMemoryCache memoryCache) { m_client = new HttpClient(new HubspotHttpClientHandler(configuration["HubspotApiKey"])) { BaseAddress = new Uri("https://api.hubapi.com/") }; m_cache = memoryCache; // Hubspot API has a global limit of 100 requests every 10 seconds m_rateLimiter = SimpleRateLimiter.MaxRequestsPerInterval(100, TimeSpan.FromSeconds(10)); m_jitterer = new Random(); m_client.DefaultRequestHeaders.Accept.Clear(); m_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }
public void Invoke_TwoCallsPerMinute_OnlyOneGetsThroughPerMinute() { var allowedCallsPerMinute = 1; var timesToTry = 10; var sut = new SimpleRateLimiter(allowedCallsPerMinute, TimeSpan.FromMinutes(1)); var executedCount = 0; var now = DateTime.Now; TimeProvider.Current.SetTime(now); for (int times = 0; times < 10; times++) { executedCount += sut.Invoke(SomeExpensiveFunction); now = now.AddSeconds(30); TimeProvider.Current.SetTime(now); // move the time half a minute } Assert.Equal(timesToTry / 2, executedCount); // We do 2 calls per minute but allow only one, so we expect half of them to get through }
public void TestPause() { SimpleRateLimiter limiter = new SimpleRateLimiter(10); // 10 MB / Sec limiter.Pause(2); //init long pause = 0; for (int i = 0; i < 3; i++) { pause += limiter.Pause(4 * 1024 * 1024); // fire up 3 * 4 MB } //long convert = TimeUnit.MILLISECONDS.convert(pause, TimeUnit.NANOSECONDS); // 1000000 Milliseconds per nanosecond long convert = pause / 1000000; Assert.IsTrue(convert < 2000L, "we should sleep less than 2 seconds but did: " + convert + " millis"); Assert.IsTrue(convert > 1000L, "we should sleep at least 1 second but did only: " + convert + " millis"); }
public async Task TestRateLimitingAsync() { // 10 requests per 1 seconds var ratelimiter = SimpleRateLimiter.MaxRequestsPerInterval(10, TimeSpan.FromSeconds(1)); var stopwatch = new Stopwatch(); var random = new Random(); stopwatch.Start(); for (int i = 0; i < 101; i++) { await ratelimiter.WaitForReady(); // simulate some kind of actual network request await Task.Delay(random.Next(10, 50)); } stopwatch.Stop(); Assert.That(stopwatch.Elapsed >= TimeSpan.FromSeconds(10), "Expected 101 requests would take 10 seconds or more."); }