Esempio n. 1
0
 public FullyThrottledTokenBucket(ITokenBucket oldBucket)
 {
     if (oldBucket != null)
     {
         this.pendingCharges = oldBucket.PendingCharges;
     }
 }
        // Token: 0x060002F7 RID: 759 RVA: 0x0000F8AC File Offset: 0x0000DAAC
        BackOffValue IAirSyncUser.GetBudgetBackOffValue()
        {
            BackOffValue backOffValue = null;

            if (((IAirSyncUser)this).Budget != null)
            {
                ITokenBucket budgetTokenBucket = ((IAirSyncUser)this).GetBudgetTokenBucket();
                if (budgetTokenBucket == null)
                {
                    AirSyncDiagnostics.TraceInfo(ExTraceGlobals.RequestsTracer, null, "[AirSyncUser.GetBudgetBackOffDuration] Budget does not contain a token bucket.  Likely unthrottled.");
                    return(BackOffValue.NoBackOffValue);
                }
                float balance = budgetTokenBucket.GetBalance();
                AirSyncDiagnostics.TraceInfo <float, int>(ExTraceGlobals.RequestsTracer, null, "[AirSyncUser.GetBudgetBackOffDuration]. Balance :{0}, RechargeRate:{1}", balance, budgetTokenBucket.RechargeRate);
                backOffValue = new BackOffValue
                {
                    BackOffReason = "Budget"
                };
                if ((double)balance < GlobalSettings.BudgetBackOffMinThreshold.TotalMilliseconds)
                {
                    backOffValue.BackOffDuration = Math.Ceiling((GlobalSettings.BudgetBackOffMinThreshold.TotalMilliseconds - (double)balance) * 60.0 * 60.0 / (double)budgetTokenBucket.RechargeRate);
                    backOffValue.BackOffType     = ((balance > (float)(ulong.MaxValue * (ulong)((IAirSyncUser)this).Budget.ThrottlingPolicy.EasMaxBurst.Value)) ? BackOffType.Medium : BackOffType.High);
                }
                else
                {
                    backOffValue.BackOffDuration = Math.Ceiling((GlobalSettings.BudgetBackOffMinThreshold.TotalMilliseconds - (double)balance) / 1000.0);
                }
            }
            AirSyncDiagnostics.TraceInfo <double, BackOffType>(ExTraceGlobals.RequestsTracer, null, "[AirSyncUser.GetBudgetBackOffDuration]. BudgetBackOff Duration:{0} sec. BackOffType:{1}", backOffValue.BackOffDuration, backOffValue.BackOffType);
            return(backOffValue ?? BackOffValue.NoBackOffValue);
        }
Esempio n. 3
0
        public OAuthClient(string clientId, string clientSecret, string region, ITokenBucket tokenBucket)
            : base($"https://{region}.battle.net", tokenBucket)
        {
            var credentials = Encoding.ASCII.GetBytes($"{clientId}:{clientSecret}");

            Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
            AddParameter("grant_type", "client_credentials");
        }
Esempio n. 4
0
 public void SetUp()
 {
     _refillStrategy = new MockRefillStrategy();
     _sleepStrategy  = new Mock <ISleepStrategy>();
     _bucket         = TokenBuckets.Construct()
                       .WithCapacity(Capacity)
                       .WithRefillStrategy(_refillStrategy)
                       .WithSleepStrategy(_sleepStrategy.Object)
                       .Build();
 }
Esempio n. 5
0
 public WorkflowController(ILogger <WorkflowController> logger,
                           IPersistenceProvider persistenceProvider,
                           IWorkflowRegistry registry,
                           ITokenBucket tokenBucket)
 {
     _persistenceProvider = persistenceProvider;
     _logger      = logger;
     _registry    = registry;
     _tokenBucket = tokenBucket;
 }
Esempio n. 6
0
 private TokenBucket(ITokenBucket oldBucket, Unlimited <uint> maxBalance, Unlimited <uint> rechargeRate, Unlimited <uint> minBalance, BudgetKey budgetKey)
 {
     this.BudgetKey     = budgetKey;
     this.LastUpdateUtc = TimeProvider.UtcNow;
     this.UpdateSettings(maxBalance, rechargeRate, minBalance);
     this.balance = (maxBalance.IsUnlimited ? 2147483647U : maxBalance.Value);
     if (oldBucket != null)
     {
         this.PendingCharges = oldBucket.PendingCharges;
     }
 }
Esempio n. 7
0
        protected HttpClientBase(string baseAddress, ITokenBucket tokenBucket)
        {
            _tokenBucket = tokenBucket;
            Client       = new HttpClient
            {
                BaseAddress = new Uri(baseAddress)
            };
            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            _parameters = new Dictionary <string, string>();
        }
Esempio n. 8
0
 /// <summary>
 /// Checks if the buckets have the same tick span and total limit. Returns true if both buckets
 /// are null.
 /// </summary>
 /// <param name="a">Token bucket A. May be null.</param>
 /// <param name="b">Token bucket B. May be null.</param>
 /// <returns>True if equivalent, false otherwise.</returns>
 public static bool AreEquivalent(ITokenBucket a, ITokenBucket b)
 {
     if (a == b)
     {
         return(true);
     }
     if (a == null || b == null)
     {
         return(false);
     }
     return(a.GetTickSpan() == b.GetTickSpan() && a.GetTotalLimit() == b.GetTotalLimit());
 }
        // Token: 0x060002FB RID: 763 RVA: 0x0000FAF8 File Offset: 0x0000DCF8
        void IAirSyncUser.SetBudgetDiagnosticValues(bool start)
        {
            ITokenBucket budgetTokenBucket = ((IAirSyncUser)this).GetBudgetTokenBucket();

            if (budgetTokenBucket != null)
            {
                float balance = budgetTokenBucket.GetBalance();
                this.context.SetDiagnosticValue(start ? ConditionalHandlerSchema.BudgetBalanceStart : ConditionalHandlerSchema.BudgetBalanceEnd, balance);
                this.context.SetDiagnosticValue(start ? ConditionalHandlerSchema.IsOverBudgetAtStart : ConditionalHandlerSchema.IsOverBudgetAtEnd, balance < 0f);
            }
            StandardBudgetWrapper standardBudgetWrapper = ((IAirSyncUser)this).Budget as StandardBudgetWrapper;

            if (standardBudgetWrapper != null)
            {
                this.context.SetDiagnosticValue(start ? ConditionalHandlerSchema.ConcurrencyStart : ConditionalHandlerSchema.ConcurrencyEnd, standardBudgetWrapper.GetInnerBudget().Connections);
            }
        }
Esempio n. 10
0
        public static ITokenBucket Create(ITokenBucket tokenBucket, Unlimited <uint> maxBalance, Unlimited <uint> rechargeRate, Unlimited <uint> minBalance, BudgetKey budgetKey)
        {
            if (rechargeRate == 0U)
            {
                return(new FullyThrottledTokenBucket(tokenBucket));
            }
            if (rechargeRate == 2147483647U || rechargeRate.IsUnlimited)
            {
                return(new UnthrottledTokenBucket(tokenBucket));
            }
            TokenBucket tokenBucket2 = tokenBucket as TokenBucket;

            if (tokenBucket2 != null && tokenBucket2.BudgetKey == budgetKey)
            {
                tokenBucket2.UpdateSettings(maxBalance, rechargeRate, minBalance);
                return(tokenBucket);
            }
            return(new TokenBucket(tokenBucket, maxBalance, rechargeRate, minBalance, budgetKey));
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            // Create a token bucket with a capacity of 1 token that refills at a fixed interval of 1 token/sec.
            ITokenBucket bucket = TokenBuckets.Construct()
                                  .WithCapacity(100)
                                  .WithFixedIntervalRefillStrategy(100, TimeSpan.FromSeconds(1))
                                  .Build();

            // ...

            while (true)
            {
                // Consume a token from the token bucket.  If a token is not available this method will block until
                // the refill strategy adds one to the bucket.
                bucket.Consume(1);

                Poll();
            }
        }
        public void Add(Host host, LimitRule rule)
        {
            ITokenBucket ulBucket = null;
            ITokenBucket dlBucket = null;

            Remove(host);
            host.SetLimitRule(rule);

            if (rule.IsUploadLimited && !rule.IsUploadBlocked)
            {
                ulBucket = TokenBuckets.Construct()
                           .WithCapacity(rule.UploadRate.Value + (rule.UploadBurst ?? NetworkUtilities.GetDefaultBurst(rule.UploadRate.Value)))
                           .WithFixedIntervalRefillStrategy(rule.UploadRate.Value, TimeSpan.FromSeconds(1))
                           .Build();
            }

            if (rule.IsDownloadLimited && !rule.IsDownloadBlocked)
            {
                dlBucket = TokenBuckets.Construct()
                           .WithCapacity(rule.DownloadRate.Value + (rule.DownloadBurst ?? NetworkUtilities.GetDefaultBurst(rule.DownloadRate.Value)))
                           .WithFixedIntervalRefillStrategy(rule.DownloadRate.Value, TimeSpan.FromSeconds(1))
                           .Build();
            }

            if (ulBucket == null && dlBucket == null && !host.LimitRule.IsUploadBlocked && !host.LimitRule.IsDownloadBlocked)
            {
                return;
            }

            var buckets = new Tuple <ITokenBucket, ITokenBucket>(ulBucket, dlBucket);

            lock (_hostBucketDictLock) lock (_ipHostDict) lock (_bandwidthUploadDictLock) lock (_bandwidthDownloadDictLock)
                        {
                            _hostBucketDict.Add(host, buckets);
                            _ipHostDict.Add(IPAddress.Parse(host.IpAddress.ToString()), host);
                            _bandwidthUploadDict.Add(host, 0);
                            _bandwidthDownloadDict.Add(host, 0);
                        }
        }
        private async Task <TResponse> ExecuteThrottledAsync(CustomerThrottle customerThrottle, TRequest request, CancellationToken cancellationTokenToCheckInternally,
                                                             CancellationToken cancellationTokenToPassToDelegate)
        {
            ITokenBucket tokenBucket = null;

            if (customerThrottle.MaximumRequestsPerSecond > 0)
            {
                tokenBucket = await RetrieveMatchingTokenBucketContextOrMakeNew(customerThrottle).ConfigureAwait(false);

                if (cancellationTokenToCheckInternally.IsNotNone())
                {
                    cancellationTokenToCheckInternally.ThrowIfCancellationRequested();
                }

                await tokenBucket.WaitConsumeAsync(1, cancellationTokenToCheckInternally).ConfigureAwait(false);
            }

            if (cancellationTokenToCheckInternally.IsNotNone())
            {
                cancellationTokenToCheckInternally.ThrowIfCancellationRequested();
            }

            return(await delegateFunction(request, cancellationTokenToPassToDelegate).ConfigureAwait(false));
        }
Esempio n. 14
0
 /// <summary>
 /// Initializes a new instance of <see cref="AlgorithmTimeLimitManager"/> to manage the
 /// creation of <see cref="IsolatorLimitResult"/> instances as it pertains to the
 /// algorithm manager's time loop
 /// </summary>
 /// <param name="additionalTimeBucket">Provides a bucket of additional time that can be requested to be
 /// spent to give execution time for things such as training scheduled events</param>
 /// <param name="timeLoopMaximum">Specifies the maximum amount of time the algorithm is permitted to
 /// spend in a single time loop. This value can be overriden if certain actions are taken by the
 /// algorithm, such as invoking the training methods.</param>
 public AlgorithmTimeLimitManager(ITokenBucket additionalTimeBucket, TimeSpan timeLoopMaximum)
 {
     _timeLoopMaximum     = timeLoopMaximum;
     AdditionalTimeBucket = additionalTimeBucket;
     _currentTimeStepTime = new ReferenceWrapper <DateTime>(DateTime.MinValue);
 }
Esempio n. 15
0
 /// <summary>
 /// Start stream.
 /// </summary>
 public void Start()
 {
     lock (this.SyncRoot)
     {
         if (_playlistSubscriberStream.State != State.UNINIT)
             throw new IllegalStateException();
         _playlistSubscriberStream.State = State.STOPPED;
         if (_msgOut == null)
         {
             _msgOut = _consumerService.GetConsumerOutput(_playlistSubscriberStream);
             _msgOut.Subscribe(this, null);
         }
         _audioBucket = _bwController.GetAudioBucket(_bwContext);
         _videoBucket = _bwController.GetVideoBucket(_bwContext);
     }
 }
Esempio n. 16
0
 public CharacterEndpoint(ITokenBucket tokenBucket)
     : base(tokenBucket)
 {
 }
Esempio n. 17
0
 public void Available(ITokenBucket bucket, long tokenCount)
 {
     lock (this.SyncRoot)
     {
         _waitingForToken = false;
         _checkBandwidth = false;
         try
         {
             PullAndPush();
         }
         catch (Exception ex)
         {
             log.Error("Error while pulling message.", ex);
         }
         _checkBandwidth = true;
     }
 }
Esempio n. 18
0
 public void Reset(ITokenBucket bucket, long tokenCount)
 {
     _waitingForToken = false;
 }
Esempio n. 19
0
 public RequestLimitService(ITokenBucket tokenBucket, IResourceRepository resourceRepository, ILimitRuleFilter limitRuleFilter)
 {
     _tokenBucket        = tokenBucket;
     _resourceRepository = resourceRepository;
     _limitRuleFilter    = limitRuleFilter;
 }
Esempio n. 20
0
 public SeasonEndpoint(ITokenBucket tokenBucket)
     : base(tokenBucket)
 {
 }
 public UnthrottledTokenBucket(ITokenBucket oldBucket)
 {
     this.pendingCharges = ((oldBucket == null) ? 0 : oldBucket.PendingCharges);
 }
Esempio n. 22
0
 public ProfileEndpoint(ITokenBucket tokenBucket)
     : base(tokenBucket)
 {
 }
Esempio n. 23
0
 public async Task SetUp()
 {
     _refillStrategy = new MockRefillStrategy();
     _bucket         = await TokenBuckets.BucketWithRefillStrategy(Capacity, _refillStrategy).ConfigureAwait(false);
 }
Esempio n. 24
0
 public static string ToLimitString(this ITokenBucket b)
 {
     return(b.GetTotalLimit() + ":" + (b.GetTickSpan() / TimeSpan.TicksPerSecond));
 }
Esempio n. 25
0
 public ActEndpoint(ITokenBucket tokenBucket)
     : base(tokenBucket)
 {
 }
Esempio n. 26
0
 protected Endpoint(ITokenBucket tokenBucket)
 {
     _tokenBucket = tokenBucket;
 }
Esempio n. 27
0
 public FollowerEndpoint(ITokenBucket tokenBucket)
     : base(tokenBucket)
 {
 }
Esempio n. 28
0
 public BattleNetClient(string accessToken, string region, string localization, ITokenBucket tokenBucket)
     : base($"https://{region}.api.blizzard.com", tokenBucket)
 {
     AddParameter("access_token", accessToken);
     AddParameter("locale", localization);
 }
Esempio n. 29
0
 /// <summary>
 /// Initializes a new instance of <see cref="AlgorithmTimeLimitManager"/> to manage the
 /// creation of <see cref="IsolatorLimitResult"/> instances as it pertains to the
 /// algorithm manager's time loop
 /// </summary>
 /// <param name="additionalTimeBucket">Provides a bucket of additional time that can be requested to be
 /// spent to give execution time for things such as training scheduled events</param>
 /// <param name="timeLoopMaximum">Specifies the maximum amount of time the algorithm is permitted to
 /// spend in a single time loop. This value can be overriden if certain actions are taken by the
 /// algorithm, such as invoking the training methods.</param>
 public AlgorithmTimeLimitManager(ITokenBucket additionalTimeBucket, TimeSpan timeLoopMaximum)
 {
     _timeLoopMaximum     = timeLoopMaximum;
     AdditionalTimeBucket = additionalTimeBucket;
 }
Esempio n. 30
0
 public void SetUp()
 {
     _refillStrategy = new MockRefillStrategy();
     _sleepStrategy  = new Mock <ISleepStrategy>();
     _bucket         = new TokenBucket(Capacity, _refillStrategy, _sleepStrategy.Object);
 }
Esempio n. 31
0
 /// <summary>
 /// Provides an overload of <see cref="ITokenBucket.Consume"/> that accepts a <see cref="TimeSpan"/> timeout
 /// </summary>
 public static void Consume(this ITokenBucket bucket, long tokens, TimeSpan timeout)
 {
     bucket.Consume(tokens, (long)timeout.TotalMilliseconds);
 }
Esempio n. 32
0
 public ArtisanEndpoint(ITokenBucket tokenBucket)
     : base(tokenBucket)
 {
 }
        private unsafe void LimitLoop(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                var  buffer     = new WinDivertBuffer();
                var  address    = new WinDivertAddress();
                uint readLength = 0;

                bool recvResult = WinDivert.WinDivertRecv(_networkInfo.WinDivertHandle, buffer, ref address, ref readLength);
                if (!recvResult)
                {
                    throw new Exception("WinDivert failed to receive packet");
                }

                var                parseResult = WinDivert.WinDivertHelperParsePacket(buffer, readLength);
                Host               host        = null;
                ITokenBucket       bucket      = null;
                WinDivertDirection?direction   = null;

                if (parseResult.IPv4Header != (IPv4Header *)0)
                {
                    lock (_ipHostDictLock) lock (_hostBucketDictLock)
                        {
                            if (_ipHostDict.TryGetValue(parseResult.IPv4Header->SrcAddr, out host))
                            {
                                bucket    = _hostBucketDict[host].Item1;
                                direction = WinDivertDirection.Outbound;
                            }
                            else if (_ipHostDict.TryGetValue(parseResult.IPv4Header->DstAddr, out host))
                            {
                                bucket    = _hostBucketDict[host].Item2;
                                direction = WinDivertDirection.Inbound;
                            }
                        }

                    if (host != null &&
                        (host.LimitRule.IsBlocked ||
                         (direction == WinDivertDirection.Outbound && host.LimitRule.IsUploadBlocked) ||
                         (direction == WinDivertDirection.Inbound && host.LimitRule.IsDownloadBlocked)))
                    {
                        buffer.Dispose();
                        continue;
                    }

                    if (bucket != null)
                    {
                        bool passed = false;

                        try
                        {
                            passed = bucket.TryConsume(readLength * 8);
                        }
                        catch (ArgumentOutOfRangeException) { }

                        if (passed)
                        {
                            switch (direction)
                            {
                            case WinDivertDirection.Outbound:
                                lock (_bandwidthUploadDictLock)
                                    _bandwidthUploadDict[host] += readLength * 8;
                                break;

                            case WinDivertDirection.Inbound:
                                lock (_bandwidthDownloadDictLock)
                                    _bandwidthDownloadDict[host] += readLength * 8;
                                break;
                            }
                        }
                        else
                        {
                            buffer.Dispose();
                            continue;
                        }
                    }
                }

                WinDivert.WinDivertSend(_networkInfo.WinDivertHandle, buffer, readLength, ref address);
                buffer.Dispose();
            }
        }