aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/retry/retry.cpp
blob: f41c97e1794b2b9d63390178bfbbfadb093df6e3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "retry.h"

#include <util/stream/output.h>

namespace {
class TRetryOptionsWithRetCodePolicy : public IRetryPolicy<bool> {
public:
    explicit TRetryOptionsWithRetCodePolicy(const TRetryOptions& opts)
        : Opts(opts)
    {
    }

    class TRetryState : public IRetryState {
    public:
        explicit TRetryState(const TRetryOptions& opts)
            : Opts(opts)
        {
        }

        TMaybe<TDuration> GetNextRetryDelay(bool ret) override {
            if (ret || Attempt == Opts.RetryCount) {
                return Nothing();
            }
            return Opts.GetTimeToSleep(Attempt++);
        }

    private:
        const TRetryOptions Opts;
        size_t Attempt = 0;
    };

    IRetryState::TPtr CreateRetryState() const override {
        return std::make_unique<TRetryState>(Opts);
    }

private:
    const TRetryOptions Opts;
};
} // namespace

bool DoWithRetryOnRetCode(std::function<bool()> func, TRetryOptions retryOptions) {
    return DoWithRetryOnRetCode<bool>(std::move(func), std::make_shared<TRetryOptionsWithRetCodePolicy>(retryOptions), retryOptions.SleepFunction);
}

TRetryOptions MakeRetryOptions(const NRetry::TRetryOptionsPB& retryOptions) {
    return TRetryOptions(retryOptions.GetMaxTries(),
                         TDuration::MilliSeconds(retryOptions.GetInitialSleepMs()),
                         TDuration::MilliSeconds(retryOptions.GetRandomDeltaMs()),
                         TDuration::MilliSeconds(retryOptions.GetSleepIncrementMs()),
                         TDuration::MilliSeconds(retryOptions.GetExponentalMultiplierMs()));
}