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