Created
February 26, 2019 22:52
-
-
Save jpann/14935f0ee2927979934db26d19626ffa to your computer and use it in GitHub Desktop.
nancy throttling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.Caching; | |
using Bootstrapper; | |
public class Home : NancyModule | |
{ | |
public Home() | |
{ | |
Get["/"] = parameters => { | |
return "Hi"; | |
}; | |
} | |
} | |
public class ThrottlingHooks : IApplicationStartup | |
{ | |
private readonly IThrottleCache cache; | |
public ThrottlingHooks(IThrottleCache cache) | |
{ | |
this.cache = cache; | |
} | |
public void Initialize(IPipelines pipelines) | |
{ | |
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => { | |
if (this.cache.IsRateExceeded(ctx.Request.UserHostAddress)) | |
{ | |
return HttpStatusCode.TooManyRequests; | |
} | |
return null; | |
}); | |
pipelines.AfterRequest.AddItemToStartOfPipeline(ctx => { | |
this.cache.Register(ctx.Request.UserHostAddress); | |
}); | |
} | |
} | |
public interface IThrottleCache | |
{ | |
bool IsRateExceeded(string host); | |
void Register(string host); | |
} | |
public class InMemoryThrottleCache : IThrottleCache | |
{ | |
private readonly MemoryCache cache; | |
public InMemoryThrottleCache() | |
{ | |
this.cache = new MemoryCache("ThrottlingCache"); | |
} | |
public bool IsRateExceeded(string host) | |
{ | |
if (!this.cache.Contains(host)) | |
{ | |
return false; | |
} | |
return ((ThrottleToken) this.cache[host]).Count > 10; | |
} | |
public void Register(string host) | |
{ | |
if (!this.cache.Contains(host)) | |
{ | |
this.cache.Add(host, new ThrottleToken(), DateTimeOffset.Now.AddMinutes(1)); | |
} | |
var token = | |
this.cache.Get(host) as ThrottleToken; | |
token.Count++; | |
} | |
private class ThrottleToken | |
{ | |
public int Count { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment