Skip to content

Commit

Permalink
Support optional throttling (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
smithrobs authored Dec 11, 2016
1 parent 4e9ffc9 commit df131cc
Show file tree
Hide file tree
Showing 9 changed files with 282 additions and 11 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 2.2.0 (2016-12-??)

* Optional API request rate limiting.

# 2.1.2 (2016-12-07)

* Look for ```appsettings.json``` (netcore webapp convention)
Expand Down
9 changes: 5 additions & 4 deletions Nexmo.Api.Test.Integration/Nexmo.Api.Test.Integration.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,14 @@
<Compile Include="NumberTest.cs" />
<Compile Include="AccountTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ThrottleTest.cs" />
</ItemGroup>
<ItemGroup>
<None Include="..\Nexmo.Api.Test.Unit\settings.json">
<Link>settings.json</Link>
<None Include="..\Nexmo.Api.Test.Unit\appsettings.json">
<Link>appsettings.json</Link>
</None>
<None Include="..\Nexmo.Api.Test.Unit\settings.json.example">
<Link>settings.json.example</Link>
<None Include="..\Nexmo.Api.Test.Unit\appsettings.json.example">
<Link>appsettings.json.example</Link>
</None>
<None Include="packages.config" />
</ItemGroup>
Expand Down
23 changes: 23 additions & 0 deletions Nexmo.Api.Test.Integration/ThrottleTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Diagnostics;
using NUnit.Framework;

namespace Nexmo.Api.Test.Integration
{
[TestFixture]
public class ThrottleTest
{
[Test]
public void should_rate_limit()
{
Configuration.Instance.Settings["appSettings:Nexmo.Api.RequestsPerSecond"] = "1";
var watch = new Stopwatch();
watch.Start();
for (var i = 1; i < 7; i++)
{
Account.GetBalance();
}
watch.Stop();
Assert.GreaterOrEqual(watch.Elapsed.Seconds, 5);
}
}
}
2 changes: 2 additions & 0 deletions Nexmo.Api.Test.Unit/Nexmo.Api.Test.Unit.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="appsettings.json" />
<None Include="appsettings.json.example" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
Expand Down
21 changes: 18 additions & 3 deletions Nexmo.Api/Configuration.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using Nexmo.Api.ConfigurationExtensions;
using Nexmo.Api.Request;

namespace Nexmo.Api
{
Expand Down Expand Up @@ -36,9 +38,22 @@ private Configuration()

public static Configuration Instance { get; } = new Configuration();

public IConfiguration Settings { get; private set; }
public IConfiguration Settings { get; }
public HttpMessageHandler ClientHandler { get; set; }

public HttpClient Client => _client ?? (_client = ClientHandler == null ? new HttpClient() : new HttpClient(ClientHandler));
public HttpClient Client
{
get
{
var reqPerSec = Instance.Settings["appSettings:Nexmo.Api.RequestsPerSecond"];
if (string.IsNullOrEmpty(reqPerSec))
return _client ?? (_client = new HttpClient());

var delay = 1 / double.Parse(reqPerSec);
var execTimeSpanSemaphore = new TimeSpanSemaphore(1, TimeSpan.FromSeconds(delay));
var handler = ClientHandler != null ? new ThrottlingMessageHandler(execTimeSpanSemaphore, ClientHandler) : new ThrottlingMessageHandler(execTimeSpanSemaphore);
return _client ?? (_client = new HttpClient(handler));
}
}
}
}
4 changes: 0 additions & 4 deletions Nexmo.Api/Nexmo.Api.xproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,5 @@
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<ItemGroup>
<DnxInvisibleCompile Include="Request\WebRequestAdapter.cs" />
<DnxInvisibleCompile Include="Request\WebResponseAdapter.cs" />
</ItemGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>
28 changes: 28 additions & 0 deletions Nexmo.Api/Request/ThrottlingMessageHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// originally from https://github.com/saguiitay/OneDriveRestAPI

using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Nexmo.Api.Request
{
internal class ThrottlingMessageHandler : DelegatingHandler
{
private readonly TimeSpanSemaphore _execTimeSpanSemaphore;

public ThrottlingMessageHandler(TimeSpanSemaphore execTimeSpanSemaphore)
: this(execTimeSpanSemaphore, new HttpClientHandler {AllowAutoRedirect = true})
{ }

public ThrottlingMessageHandler(TimeSpanSemaphore execTimeSpanSemaphore, HttpMessageHandler innerHandler)
: base(innerHandler)
{
_execTimeSpanSemaphore = execTimeSpanSemaphore;
}

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return _execTimeSpanSemaphore?.RunAsync(base.SendAsync, request, cancellationToken) ?? base.SendAsync(request, cancellationToken);
}
}
}
189 changes: 189 additions & 0 deletions Nexmo.Api/Request/TimeSpanSemaphore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/*
MIT License
Copyright (C) 2011 by Joel Fillmore
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
https://github.com/joelfillmore/JFLibrary
*/

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Nexmo.Api.Request
{
/// <summary>
/// Allows a limited number of acquisitions during a timespan
/// </summary>
internal class TimeSpanSemaphore : IDisposable
{
private SemaphoreSlim _pool;

// the time span for the max number of callers
private TimeSpan _resetSpan;

// keep track of the release times
private Queue<DateTime> _releaseTimes;

// protect release time queue
private object _queueLock = new object();

public TimeSpanSemaphore(int maxCount, TimeSpan resetSpan)
{
_pool = new SemaphoreSlim(maxCount, maxCount);
_resetSpan = resetSpan;

// initialize queue with old timestamps
_releaseTimes = new Queue<DateTime>(maxCount);
for (int i = 0; i < maxCount; i++)
{
_releaseTimes.Enqueue(DateTime.MinValue);
}
}

/// <summary>
/// Blocks the current thread until it can enter the semaphore, while observing a CancellationToken
/// </summary>
private void Wait(CancellationToken cancelToken)
{
// will throw if token is cancelled
_pool.Wait(cancelToken);

// get the oldest release from the queue
DateTime oldestRelease;
lock (_queueLock)
{
oldestRelease = _releaseTimes.Dequeue();
}

// sleep until the time since the previous release equals the reset period
DateTime now = DateTime.UtcNow;
DateTime windowReset = oldestRelease.Add(_resetSpan);
if (windowReset > now)
{
int sleepMilliseconds = Math.Max(
(int)(windowReset.Subtract(now).Ticks / TimeSpan.TicksPerMillisecond),
1); // sleep at least 1ms to be sure next window has started
// TODO: log
//_logger.LogInformation($"Waiting {sleepMilliseconds} ms for TimeSpanSemaphore limit to reset.");

bool cancelled = cancelToken.WaitHandle.WaitOne(sleepMilliseconds);
if (cancelled)
{
Release();
cancelToken.ThrowIfCancellationRequested();
}
}
}

/// <summary>
/// Exits the semaphore
/// </summary>
private void Release()
{
lock (_queueLock)
{
_releaseTimes.Enqueue(DateTime.UtcNow);
}
_pool.Release();
}

/// <summary>
/// Runs an action after entering the semaphore (if the CancellationToken is not canceled)
/// </summary>
public void Run(Action action, CancellationToken cancelToken)
{
// will throw if token is cancelled, but will auto-release lock
Wait(cancelToken);

try
{
action();
}
finally
{
Release();
}
}

/// <summary>
/// Runs an action after entering the semaphore (if the CancellationToken is not canceled)
/// </summary>
public async Task RunAsync(Func<Task> action, CancellationToken cancelToken)
{
// will throw if token is cancelled, but will auto-release lock
Wait(cancelToken);

try
{
await action().ConfigureAwait(false);
}
finally
{
Release();
}
}

/// <summary>
/// Runs an action after entering the semaphore (if the CancellationToken is not canceled)
/// </summary>
public async Task RunAsync<T>(Func<T, Task> action, T arg, CancellationToken cancelToken)
{
// will throw if token is cancelled, but will auto-release lock
Wait(cancelToken);

try
{
await action(arg).ConfigureAwait(false);
}
finally
{
Release();
}
}

/// <summary>
/// Runs an action after entering the semaphore (if the CancellationToken is not canceled)
/// </summary>
public async Task<TR> RunAsync<T, TR>(Func<T, CancellationToken, Task<TR>> action, T arg, CancellationToken cancelToken)
{
// will throw if token is cancelled, but will auto-release lock
Wait(cancelToken);

try
{
return await action(arg, cancelToken).ConfigureAwait(false);
}
finally
{
Release();
}
}

/// <summary>
/// Releases all resources used by the current instance
/// </summary>
public void Dispose()
{
_pool.Dispose();
}
}
}
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,19 @@ Configuration:
* As you are able, please move your project to JSON configuration as XML
configuration will be going away in a future release.

### Configuration Reference

Key | Description
----|------------
Nexmo.api_key | Your API key from the [dashboard](https://dashboard.nexmo.com/settings)
Nexmo.api_secret | Your API secret from the [dashboard](https://dashboard.nexmo.com/settings)
Nexmo.Application.Id | Your application ID
Nexmo.Application.Key | Path to your application key
Nexmo.Url.Rest | Optional. Nexmo REST API base URL. Defaults to https://rest.nexmo.com
Nexmo.Url.Api | Optional. Nexmo API base URL. Defaults to https://api.nexmo.com
Nexmo.Api.RequestsPerSecond | Optional. Throttle to specified requests per second.
Nexmo.UserAgent | Optional. Your app-specific usage identifier in the format of `name/version`. Example: `"myApp/1.0"`

Examples
--------
The following examples show how to:
Expand Down

0 comments on commit df131cc

Please sign in to comment.