public Result <RequestCount> Save(RequestCount Entity)
        {
            var result = new Result <RequestCount>();

            try
            {
                var objtosave = _context.RequestCounts.FirstOrDefault(u => u.CountId == Entity.CountId);
                if (objtosave == null)
                {
                    objtosave = new RequestCount();
                    _context.RequestCounts.Add(Entity);
                }

                if (!IsValid(objtosave, result))
                {
                    return(result);
                }

                _context.SaveChanges();
            }
            catch (Exception e)
            {
                result.HasError = true;
                result.Message  = e.Message;
            }

            return(result);
        }
Beispiel #2
0
        public void ResetHeader_LessTimeOrEqualThanThrottlingPeriod()
        {
            var sixSecondsLeft = new RequestCount(5.Seconds());

            this.SetupThrottling(3, 10.Seconds(), sixSecondsLeft);

            var client = new HttpClient(BaseUrl.ToString());

            client.Request.AddExtraHeader(ApiKey.ParameterName, ApiKey.EmptyParameterValue);
            this.DisableEnforcer().DisableAuthentication().FullThrottle();

            HttpResponse response = this.Get(client);

            Assert.That(response, Must.Have.ResetHeader(
                            Is.LessThanOrEqualTo("10").Using(RemainingSeconds.InPeriod)));

            Task t = Task.Factory
                     .StartNew(() => Thread.Sleep(TimeSpan.FromSeconds(1)), TaskCreationOptions.LongRunning)
                     .ContinueWith(_ =>
            {
                response = this.Get(client);
                Assert.That(response, Must.Have.ResetHeader(
                                Is.LessThan("10").Using(RemainingSeconds.InPeriod)));
            });

            t.Wait();
        }
 public AsynchronousCollectionBase(RequestCount requestCount, RequestData requestData, SubmitChanges submitChanges)
 {
     Storage       = new DataStorage();
     SubmitChanges = submitChanges;
     RequestData   = requestData;
     RequestCount  = requestCount;
 }
        public async Task Invoke(HttpContext context)
        {
            var endpoint = context.GetEndpoint();

            RequestLimitAttribute requestLimit = endpoint?.Metadata.GetMetadata <RequestLimitAttribute>();
            RequestCount          requestCount = null;

            try
            {
                if (requestLimit != null)
                {
                    requestCount = _requestCounts.GetOrAdd(endpoint.DisplayName, (_) => new RequestCount());
                    int newRequestCount = requestCount.Increment();
                    if (newRequestCount > requestLimit.MaxConcurrency)
                    {
                        _logger.ThrottledEndpoint(requestLimit.MaxConcurrency, newRequestCount);
                        context.Response.StatusCode = (int)HttpStatusCode.TooManyRequests;
                        return;
                    }
                }

                await _next(context);
            }
            finally
            {
                //IMPORTANT This will not work for operation style apis, such as when returning a 202 for egress calls.
                requestCount?.Decrement();
            }
        }
 public AsynchronousCollection(RequestCount requestCount, RequestData requestData, SubmitChanges submitChanges, AsynchronousCollectionSettings settings) :
     base(requestCount, requestData, submitChanges)
 {
     settings.Apply <T>(this);
     Storage.OnInitialized += OnStorageInitialized;
     Storage.OnCompleted   += OnStorageCompleted;
     RaiseGetCount();
 }
 public int CompareTo(object obj)
 {
     if(obj is ApplicationInstance)
     {
         ApplicationInstance instance = (ApplicationInstance)obj;
         return (RequestCount.CompareTo(instance.RequestCount));
     }
     throw new ArgumentException("Object is not an Application Instance");
 }
 public static AsynchronousCollection <T> CreateCollection <T>(RequestCount requestCount, RequestData requestData, RequestDataMode requestDataMode)
 {
     if (requestDataMode == RequestDataMode.OnDemand)
     {
         return(new AsynchronousCollection <T>(requestCount, requestData));
     }
     else
     {
         return(new AsynchronousCollection2 <T>(requestCount, requestData));
     }
 }
        public bool IsValid(RequestCount obj, Result <RequestCount> result)
        {
            if (!ValidationHelper.IsStringValid((obj.CountId.ToString())))
            {
                result.HasError = true;
                result.Message  = "Invalid RequestCountId";
                return(false);
            }

            return(true);
        }
 public static AsynchronousCollection <T> CreateCollection <T>(RequestCount requestCount, RequestData requestData, SubmitChanges submitChanges, AsynchronousCollectionSettings settings)
 {
     if (settings.GetType() == typeof(AsynchronousCollection2Settings))
     {
         return(new AsynchronousCollection2 <T>(requestCount, requestData, submitChanges, (AsynchronousCollection2Settings)settings));
     }
     if (settings.GetType() == typeof(AsynchronousCollectionSettings))
     {
         return(new AsynchronousCollection <T>(requestCount, requestData, submitChanges, settings));
     }
     return(null);
 }
            public void Add(FetchResultCounters other)
            {
                if (other == null)
                {
                    return;
                }

                if (!other.RequestCount.IsEmpty)
                {
                    RequestCount.Add(other.RequestCount);
                }

                OrderCount += other.OrderCount;
            }     // Add
Beispiel #11
0
        public void RemainingHeader_TotalMinusRepositoryCount()
        {
            var two = new RequestCount(TimeSpan.Zero).Increase();

            this.SetupThrottling(3, 10.Seconds(), two);

            var client = new HttpClient(BaseUrl.ToString());

            client.Request.AddExtraHeader(ApiKey.ParameterName, ApiKey.EmptyParameterValue);
            this.DisableEnforcer().DisableAuthentication().FullThrottle();

            HttpResponse response = this.Get(client);

            Assert.That(response, Must.Have.RemainingHeader(Is.EqualTo("1")));
        }
Beispiel #12
0
        public override string ToString()
        {
            StringBuilder builder = new StringBuilder(GetType().Name);

            builder.AppendLine();

            builder.Append("\tMaxActive: ");
            builder.AppendLine(Interlocked.Read(ref _maxActive).ToString());
            builder.Append("\tActive: ");
            builder.AppendLine(Interlocked.Read(ref _activeCount).ToString());

            var requestCount         = RequestCount;
            var requestCompleteCount = RequestCompleteCount;
            var requestFailed        = RequestFailed;

            var tickCount = Interlocked.Read(ref _tickCount);

            builder.Append("\tRequestCount: ");
            builder.AppendLine(RequestCount.ToString());

            builder.Append("\tRequestFailed: ");
            builder.AppendLine(RequestFailed.ToString());

            builder.Append("\tRequestComplete: ");
            builder.AppendLine(Interlocked.Read(ref requestCompleteCount).ToString());

            if (requestCount > 0)
            {
                TimeSpan timeSpan = TimeSpan.FromTicks(tickCount);
                var      avg      = timeSpan.TotalMilliseconds / (double)requestCount;

                builder.Append("\tAvgTimeToLastByte: ");
                builder.AppendLine(avg.ToString("0.0000000"));
            }

            builder.AppendLine("\tCache:");

            foreach (var item in Cache.Keys)
            {
                builder.Append("\t\t");
                builder.Append(item);
                builder.Append("=");
                builder.AppendLine(Cache[item].TokenSource.IsCancellationRequested ? "complete" : "building");
            }

            return(builder.ToString());
        }
Beispiel #13
0
        public void Rate(IHttpRequest request, IHttpResponse response)
        {
            ApiKey apiKey = ApiKey.ExtractFrom(request);

            if (!apiKey.IsMissing)
            {
                var resources = request.TryResolve <IResourceManager>();
                ThrottlingConfiguration configuration = resources.Get(ThrottlingConfiguration.Key, ThrottlingConfiguration.Empty());

                var          repository = request.TryResolve <IRequestCountRepository>();
                RequestCount count      = repository.Get(apiKey);

                addLimitHeader(response, configuration);
                addRemainingHeader(response, configuration, count);
                addResetHeader(response, configuration, count);
            }
        }
        public ActionResult GetAllRequest()
        {
            try
            {
                RequestCountViewModel requestCountView = new RequestCountViewModel();
                var result   = _requestService.GetAll();
                var requests = result.Data.Where(q => q.Status.Equals("Pending")).ToList();
                if (result.HasError)
                {
                    ViewBag.Message = result.Message;
                    return(Content(result.Message));
                }

                var notification = _notificationService.GetAll();
                var list         = notification.Data.Where(q => q.UserId == 0 && q.IsDeliver.Equals("false")).ToList();
                if (list.Count != 0)
                {
                    ViewBag.notification      = true;
                    ViewBag.notificationCount = list.Count;
                }
                else
                {
                    ViewBag.notification = false;
                }
                ViewBag.Entry = HttpUtil.CurrentUser.UserType;
                RequestCount req = new RequestCount();
                req.NewCount = result.Data.Count;
                var request = _requestCount.GetById(1);
                request.Data.NewCount      = result.Data.Count;
                request.Data.PreviousCount = request.Data.NewCount;
                var request2 = _requestCount.Save(request.Data);
                requestCountView.RequestForServices = requests;
                requestCountView.RequestCount       = request.Data;

                return(View(requestCountView));
            }
            catch (Exception e)
            {
                return(Content(e.Message));
            }
        }
Beispiel #15
0
        //@Headers({ "Content-Type: application/json"})
        //@POST("api/v1/data/count")
        //Call<ResponseCount> count(@Body RequestCount requestCount);
        public async Task <ResponseResult> CountAsync(RequestCount requestCount)
        {
            var uri = new Uri(baseUri + @"api/v1/data/count");
            // Сформировать JSON данные
            string jsonContent = JsonConvert.SerializeObject(requestCount);
            HttpResponseMessage httpResponse = await cmd.PostAsync(uri, jsonContent);

            ResponseResult responseResult = new ResponseResult();

            if (httpResponse.IsSuccessStatusCode)
            {
                responseResult = JsonConvert.DeserializeObject <ResponseResult>(httpResponse.Content.ToString());
            }
            else
            {
                responseResult.Error   = true;
                responseResult.ErrCode = "";
                responseResult.ErrMsg  = "Ошибка HttpClient.";
            }
            return(responseResult);
        }
Beispiel #16
0
            /// <summary>
            /// Gets the time to delay until for a single rate limit rule.
            /// </summary>
            /// <param name="platformId">The platform ID of the default server to connect to. This should equal one of the <see cref="Models.PlatformId"/> values.</param>
            /// <param name="now">The current time in UTC.</param>
            /// <returns>The time to delay until.</returns>
            public DateTime GetDelayTime(string platformId, DateTime now)
            {
                RequestCount requestCount = RequestCounts.GetOrAdd(platformId, requestCountFactory);

                lock (requestCount)
                {
                    if (requestCount.ResetTime < now || requestCount.Count == 0)
                    {
                        // Wait a little longer than the reset time in case there's a bit of lag when talking to the server
                        requestCount.ResetTime = now + TimeSpan.FromSeconds(Rule.Duration + 0.75);
                        requestCount.Count     = 1;
                    }
                    else if (requestCount.Count < Rule.Limit)
                    {
                        ++requestCount.Count;
                    }
                    else
                    {
                        return(requestCount.ResetTime);
                    }
                }
                return(now);
            }
Beispiel #17
0
        public void Throttle(IHttpRequest request, IHttpResponse response)
        {
            var resources = request.TryResolve <IResourceManager>();
            ThrottlingConfiguration configuration = resources.Get(ThrottlingConfiguration.Key, ThrottlingConfiguration.Empty());

            var key = ApiKey.ExtractFrom(request);

            if (!key.IsMissing && configuration.ThrottlingEnabled)
            {
                var          repository = request.TryResolve <IRequestCountRepository>();
                RequestCount count      = repository.Ensure(key, () => new RequestCount(configuration.Period));

                if (count.IsLessThan(configuration.NumberOfRequests))
                {
                    repository.Update(key, count.Increase());
                }
                else
                {
                    response.AddHeader("Retry-After", configuration.FormattedSeconds);
                    throw new HttpError(429, configuration.ErrorMessage());
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// Adds application-level rate limiting rules if they have not been added already.
        /// </summary>
        /// <param name="rules">The list of rules.</param>
        /// <param name="platformId">The platform ID of the response that contained the rate limit definitions. The request count will automatically be incremented for this platform.</param>
        /// <param name="currentCounts">The current request counts for each rule. If unspecified, 1 request for each rule will be assumed.</param>
        public virtual void TrySetRules(IEnumerable <RateLimitRule> rules, string platformId = null, IEnumerable <RateLimitRule> currentCounts = null)
        {
            var now = DateTime.UtcNow;

            foreach (var rule in rules)
            {
                appTrackers.AddOrUpdate(rule.Duration, (duration) =>
                {
                    var newTracker = new RateLimitTracker {
                        Rule = rule
                    };
                    if (platformId != null)
                    {
                        var currentCount          = currentCounts?.FirstOrDefault(c => c.Duration == duration)?.Limit ?? 1;
                        RequestCount requestCount = newTracker.RequestCounts.GetOrAdd(platformId, (pid) => new RequestCount());
                        // Wait a little longer than the reset time in case there's a bit of lag when talking to the server
                        requestCount.ResetTime = now + TimeSpan.FromSeconds(duration + 0.75);
                        requestCount.Count     = currentCount;
                    }
                    return(newTracker);
                }, identityUpdateFactory);
            }
        }
Beispiel #19
0
        public static IRequestCountRepository SetupThrottling(this Testing.Commons.ServiceStack.v3.HostTesterBase tester, ushort numberOfRequests, TimeSpan period, RequestCount count = null)
        {
            var configuration = new ThrottlingConfiguration
            {
                NumberOfRequests = numberOfRequests,
                Period           = period
            };

            var manager = Substitute.For <IResourceManager>();

            manager.Get(ThrottlingConfiguration.Key, Arg.Any <ThrottlingConfiguration>())
            .Returns(configuration);
            tester.Replacing(manager);

            var repository = Substitute.For <IRequestCountRepository>();

            if (count != null)
            {
                repository.Get(Arg.Any <ApiKey>()).Returns(count);
            }
            tester.Replacing(repository);
            return(repository);
        }
 public AsynchronousCollection2(RequestCount requestCount, RequestData requestData, SubmitChanges submitChanges, AsynchronousCollection2Settings setting)
     : base(requestCount, requestData, submitChanges, setting)
 {
     RequestDataTimer = new DispatcherTimer();
 }
Beispiel #21
0
 public void SaveStats()
 {
     File.WriteAllLines("./cache-stats", new string[] { RequestCount.ToString(), HitCount.ToString() });
 }
 public AsynchronousCollection2(RequestCount requestCount, RequestData requestData, SubmitChanges submitChanges)
     : this(requestCount, requestData, submitChanges, AsynchronousCollection2Settings.Default)
 {
 }
 public AsynchronousCollection2(RequestCount requestCount, RequestData requestData, AsynchronousCollection2Settings setting)
     : this(requestCount, requestData, null, setting)
 {
 }
 public AsynchronousCollection2(RequestCount requestCount, RequestData requestData)
     : this(requestCount, requestData, null, AsynchronousCollection2Settings.Default)
 {
 }
 public static AsynchronousCollection <T> CreateCollection <T>(RequestCount requestCount, RequestData requestData, AsynchronousCollectionSettings settings)
 {
     return(CreateCollection <T>(requestCount, requestData, null, settings));
 }
Beispiel #26
0
        private static void addRemainingHeader(IHttpResponse response, ThrottlingConfiguration configuration, RequestCount count)
        {
            string numberOfRequestLeftInPeriod = count != null?
                                                 count.Remaining(configuration.NumberOfRequests).ToString(CultureInfo.InvariantCulture) :
                                                     configuration.FormattedRequests;

            response.AddHeader("X-Rate-Limit-Remaining", numberOfRequestLeftInPeriod);
        }
 public AsynchronousCollectionBase(RequestCount requestCount, RequestData requestData)
     : this(requestCount, requestData, null)
 {
 }
Beispiel #28
0
        private static void addResetHeader(IHttpResponse response, ThrottlingConfiguration configuration, RequestCount count)
        {
            string numberOfSecondsLeftInPeriod = count != null?
                                                 count.Remaining(DateTimeOffset.UtcNow).ToString(CultureInfo.InvariantCulture) :
                                                     configuration.FormattedSeconds;

            response.AddHeader("X-Rate-Limit-Reset", numberOfSecondsLeftInPeriod);
        }