retry.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "retry.h"
  2. #include <util/stream/output.h>
  3. namespace {
  4. class TRetryOptionsWithRetCodePolicy : public IRetryPolicy<bool> {
  5. public:
  6. explicit TRetryOptionsWithRetCodePolicy(const TRetryOptions& opts)
  7. : Opts(opts)
  8. {
  9. }
  10. class TRetryState : public IRetryState {
  11. public:
  12. explicit TRetryState(const TRetryOptions& opts)
  13. : Opts(opts)
  14. {
  15. }
  16. TMaybe<TDuration> GetNextRetryDelay(bool ret) override {
  17. if (ret || Attempt == Opts.RetryCount) {
  18. return Nothing();
  19. }
  20. return Opts.GetTimeToSleep(Attempt++);
  21. }
  22. private:
  23. const TRetryOptions Opts;
  24. size_t Attempt = 0;
  25. };
  26. IRetryState::TPtr CreateRetryState() const override {
  27. return std::make_unique<TRetryState>(Opts);
  28. }
  29. private:
  30. const TRetryOptions Opts;
  31. };
  32. } // namespace
  33. bool DoWithRetryOnRetCode(std::function<bool()> func, TRetryOptions retryOptions) {
  34. return DoWithRetryOnRetCode<bool>(std::move(func), std::make_shared<TRetryOptionsWithRetCodePolicy>(retryOptions), retryOptions.SleepFunction);
  35. }
  36. TRetryOptions MakeRetryOptions(const NRetry::TRetryOptionsPB& retryOptions) {
  37. return TRetryOptions(retryOptions.GetMaxTries(),
  38. TDuration::MilliSeconds(retryOptions.GetInitialSleepMs()),
  39. TDuration::MilliSeconds(retryOptions.GetRandomDeltaMs()),
  40. TDuration::MilliSeconds(retryOptions.GetSleepIncrementMs()),
  41. TDuration::MilliSeconds(retryOptions.GetExponentalMultiplierMs()));
  42. }