public RateLimitExceededException(IResponse response, Exception innerException) : base(response, innerException) { response.ArgumentNotNull(nameof(response)); rateLimit = response.ApiInfo.RateLimit; }
public ServiceBaseTestObject( IHeaderManager headerManager, IModelMapper modelMapper, IRateLimit rateLimit) : base(headerManager, modelMapper, ApiVersion.V1, ApiEndPoint.Cards, rateLimit) { }
public async Task Invoke(HttpContext context) { IRateLimit rateLimit = client.GetGrain <IRateLimit>(context.Request.Host.Host); var para = new RateLimitParameter { Rate = rate, BucketSize = bucketSize }; double left = await rateLimit.IsNeedToLimit(para); if (left > 0) { // 水桶还没满,继续加1 await _next(context); } else { ///如果超出30,进入下一个中间件,下一个中间件是用来加入黑名单的 if (left <= -30) { //Header中加入一个标志 context.Items.Add("BAN", "1"); await _next(context); } else { context.Response.StatusCode = 429; } } }
public CardService( IHeaderManager headerManager, IModelMapper modelMapper, ApiVersion version, IRateLimit rateLimit) : base(headerManager, modelMapper, version, ApiEndPoint.Cards, rateLimit) { }
public RegionalRequester(IRiotApiConfig config, string route) { _config = config; _appRateLimit = new RateLimit(RateLimitType.Application, config); _client.BaseAddress = new Uri($"https://{route}{RiotRootUrl}"); _client.DefaultRequestHeaders.Add(RiotKeyHeader, config.ApiKey); }
public bool AttemptPass(Int64 time) { lock (@lock) { var(newLimitState, passed) = rateLimitState.AttemptPass(time); rateLimitState = newLimitState; return(passed); } }
// Returns true if the request succeeded or failed, false if it hit the rate limit // (and thus should be retried later) async Task <bool> RunGitHubTask(GitHubTask task) { try { _logger.Information("Running {@Operation} ({RemainingRequests}/{RequestLimit})", task.OperationDescription, _remainingRequests, _limit); IRateLimit result = await task.Action(); _logger.Information("Finished {@Operation} ({RemainingRequests}/{RequestLimit})", task.OperationDescription, _remainingRequests, _limit); if (result != null) { lock (_lockObject) { _remainingRequests = result.RateLimit.Remaining; _limit = result.RateLimit.Limit; _resetTime = result.RateLimit.Reset; } } task.CompletionSource.SetResult(result); _requestCompleted.Set(); } catch (RateLimitExceededException ex) { _logger .ForContext("ResetTime", ex.Reset) .Warning("Rate limit exceeded for {@Operation}, resets in {ResetDelay}. {RemainingRequests}/{RequestLimit}", task.OperationDescription, ex.Reset.Subtract(DateTimeOffset.UtcNow), ex.Remaining, ex.Limit); lock (_lockObject) { _remainingRequests = ex.Remaining; _limit = ex.Limit; _resetTime = ex.Reset; } return(false); } catch (Exception ex) { _logger.Error(ex, "Failed {@Operation}", task.OperationDescription); task.CompletionSource.SetException(ex); } finally { lock (_lockObject) { _executingOperations--; } } return(true); }
protected ServiceBase( IHeaderManager headerManager, IModelMapper modelMapper, ApiVersion version, ApiEndPoint endpoint, IRateLimit rateLimit) { _headerManager = headerManager; ModelMapper = modelMapper; Version = version; EndPoint = endpoint; _rateLimit = rateLimit; ResetCurrentUrl(); }
internal MtgServiceProvider( IHeaderManager headerManager, IModelMapper modelMapper, IRateLimit rateLimit) { _headerManager = headerManager; _modelMapper = modelMapper; _rateLimit = rateLimit; _apiVersion = ApiVersion.V1; FlurlHttp.Configure(settings => { settings.JsonSerializer = new SystemTextJsonSerializer(); }); }
public ApiInfo( IDictionary <string, Uri> links, IList <string> oauthScopes, IList <string> acceptedOauthScopes, string etag, IRateLimit rateLimit) { links.ArgumentNotNull(nameof(links)); oauthScopes.ArgumentNotNull(nameof(oauthScopes)); acceptedOauthScopes.ArgumentNotNull(nameof(acceptedOauthScopes)); Links = new ReadOnlyDictionary <string, Uri>(links); OauthScopes = new ReadOnlyCollection <string>(oauthScopes); AcceptedOauthScopes = new ReadOnlyCollection <string>(acceptedOauthScopes); Etag = etag; RateLimit = rateLimit; }
private IRestRequest BuildRequest(string endpoint, IEnumerable <Parameter> parameters) { var request = new RestRequest(endpoint) { OnBeforeDeserialization = r => { Rates = new RateLimit(r.Headers); } }; if (parameters == null) { return(request); } foreach (var parameter in parameters) { request.AddParameter(parameter); } return(request); }
public DhtClient(DhtConfig config) { _endPoint = new IPEndPoint(IPAddress.Any, config.Port); _client = new UdpClient(_endPoint) { Ttl = byte.MaxValue }; switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.WinCE: _client.Client.IOControl(-1744830452, new byte[] { Convert.ToByte(false) }, new byte[4]); break; } _node = new DhtNode() { Host = IPAddress.Any, Port = config.Port, NodeId = GenerateRandomNodeId() }; _kTable = new RouteTable(config.KTableSize); _nodeQueue = new BlockingCollection <DhtNode>(config.NodeQueueMaxSize); _recvMessageQueue = new BlockingCollection <DhtData>(config.ReceiveQueueMaxSize); _requestQueue = new BlockingCollection <Tuple <DhtMessage, IPEndPoint> >(config.RequestQueueMaxSize); _responseQueue = new BlockingCollection <Tuple <DhtMessage, DhtNode> >(config.ResponseQueueMaxSize); _sendMessageQueue = new BlockingCollection <Tuple <DhtMessage, DhtNode> >(config.SendQueueMaxSize); _replyMessageQueue = new BlockingCollection <Tuple <DhtMessage, DhtNode> >(); _sendRateLimit = new TokenBucketLimit(config.SendRateLimit * 1024, 1, TimeUnit.Second); _receveRateLimit = new TokenBucketLimit(config.ReceiveRateLimit * 1024, 1, TimeUnit.Second); _processResponseThreadNum = config.ProcessResponseThreadNum; _processRequestThreadNum = config.ProcessRequestThreadNum; _cancellationTokenSource = new CancellationTokenSource(); _tasks = new List <Task>(); _bootstrapNodes = new List <DhtNode>(DefaultBootstrapNodes); MessageMap = IocContainer.GetService <AbstractMessageMap>(); }
public async Task OnActionExecutionAsync(ActionExecutingContext httpcontext, ActionExecutionDelegate next) { IPAddress ipAddress = httpcontext.HttpContext.Request.HttpContext.Connection.RemoteIpAddress; string ip = ipAddress.ToString(); Console.WriteLine("\n\n\n\n--->from ip " + ipAddress); OrleanService orlean = await OrleanService.GetInstance(); IRateLimit grain = orlean.GetRateLimit(ip); bool isOk = await grain.CheckRateLimit(); if (!isOk) { BlackListItem item = await context.BlackLists.FindAsync(ip); if (item == null) { item = new BlackListItem(ip); context.BlackLists.Add(item); } else { long unixTime = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; item.LastTime = unixTime; context.BlackLists.Update(item); } await context.SaveChangesAsync(); httpcontext.HttpContext.Response.StatusCode = 429; httpcontext.Result = new EmptyResult(); } else { await next(); } }
public IRateLimit GetRateLimit(string ip) { IRateLimit grain = _client.GetGrain <IRateLimit>(ip); return(grain); }
public RateLimitMutableContainer(IRateLimit init) { rateLimitState = init; }
public async Task RunImgUR() { Console.Write("Authentication ID > "); string ImgurAuthenticationID = Console.ReadLine(); /* * Console.Write("Authentication Secret > "); * string ImgurAuthenticationSecret=Console.ReadLine(); * Console.Write("OAuth Access Token > "); * string OAuthAccessToken=Console.ReadLine(); */ IApiClient ClientImgur = new AuthenticationImpl.ImgurClient(ImgurAuthenticationID); //IApiClient ClientImgurAuthenticated=new AuthenticationImpl.ImgurClient(ImgurAuthenticationID,ImgurAuthenticationSecret,new ModelsImpl.OAuth2Token(OAuthAccessToken,string.Empty,"bearer","77530931","wereleven",315360000)); Imgur.LibraryEnhancements.AccountEndpointEnhanced AccountAPI = new Imgur.LibraryEnhancements.AccountEndpointEnhanced(ClientImgur); ImgurEndpoints.ImageEndpoint ImageAPI = new ImgurEndpoints.ImageEndpoint(ClientImgur); ImgurEndpoints.AlbumEndpoint AlbumAPI = new ImgurEndpoints.AlbumEndpoint(ClientImgur); //ImgurEndpoints.CommentEndpoint CommentAPIAuthenticated=new ImgurEndpoints.CommentEndpoint(ClientImgurAuthenticated); //ImgurEndpoints.OAuth2Endpoint OAuthAPI=new ImgurEndpoints.OAuth2Endpoint(ClientImgurAuthenticated); ImgurEndpoints.RateLimitEndpoint LimitAPI = new ImgurEndpoints.RateLimitEndpoint(ClientImgur); try{ /* * Kewl Cat Album ID: YYL69 * Kewl Cat Image ID: 2rzgptw * Galcian Image ID: BWeb9EM */ Console.WriteLine("Initial connection..."); IRateLimit RemainingUsage = await LimitAPI.GetRateLimitAsync(); Console.WriteLine("Remaining API usage - {0} / {1}", RemainingUsage.ClientRemaining, RemainingUsage.ClientLimit); Console.WriteLine(); /* * Console.WriteLine("Refreshing OAuth Token..."); * Task<IOAuth2Token> wait=OAuthAPI.GetTokenByRefreshTokenAsync(ClientImgurAuthenticated.OAuth2Token.RefreshToken); * IOAuth2Token RefreshedOAuthToken=await wait; * ClientImgurAuthenticated.SetOAuth2Token(RefreshedOAuthToken); * Console.WriteLine("ImgUR Account: {0} [{1}]",RefreshedOAuthToken.AccountUsername,RefreshedOAuthToken.AccountId); * Console.WriteLine("Type: {0}",RefreshedOAuthToken.TokenType); * Console.WriteLine("Token: {0}",RefreshedOAuthToken.AccessToken); * Console.WriteLine("Refresh Token: {0}",RefreshedOAuthToken.RefreshToken); * Console.WriteLine("Expires: {0} ({1} seconds)",RefreshedOAuthToken.ExpiresAt,RefreshedOAuthToken.ExpiresIn); * Console.WriteLine(); */ Console.WriteLine("Retrieving Account details..."); //IAccount Account=await AccountAPI.GetAccountAsync(ImgurUser); IAccount Account = await AccountAPI.GetAccountAsync(ImgurUserID); Console.WriteLine("ID - {0}", Account.Id); Console.WriteLine("Username - {0}", Account.Url); Console.WriteLine("Created - {0}", Account.Created); Console.WriteLine("Notoriety - {0}", Account.Notoriety); Console.WriteLine("Reputation - {0}", Account.Reputation); Console.WriteLine("Bio - {0}", Account.Bio); Console.WriteLine(); Console.WriteLine("Retrieving recent Comments..."); IList <IComment> Comments = (await AccountAPI.GetCommentsAsync(ImgurUser, CommentSortOrder.Newest, 0)).ToList(); byte count = 0; foreach (IComment Comment in Comments) { if (++count > 3) { break; } DisplayComment(Comment); } Console.WriteLine("Retrieving recent Comment IDs..."); IList <int> CommentIDs = (await AccountAPI.GetCommentIdsAsync(ImgurUser, CommentSortOrder.Newest, 0)).ToList(); if (CommentIDs.Count > 0) { Console.WriteLine("Recent Comments - " + string.Join(", ", CommentIDs)); Console.WriteLine(); Console.WriteLine("Retrieving most recent Comment ({0})...", CommentIDs[0]); IComment Comment = await AccountAPI.GetCommentAsync(CommentIDs[0], ImgurUser); DisplayComment(Comment); string CommentImageID; if (!Comment.OnAlbum) { CommentImageID = Comment.ImageId; } else { Console.WriteLine("Retrieving most recent Comment Album details ({0})...", Comment.ImageId); IAlbum Album = await AlbumAPI.GetAlbumAsync(Comment.ImageId); Console.WriteLine("ID - {0}", Album.Id); Console.WriteLine("Title - {0}", Album.Title); Console.WriteLine("URL - {0}", Album.Link); Console.WriteLine("Owner Username if Album not anonymous - {0}", Album.AccountUrl); Console.WriteLine("Cover Image ID - {0}", Album.Cover); Console.WriteLine("Cover Image Dimensions - {0}x{1}", Album.CoverWidth, Album.CoverHeight); Console.WriteLine("Total Images - {0}", Album.ImagesCount); Console.WriteLine("In Gallery - {0}", Album.InGallery); Console.WriteLine("Created - {0}", Album.DateTime); Console.WriteLine("Views - {0}", Album.Views); Console.WriteLine("Category - {0}", Album.Section); Console.WriteLine("NSFW - {0}", Album.Nsfw); Console.WriteLine("View Layout - {0}", Album.Layout); Console.WriteLine("Description - {0}", Album.Description); Console.WriteLine(); CommentImageID = Comment.AlbumCover; } Console.WriteLine("Retrieving most recent Comment Image details ({0})...", CommentImageID); IImage Image = await ImageAPI.GetImageAsync(CommentImageID); Console.WriteLine("ID - {0}", Image.Id); Console.WriteLine("Title - {0}", Image.Title); Console.WriteLine("URL - {0}", Image.Link); Console.WriteLine("Filename - {0}", Image.Name); Console.WriteLine("MIME - {0}", Image.Type); Console.WriteLine("Size - {0}B", Image.Size); Console.WriteLine("Dimensions - {0}x{1}", Image.Width, Image.Height); Console.WriteLine("Uploaded - {0}", Image.DateTime); Console.WriteLine("Views - {0}", Image.Views); Console.WriteLine("Category - {0}", Image.Section); Console.WriteLine("NSFW - {0}", Image.Nsfw); Console.WriteLine("Animated - {0}", Image.Animated); Console.WriteLine("Description - {0}", Image.Description); Console.WriteLine(); /* * Console.Write("Enter Comment to post, or blank to skip > "); * string CommentReply=Console.ReadLine(); * if(!string.IsNullOrWhiteSpace(CommentReply)){ * int ReplyID=await CommentAPIAuthenticated.CreateReplyAsync(CommentReply,Comment.ImageId,Comment.Id.ToString("D")); * Console.WriteLine("Created Comment ID - {0}",ReplyID); * } * Console.WriteLine(); */ } else { Console.WriteLine(); } }catch (ImgurException Error) { Console.Error.WriteLine("Error: " + Error.Message); } Console.WriteLine("Remaining API usage - {0} / {1}", ClientImgur.RateLimit.ClientRemaining, ClientImgur.RateLimit.ClientLimit); Console.ReadKey(true); }