throttling.h 807 B

1234567891011121314151617181920212223242526272829303132
  1. #pragma once
  2. #include <library/cpp/unified_agent_client/f_maybe.h>
  3. #include <util/datetime/base.h>
  4. namespace NUnifiedAgent {
  5. // Comment from a non-author:
  6. // It is based on something similar to https://en.wikipedia.org/wiki/Token_bucket
  7. class TThrottler {
  8. public:
  9. explicit TThrottler(double rate, TDuration updatePeriod = TDuration::MilliSeconds(100));
  10. TThrottler(double rate, double burst);
  11. void Consume(double& tokens, TFMaybe<TDuration>& nextCheckDelay);
  12. bool TryConsume(double tokens);
  13. void ConsumeAndWait(double tokens);
  14. private:
  15. ui64 UpdateTokens();
  16. private:
  17. ui64 CyclesPerMillisecond;
  18. ui64 UpdatePeriod;
  19. double PeriodTokens;
  20. double AvailableTokens;
  21. ui64 ExpirationTime;
  22. };
  23. }