aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/tvmauth/client/misc/exponential_backoff.h
blob: 95bc29de11dad23d4e6a47e4b275e96402f12282 (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#pragma once

#include <util/datetime/base.h>
#include <util/random/normal.h>
#include <util/system/event.h>

#include <atomic> 
 
namespace NTvmAuth {
    // https://habr.com/ru/post/227225/
    class TExponentialBackoff {
    public:
        struct TSettings {
            TDuration Min;
            TDuration Max;
            double Factor = 1.001;
            double Jitter = 0;

            bool operator==(const TSettings& o) const {
                return Min == o.Min &&
                       Max == o.Max &&
                       Factor == o.Factor &&
                       Jitter == o.Jitter;
            }
        };

        TExponentialBackoff(const TSettings& settings, bool isEnabled = true)
            : CurrentValue_(settings.Min)
            , IsEnabled_(isEnabled)
        {
            UpdateSettings(settings);
        }

        void UpdateSettings(const TSettings& settings) {
            Y_ENSURE(settings.Factor > 1, "factor=" << settings.Factor << ". Should be > 1");
            Y_ENSURE(settings.Jitter >= 0 && settings.Jitter < 1, "jitter should be in range [0, 1)");

            Min_ = settings.Min;
            Max_ = settings.Max;
            Factor_ = settings.Factor;
            Jitter_ = settings.Jitter;
        }

        TDuration Increase() {
            CurrentValue_ = std::min(CurrentValue_ * Factor_, Max_);

            double rnd = StdNormalRandom<double>();
            const bool isNegative = rnd < 0;
            rnd = std::abs(rnd);

            const TDuration diff = rnd * Jitter_ * CurrentValue_;
            if (isNegative) {
                CurrentValue_ -= diff;
            } else {
                CurrentValue_ += diff;
            }

            return CurrentValue_;
        }

        TDuration Decrease() {
            CurrentValue_ = std::max(CurrentValue_ / Factor_, Min_);
            return CurrentValue_;
        }

        void Sleep(TDuration add = TDuration()) {
            if (IsEnabled_.load(std::memory_order_relaxed)) {
                Ev_.WaitT(CurrentValue_ + add);
            }
        }

        void Interrupt() {
            Ev_.Signal();
        }

        TDuration GetCurrentValue() const {
            return CurrentValue_;
        }

        void SetEnabled(bool val) {
            IsEnabled_.store(val);
        }

    private:
        TDuration Min_;
        TDuration Max_;
        double Factor_;
        double Jitter_;
        TDuration CurrentValue_;
        std::atomic_bool IsEnabled_;

        TAutoEvent Ev_;
    };
}