public void Locked_ReturnsLocked() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(true); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsLocked.Should().Be(true); result.Limiter.Should().Be(limit); }
//TODO: Define your throttling policy private static ThrottlePolicy CreateThrottlePolicy() { var policy = new ThrottlePolicy { //enables throttling by IP IpThrottling = true, //enables throttling by UserId/CompanyId if user is authenticated ClientThrottling = true, //enables throttling by URL endpoint EndPointThrottling = false }; //overrides default rate limit for a given IP pattern policy.IpThrottlingRateLimits["10.0.*.*"] = new RateLimit { Period = TimeSpan.FromHours(1), Value = 5000 }; //// override default rate limit for a given authenticated client //policy.ClientThrottlingRateLimits["<CompanyId>:<UserId>"] = new RateLimit { Period = TimeSpan.FromHours(1), Value = 5000 }; //white list following IP addresses policy.IpWhiteList.Add("10.0.*.10"); policy.IpWhiteList.Add("10.0.*.11"); policy.IpWhiteList.Add("10.0.*.12"); return(policy); }
public void LimitReached_ReturnsThrottled() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 1 }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.Should().Be(true); result.IsLocked.Should().Be(false); }
public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); // configure CORS from config if (SettingsManager.EnableCORS) { config.EnableCors(new EnableCorsAttribute(SettingsManager.Origins, SettingsManager.Headers, SettingsManager.Methods, SettingsManager.ExposedHeaders) { SupportsCredentials = true }); } // configure JSON settings so that output will be camelCase, input parameters can be camelCase or PascalCase config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Apply Throttling Policy on all Controllers - from web.config // see more configs here: https://github.com/stefanprodan/WebApiThrottle config.MessageHandlers.Add(new ThrottlingHandler( policy: ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), policyRepository: null, repository: new CacheRepository(), logger: null, ipAddressParser: new XForwaredIPAddressParser() )); // Apply model validation attribute to all controllers config.Filters.Add(new ValidatedAttribute()); // Configure Model validation errors to be in Hebrew ValidatorOptions.LanguageManager.Culture = new CultureInfo("he"); }
public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。 // 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。 // 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712。 //config.EnableQuerySupport(); // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行 // 有关详细信息,请参阅: http://www.asp.net/web-api config.Filters.Add(new ThrottlingFilter( policy: ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), policyRepository: new PolicyCacheRepository(), repository: new RedisCacheRepository(), logger: new TracingThrottleLogger())); //config.Filters.Add(new ThrottlingCommonFilter( // policy: ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), // policyRepository: new PolicyCacheRepository(), // repository: new RedisCacheRepository(), // logger: new TracingThrottleLogger())); #if DEBUG HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize(); #endif }
public void ZeroLimit_ReturnsNotThrottled() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 0 }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.ShouldBeEquivalentTo(CheckResult.NotThrottled.IsThrottled); result.IsLocked.ShouldBeEquivalentTo(CheckResult.NotThrottled.IsLocked); }
public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); if (SettingsManager.EnableCORS) { config.EnableCors(new EnableCorsAttribute(SettingsManager.Origins, SettingsManager.Headers, SettingsManager.Methods, SettingsManager.ExposedHeaders)); } //Apply Throttling Policy on all Controllers - from web.config //see more configs here: https://github.com/stefanprodan/WebApiThrottle config.MessageHandlers.Add(new ThrottlingHandler( policy: ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), policyRepository: null, repository: new CacheRepository(), logger: null, ipAddressParser: new XForwaredIPAddressParser() )); //Apply model validation attribute to all controllers config.Filters.Add(new ValidatedAttribute()); //Configure Model validation errors to be in Hebrew ValidatorOptions.LanguageManager.Culture = new CultureInfo("he"); }
public static void Register(HttpConfiguration config) { var policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()); config.Filters.Add(new ThrottlingFilter( /*policy: new ThrottlePolicy * { * //scope to IPs * IpThrottling = false, * IpRules = new Dictionary<string, RateLimits> * { * { "::1/10", new RateLimits { PerSecond = 2 } }, * { "192.168.2.1", new RateLimits { PerMinute = 30, PerHour = 30*60, PerDay = 30*60*24 } } * }, * //white list the "::1" IP to disable throttling on localhost * IpWhitelist = new List<string> { "127.0.0.1", "192.168.0.0/24" }, * //scope to clients (if IP throttling is applied then the scope becomes a combination of IP and client key) * //ClientThrottling = true, * //ClientRules = new Dictionary<string, RateLimits> * //{ * // { "api-client-key-demo", new RateLimits { PerDay = 5000 } } * //}, * //white list API keys that don’t require throttling * //ClientWhitelist = new List<string> { "admin-key" }, * //Endpoint rate limits will be loaded from EnableThrottling attribute * EndpointThrottling = true * },*/ policy: policy, logger: new Code.WebApi.ApiThrottleLogger(), policyRepository: new PolicyCacheRepository(), //todo: create a new implementation using out Cache //repository: new CacheRepository() repository: new Code.WebApi.ApiThrottleRepository() //todo: test and uncomment )); }
public void LimitReachedWithLocking_ReturnsThrottled() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 1, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.Should().Be(true); result.IsLocked.Should().Be(false); repo.Received(1) .SetLock(key, limit); repo.Received(1) .RemoveThrottle(key, limit); }
public void NotThrottled_DoesNotIncrements() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 2, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act policy.Check(key, false); // Assert repo.Received(0) .AddOrIncrementWithExpiration(key, limit); }
/// <summary> /// Initializes a new instance of the <see cref="CustomThrottlingHandler"/> class. /// </summary> /// <param name="log">Log</param> /// <param name="syncSettingsReader">synchronous settings reader</param> public CustomThrottlingHandler(ILog log, ISettingsReader syncSettingsReader) : base() { this.log = log; this.alert = (string msg, Exception ex) => this.log.LogError(msg, ex); // Read the rate limit from the configuration long rateLimitPerMinute = Convert.ToInt64(syncSettingsReader.ReadValue("RateLimitPerMinute")); // The policy reads the threshold from the settings reader ThrottlePolicy throttlePolicyOnStartup = new ThrottlePolicy(perMinute: rateLimitPerMinute) { ClientThrottling = true }; // Bug fixes <-- WebApiThrottle has a bug. Setting these to null tells WebApiThrottle that we do not do ip-based nor endpoint-based // rate limiting. We avoid the bug this way. throttlePolicyOnStartup.IpRules = null; throttlePolicyOnStartup.EndpointRules = null; // Assign the static throttle policy on startup. Throttle on clients (meaning app keys). this.Policy = throttlePolicyOnStartup; this.Repository = new CacheRepository(); this.Logger = new TracingThrottleLogger(this.log); this.PolicyRepository = new PolicyCacheRepository(); // Set the throttle policy to update every 24 hours this.srvThrottlePolicy = new SelfRefreshingVar <IPolicyRepository>(this.PolicyRepository, TimeUtils.TwentyFourHours, this.RefreshingThottlePolicy, this.alert); }
public void Throttled_ReturnsTrue() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 1, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult checkResult; bool result = policy.IsThrottled(key, out checkResult); // Assert result.Should().Be(true); }
public MessageHandlerTrottle() { this._throttlingHandler = new ThrottlingHandler() { Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), Repository = new CacheRepository() }; }
public ThrottlingFilter( ThrottlePolicy policy, IPolicyRepository policyRepo = null, IThrottleRepository throttleRepo = null) { var ipAddressParser = new ApiIpAddressParser(); processer = new ThrottleProcesser(policy, ipAddressParser, policyRepo, throttleRepo); }
// This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. public void Configuration(IAppBuilder appBuilder) { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //Web API throttling load policy from app.config config.MessageHandlers.Add(new ThrottlingHandler() { Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), Repository = new MemoryCacheRepository() }); //Web API throttling hardcoded policy //config.MessageHandlers.Add(new ThrottlingHandler() //{ // Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20, perHour: 30, perDay: 35, perWeek: 3000) // { // //scope to IPs // IpThrottling = true, // IpRules = new Dictionary<string, RateLimits> // { // { "::1/10", new RateLimits { PerSecond = 2 } }, // { "192.168.2.1", new RateLimits { PerMinute = 30, PerHour = 30*60, PerDay = 30*60*24 } } // }, // //white list the "::1" IP to disable throttling on localhost for Win8 // IpWhitelist = new List<string> { "127.0.0.1", "192.168.0.0/24" }, // //scope to clients (if IP throttling is applied then the scope becomes a combination of IP and client key) // ClientThrottling = true, // ClientRules = new Dictionary<string, RateLimits> // { // { "api-client-key-1", new RateLimits { PerMinute = 60, PerHour = 600 } }, // { "api-client-key-9", new RateLimits { PerDay = 5000 } } // }, // //white list API keys that don’t require throttling // ClientWhitelist = new List<string> { "admin-key" }, // //scope to routes (IP + Client Key + Request URL) // EndpointThrottling = true, // EndpointRules = new Dictionary<string, RateLimits> // { // { "api/values/", new RateLimits { PerSecond = 3 } }, // { "api/values", new RateLimits { PerSecond = 4 } } // } // }, // Repository = new MemoryCacheRepository() //}); appBuilder.UseWebApi(config); }
public void Instantiate_EmptyLimiters() { // Arrange var policy = new ThrottlePolicy(); // Act // Assert Assert.Equal(0, policy.Limiters.Count); }
/// <inheritdoc /> public IntersectThrottlingMiddleware( OwinMiddleware next, ThrottlePolicy policy, string header, string fallbackClientKey, IThrottleRepository throttleRepository ) : base(next, policy, null, throttleRepository ?? DefaultRepository, null, null) { mHeader = header ?? DefaultHeader; mFallbackClientKey = fallbackClientKey ?? DefaultFallbackClientKey; }
public ThrottlingMiddleware( OwinMiddleware next, ThrottlePolicy policy, IPolicyRepository policyRepo = null, IThrottleRepository throttleRepo = null) : base(next) { var ipAddressParser = new ApiIpAddressParser(); processer = new ThrottleProcesser(policy, ipAddressParser, policyRepo, throttleRepo); }
public void NoLimits_ReturnsNotThrottled() { // Arrange var policy = new ThrottlePolicy(); var key = Substitute.For<IThrottleKey>(); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.ShouldBeEquivalentTo(CheckResult.NotThrottled.IsThrottled); result.IsLocked.ShouldBeEquivalentTo(CheckResult.NotThrottled.IsLocked); }
public void NoLimits_ReturnsNotThrottled() { // Arrange var policy = new ThrottlePolicy(); var key = Substitute.For <IThrottleKey>(); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.Should().Be(CheckResult.NotThrottled.IsThrottled); result.IsLocked.Should().Be(CheckResult.NotThrottled.IsLocked); }
protected virtual void CheckResult(HttpActionContext actionContext) { HttpRequestMessage request = actionContext.Request; CheckResult checkResult = ThrottlePolicy.Check(request); if (checkResult.IsThrottled) { actionContext.Response = ThrottledResponse(request, checkResult); } else if (checkResult.IsLocked) { actionContext.Response = LockedResponse(request, checkResult); } }
/// <summary>Registers web api configurations</summary> /// <param name="config">The current configuration</param> public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); //Apply Throttling Policy on all Controllers - from web.config //see more configs here: https://github.com/stefanprodan/WebApiThrottle config.MessageHandlers.Add(new ThrottlingHandler( policy: ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), policyRepository: null, repository: new CacheRepository(), logger: null )); }
public void PerDayMethod() { // Arrange/Act var policy = new ThrottlePolicy { PerDay = 10 }; // Assert Limiter limiter = policy.Limiters.First(); limiter.Count.Should().Be(10); limiter.Period.Should().Be(TimeSpan.FromDays(1)); // Testing the getter policy.PerDay.Should().Be(limiter.Count); }
public void PerHourMethod() { // Arrange/Act var policy = new ThrottlePolicy { PerHour = 10 }; // Assert Limiter limiter = policy.Limiters.First(); limiter.Count.ShouldBeEquivalentTo(10); limiter.Period.ShouldBeEquivalentTo(TimeSpan.FromHours(1)); // Testing the getter policy.PerHour.ShouldBeEquivalentTo(limiter.Count); }
/// <summary> /// Register /// </summary> /// <param name="config"></param> public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //EnableCors http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api config.EnableCors(); //Documents config.SetDocumentationProvider(new XmlDocumentationProvider( HttpContext.Current.Server.MapPath("~/App_Data/WebApi2.XML"))); config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); //http://stackoverflow.com/a/9521363 FilterConfig.RegisterWebApiFilters(GlobalConfiguration.Configuration.Filters); //http://www.asp.net/web-api/overview/testing-and-debugging/tracing-in-aspnet-web-api //IsVerbose: If false, each trace contains minimal information. If true, traces include more information. //MinimumLevel: Sets the minimum trace level. Trace levels, in order, are Debug, Info, Warn, Error, and Fatal. SystemDiagnosticsTraceWriter traceWriter = config.EnableSystemDiagnosticsTracing(); traceWriter.IsVerbose = false; traceWriter.MinimumLevel = TraceLevel.Info; config.EnableSystemDiagnosticsTracing(); config.Services.Replace(typeof(ITraceWriter), new LoggingTracer()); //WebAPI Throttle //https://github.com/stefanprodan/WebApiThrottle config.MessageHandlers.Add(new ThrottlingHandler() { Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), Repository = new CacheRepository(), Logger = new CommonTracingThrottleLogger() }); }
public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); //Apply Throttling Policy on all Controllers - from web.config //see more configs here: https://github.com/stefanprodan/WebApiThrottle config.MessageHandlers.Add(new ThrottlingHandler() { Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), Repository = new CacheRepository() }); //Apply model validation attribute to all controllers config.Filters.Add(new ValidatedAttribute()); //Configure Model validation errors to be in Hebrew ValidatorOptions.LanguageManager.Culture = new CultureInfo("he"); }
public static void Register(HttpConfiguration config) { //// Web API configuration and services //config.MessageHandlers.Add(new ThrottlingHandler() //{ // // Default limit // //Policy = new ThrottlePolicy(perSecond: 1, perMinute: 60) // Policy = new ThrottlePolicy() // { // IpThrottling = true, //Configure or throttling by id // EndpointThrottling = true,//enabled to differentiate by endpoint // //ClientThrottling = true, //configure throttling from the header Authorization-Token // //IpWhitelist = new List<string>() { } // //ClientWhitelist = new List<string>() { "2222"} // EndpointRules = new Dictionary<string, RateLimits>() // { // // Override default limit // {"api/books", new RateLimits(){ PerSecond= 1, PerMinute = 60}} // }, // StackBlockedRequests = true //count block request // }, // Repository = new CacheRepository() //}); // Define rate limits in web.config or app.config config.MessageHandlers.Add(new ThrottlingHandler() { Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), Repository = new CacheRepository() }); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
public void ZeroLimit_ReturnsNotThrottled() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { Count = 0 }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.ShouldBeEquivalentTo(CheckResult.NotThrottled.IsThrottled); result.IsLocked.ShouldBeEquivalentTo(CheckResult.NotThrottled.IsLocked); }
public void Locked_ReturnsLocked() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(true); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsLocked.ShouldBeEquivalentTo(true); result.Limiter.ShouldBeEquivalentTo(limit); }
/// <summary> /// Registers the specified configuration. /// </summary> /// <param name="config">The configuration.</param> public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //http://blog.elmah.io/logging-to-elmah-io-from-web-api/ config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger()); config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); //http://www.asp.net/web-api/overview/testing-and-debugging/tracing-in-aspnet-web-api config.EnableSystemDiagnosticsTracing(); //config.Filters.Add(new TokenValidationAttribute());; //config.Filters.Add(new IPHostValidationAttribute()); config.MessageHandlers.Add(new ThrottlingHandler() { Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), Repository = new CacheRepository() }); }
public override void OnActionExecuting(HttpActionContext actionContext) { string endPointName = actionContext.Request.RequestUri.AbsolutePath; #region STEP 1: Get user details like email, IP address, customerid, etc. & fill dictionary requestIdentity = GetIdentity(actionContext); Dictionary <string, string> dictIdentity = new Dictionary <string, string>(); dictIdentity.Add(KeyType.clientKey.ToString(), requestIdentity.clientKey); dictIdentity.Add(KeyType.ip.ToString(), requestIdentity.ipAddress); #endregion #region STEP 2: Get ThrottleData.json file data which is saved in http memory cache. List <Client> clients = (List <Client>)MemoryCacherHelper.GetValue(allClientThrollingPolicyCacheData); Client client = clients.Where(x => x.clientKey == requestIdentity.clientKey).FirstOrDefault(); ThrottlePolicy throttlePolicy = client != null ? client.throttlePolicy : clients[0].throttlePolicy; #endregion #region STEP 3: Filtered whiteList users, throttling not applied to these users. if (throttlePolicy.whiteListClients.Contains(requestIdentity.clientKey) || throttlePolicy.whiteListClients.Contains(requestIdentity.ipAddress)) { return; } #endregion #region Step 4: Apply policy -> unique -> method name + identity key like emil, ip etc. ClientRateLimiting clientRateLimiting = throttlePolicy.clientRateLimiting.Where(p => p.key == _ThrottlePolicyKey).FirstOrDefault(); if (clientRateLimiting != null && !string.IsNullOrEmpty(dictIdentity[clientRateLimiting.keyType.ToString()])) { ApplyAndCheckPolicy(actionContext, clientRateLimiting.policy, dictIdentity[clientRateLimiting.keyType.ToString()] + endPointName); Trace.TraceInformation("******************Identity=>" + clientRateLimiting.keyType.ToString() + " => " + dictIdentity[clientRateLimiting.keyType.ToString()] + "/Method Call=>" + actionContext.Request.RequestUri.AbsoluteUri); } #endregion }
public CustomThrottlingFilter(ThrottlePolicy policy, IPolicyRepository policyRepository, IThrottleRepository repository, IThrottleLogger logger) : base(policy, policyRepository, repository, logger) { this.QuotaExceededMessage = "API calls quota exceeded! maximum admitted {0} per {1}."; }
public void LimitReachedWithLocking_ReturnsThrottled() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { Count = 1, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.ShouldBeEquivalentTo(true); result.IsLocked.ShouldBeEquivalentTo(false); repo.Received(1) .SetLock(key, limit); repo.Received(1) .RemoveThrottle(key, limit); }
public void PerDayMethod() { // Arrange/Act var policy = new ThrottlePolicy { PerDay = 10 }; // Assert Limiter limiter = policy.Limiters.First(); limiter.Count.ShouldBeEquivalentTo(10); limiter.Period.ShouldBeEquivalentTo(TimeSpan.FromDays(1)); // Testing the getter policy.PerDay.ShouldBeEquivalentTo(limiter.Count); }
public void Throttled_ReturnsTrue() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { Count = 1, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult checkResult; bool result = policy.IsThrottled(key, out checkResult); // Assert result.ShouldBeEquivalentTo(true); }
/// <summary> /// Updates the policy object cached value /// </summary> /// <param name="policy"> /// The policy. /// </param> /// <param name="cacheRepository"> /// The policy repository. /// </param> public static void UpdatePolicy(ThrottlePolicy policy, IPolicyRepository cacheRepository) { cacheRepository.Save(GetPolicyKey(), policy); }
public void NotThrottled_DoesNotIncrements() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { Count = 2, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act policy.Check(key, false); // Assert repo.Received(0) .AddOrIncrementWithExpiration(key, limit); }