userver: userver/utils/statistics/recentperiod.hpp Source File
Loading...
Searching...
No Matches
recentperiod.hpp
1#pragma once
2
3#include <atomic>
4#include <chrono>
5#include <type_traits>
6
7#include <userver/utils/assert.hpp>
8#include <userver/utils/datetime.hpp>
9#include <userver/utils/fixed_array.hpp>
10#include <userver/utils/statistics/fwd.hpp>
11#include <userver/utils/statistics/recentperiod_detail.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace utils::statistics {
16
17/** \brief Class maintains circular buffer of Counters
18 *
19 * At any time current Counter is accessible for modification via
20 * GetCurrentCounter().
21 * Counter can provide a Reset() member function to clear contents.
22 * @see utils::statistics::Percentile
23 */
24template <typename Counter, typename Result, typename Timer = utils::datetime::SteadyClock>
26public:
27 using Duration = typename Timer::duration;
28
29 static_assert(
30 (detail::kResultWantsAddFunction<Result, Counter, Duration> || detail::kResultCanUseAddAssign<Result, Counter>),
31 "The Result template type argument must provide either Add(Counter, "
32 "Duration, Duration) function or add assignment operator"
33 );
34
35 static constexpr bool kUseAddFunction = detail::kResultWantsAddFunction<Result, Counter, Duration>;
36
37 /**
38 * @param epoch_duration duration of epoch.
39 * @param max_duration max duration to calculate statistics for
40 * must be multiple of epoch_duration.
41 */
42 RecentPeriod(Duration epoch_duration = std::chrono::seconds(5), Duration max_duration = std::chrono::seconds(60))
43 : epoch_duration_(epoch_duration),
44 max_duration_(max_duration),
45 epoch_index_(0),
46 items_(GetSizeForDuration(epoch_duration, max_duration)) {
47 UINVARIANT(Duration::zero() < epoch_duration_, "epoch_duration should be greater than 0");
48 }
49
50 Counter& GetCurrentCounter() { return items_[GetCurrentIndex()].counter; }
51
52 Counter& GetPreviousCounter(int epochs_ago) { return items_[GetPreviousIndex(epochs_ago)].counter; }
53
54 /** \brief Aggregates counters within given time range
55 *
56 * @param duration Time range. Special value Duration::min() -> use
57 * whole RecentPeriod range.
58 * @param with_current_epoch Include current (possibly unfinished) counter
59 * into aggregation
60 *
61 * Type Result must have method Add(Counter, Duration, Duration) or allow
62 * addition of counter values
63 */
64 // NOLINTNEXTLINE(readability-const-return-type)
65 const Result GetStatsForPeriod(Duration duration = Duration::min(), bool with_current_epoch = false) const {
66 if (duration == Duration::min()) {
67 duration = max_duration_;
68 }
69
70 Result result{};
71 const Duration now = Timer::now().time_since_epoch();
72 const Duration current_epoch = GetEpochForDuration(now);
73 const Duration start_epoch = current_epoch - duration;
74 const Duration first_epoch_duration = now - current_epoch;
75 std::size_t index = epoch_index_.load();
76
77 for (std::size_t i = 0; i < items_.size(); i++, index = (index + items_.size() - 1) % items_.size()) {
78 const Duration epoch = items_[index].epoch;
79
80 if (epoch > current_epoch) continue;
81 if (epoch == current_epoch && !with_current_epoch) continue;
82 if (epoch < start_epoch) break;
83
84 if constexpr (kUseAddFunction) {
85 const Duration this_epoch_duration = (i == 0) ? first_epoch_duration : epoch_duration_;
86
87 const Duration before_this_epoch_duration = epoch - start_epoch;
88 result.Add(items_[index].counter, this_epoch_duration, before_this_epoch_duration);
89 } else {
90 result += items_[index].counter;
91 }
92 }
93
94 return result;
95 }
96
97 Duration GetEpochDuration() const { return epoch_duration_; }
98
99 Duration GetMaxDuration() const { return max_duration_; }
100
101 void UpdateEpochIfOld() { [[maybe_unused]] auto ignore = GetCurrentIndex(); }
102
103 void Reset() {
104 for (auto& item : items_) {
105 item.Reset();
106 }
107 }
108
109private:
110 size_t GetCurrentIndex() const {
111 while (true) {
112 const Duration now = Timer::now().time_since_epoch();
113 const Duration epoch = GetEpochForDuration(now);
114 std::size_t index = epoch_index_.load();
115 const Duration bucket_epoch = items_[index].epoch.load();
116
117 if (epoch != bucket_epoch) {
118 const std::size_t new_index = (index + 1) % items_.size();
119
120 if (epoch_index_.compare_exchange_weak(index, new_index)) {
121 items_[new_index].epoch = epoch;
122 items_[(new_index + 1) % items_.size()].Reset();
123 return new_index;
124 }
125 } else {
126 return index;
127 }
128 }
129 }
130
131 std::size_t GetPreviousIndex(int epochs_ago) {
132 int index = static_cast<int>(GetCurrentIndex()) - epochs_ago;
133 while (index < 0) index += items_.size();
134 return index % items_.size();
135 }
136
137 Duration GetEpochForDuration(Duration duration) const {
138 auto now = std::chrono::duration_cast<Duration>(duration);
139 return now - now % epoch_duration_;
140 }
141
142 static std::size_t GetSizeForDuration(Duration epoch_duration, Duration max_duration) {
143 /* 3 = current bucket, next zero bucket and extra one to handle
144 possible race. */
145 return max_duration.count() / epoch_duration.count() + 3;
146 }
147
148 struct EpochBucket {
149 static constexpr bool kUseReset = detail::kCanReset<Counter>;
150 std::atomic<Duration> epoch;
151 Counter counter;
152
153 EpochBucket() { Reset(); }
154
155 void Reset() {
156 epoch = Duration::min();
157 if constexpr (kUseReset) {
158 counter.Reset();
159 } else {
160 counter = 0;
161 }
162 }
163 };
164
165 const Duration epoch_duration_;
166 const Duration max_duration_;
167 mutable std::atomic_size_t epoch_index_;
168 mutable utils::FixedArray<EpochBucket> items_;
169};
170
171/// @a Writer support for @a RecentPeriod
172template <typename Counter, typename Result, typename Timer>
173void DumpMetric(Writer& writer, const RecentPeriod<Counter, Result, Timer>& recent_period) {
174 writer = recent_period.GetStatsForPeriod();
175}
176
177/// Reset support for @a RecentPeriod
178template <typename Counter, typename Result, typename Timer>
179void ResetMetric(RecentPeriod<Counter, Result, Timer>& recent_period) {
180 recent_period.Reset();
181}
182
183} // namespace utils::statistics
184
185USERVER_NAMESPACE_END