userver: userver/utils/statistics/by_label_storage.hpp Source File
Loading...
Searching...
No Matches
by_label_storage.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/statistics/by_label_storage.hpp
4/// @brief @copybrief utils::statistics::MonotonicByLabelStorage
5
6#include <array>
7#include <concepts>
8#include <cstddef>
9#include <functional>
10#include <string>
11#include <string_view>
12#include <vector>
13
14#include <boost/container_hash/hash.hpp>
15#include <boost/pfr/core.hpp>
16#include <boost/pfr/core_name.hpp>
17#include <boost/pfr/tuple_size.hpp>
18
19#include <userver/concurrent/impl/monotonic_concurrent_set.hpp>
20#include <userver/utils/assert.hpp>
21#include <userver/utils/fixed_array.hpp>
22#include <userver/utils/statistics/labels.hpp>
23#include <userver/utils/statistics/writer.hpp>
24
25USERVER_NAMESPACE_BEGIN
26
27namespace utils::statistics {
28
29namespace impl {
30
31template <typename Metric>
32concept DumpableMetric = HasWriterSupport<Metric>;
33
34template <typename Metric>
35concept ResettableMetric = requires(Metric& m) { ResetMetric(m); };
36
37template <typename Field>
38std::string_view FieldToStringView(const Field& field) {
39 if constexpr (std::constructible_from<std::string_view, const Field&>) {
40 return std::string_view{field};
41 } else {
42 // ADL lookup.
43 return ToStringView(field);
44 }
45}
46
47template <typename Field>
48concept FieldConvertibleToStringView =
49 std::constructible_from<std::string_view, const Field&> || requires(const Field& f) {
50 {
51 ToStringView(f)
52 } -> std::same_as<std::string_view>;
53 };
54
55template <typename Field>
56concept FieldConstructibleFromStringView = std::constructible_from<Field, std::string_view>;
57
58template <typename Labels>
59concept AllFieldsConvertibleToStringView = []<std::size_t... Is>(std::index_sequence<Is...>) {
60 return (FieldConvertibleToStringView<boost::pfr::tuple_element_t<Is, Labels>> && ...);
61}(std::make_index_sequence<boost::pfr::tuple_size_v<Labels>>{});
62
63template <typename Labels>
64concept AllFieldsConstructibleFromStringView = []<std::size_t... Is>(std::index_sequence<Is...>) {
65 return (FieldConstructibleFromStringView<boost::pfr::tuple_element_t<Is, Labels>> && ...);
66}(std::make_index_sequence<boost::pfr::tuple_size_v<Labels>>{});
67
68template <typename Labels>
69concept LabelsAggregate = std::is_aggregate_v<Labels> && AllFieldsConvertibleToStringView<Labels>;
70
71template <typename Labels>
72auto LabelsStructToViewArray(const Labels& labels) {
73 constexpr std::size_t kN = boost::pfr::tuple_size_v<Labels>;
74 std::array<std::string_view, kN> result{};
75 boost::pfr::for_each_field(labels, [&result](const auto& field, std::size_t i) {
76 result[i] = FieldToStringView(field);
77 });
78 return result;
79}
80
81template <typename Labels>
82constexpr auto GetLabelNames() noexcept {
83 return boost::pfr::names_as_array<Labels>();
84}
85
86template <typename Labels, std::size_t... Is>
87Labels LabelsArrayToStruct(const utils::FixedArray<std::string>& arr, std::index_sequence<Is...>) {
88 UASSERT(arr.size() == sizeof...(Is));
89 return Labels{std::string_view{arr[Is]}...};
90}
91
92template <typename Labels>
93Labels LabelsArrayToStruct(const utils::FixedArray<std::string>& arr) {
94 return LabelsArrayToStruct<Labels>(arr, std::make_index_sequence<boost::pfr::tuple_size_v<Labels>>{});
95}
96
97// Transparent hash for utils::FixedArray<std::string>.
98struct FixedStringArrayHash {
99 using is_transparent [[maybe_unused]] = void;
100
101 template <typename StringViewRange>
102 std::size_t operator()(const StringViewRange& arr) const noexcept {
103 std::size_t hash = arr.size();
104 for (const auto& s : arr) {
105 boost::hash_combine(hash, std::hash<std::string_view>{}(s));
106 }
107 return hash;
108 }
109};
110
111// Transparent equality for utils::FixedArray<std::string>.
112struct FixedStringArrayEqual {
113 using is_transparent [[maybe_unused]] = void;
114
115 template <typename StringViewRange1, typename StringViewRange2>
116 bool operator()(const StringViewRange1& a, const StringViewRange2& b) const noexcept {
117 UASSERT(a.size() == b.size());
118 for (std::size_t i = 0; i < a.size(); ++i) {
119 if (std::string_view{a[i]} != std::string_view{b[i]}) {
120 return false;
121 }
122 }
123 return true;
124 }
125};
126
127// Entry stored in the set: label values + metric value.
128template <typename Metric>
129struct ByLabelEntry {
130 utils::FixedArray<std::string> labels;
131 Metric metric;
132
133 template <std::size_t N, typename... Args>
134 explicit ByLabelEntry(const std::array<std::string_view, N>& views, Args&&... args)
135 : labels(views.begin(), views.end()),
136 metric(std::forward<Args>(args)...)
137 {}
138};
139
140// Hash for ByLabelEntry - hashes only the labels part.
141template <typename Metric>
142struct ByLabelEntryHash {
143 using is_transparent [[maybe_unused]] = void;
144
145 std::size_t operator()(const ByLabelEntry<Metric>& entry) const noexcept {
146 return FixedStringArrayHash{}(entry.labels);
147 }
148
149 template <std::size_t N>
150 std::size_t operator()(const std::array<std::string_view, N>& key) const noexcept {
151 return FixedStringArrayHash{}(key);
152 }
153};
154
155// Equality for ByLabelEntry - compares only the labels part.
156template <typename Metric>
157struct ByLabelEntryEqual {
158 using is_transparent [[maybe_unused]] = void;
159
160 bool operator()(const ByLabelEntry<Metric>& a, const ByLabelEntry<Metric>& b) const noexcept {
161 return FixedStringArrayEqual{}(a.labels, b.labels);
162 }
163
164 template <std::size_t N>
165 bool operator()(const ByLabelEntry<Metric>& a, const std::array<std::string_view, N>& b) const noexcept {
166 return FixedStringArrayEqual{}(a.labels, b);
167 }
168
169 template <std::size_t N>
170 bool operator()(const std::array<std::string_view, N>& a, const ByLabelEntry<Metric>& b) const noexcept {
171 return FixedStringArrayEqual{}(a, b.labels);
172 }
173};
174
175} // namespace impl
176
177/// @ingroup userver_universal
178///
179/// @brief Thread-safe monotonic storage of metrics indexed by label values.
180///
181/// See @ref scripts/docs/en/userver/metrics.md .
182///
183/// `Labels` must be an aggregate type where all fields are convertible to `std::string_view`, by at least one of:
184///
185/// * a (possibly `explicit`) conversion operator to `std::string_view`;
186/// * an ADL-found `std::string_view ToStringView(const Field&)` function.
187///
188/// This includes `std::string_view` itself, `utils::Required<std::string_view>`,
189/// `std::string`, @ref utils::StrongTypedef, code-generated enums, etc.
190///
191/// Label names are taken from `Labels` field names.
192///
193/// Items can only be added, never removed.
194///
195/// @warning Avoid storing high-cardinality values as labels, especially when the client input can directly
196/// customize label values. This can lead to security issues where clients can cause metrics quota exhaustion
197/// or crashes due to OOM errors.
198///
199/// ## Usage of MonotonicByLabelStorage
200///
201/// Define a labels struct with `std::string_view` fields:
202/// @snippet core/src/utils/statistics/by_label_storage_test.cpp by_label_storage labels struct
203///
204/// Use @ref utils::Required for fields without adequate defaults to make sure they are always provided.
205///
206/// Declare a @ref utils::statistics::MetricTag for the storage:
207/// @snippet core/src/utils/statistics/by_label_storage_test.cpp by_label_storage metric tag
208///
209/// Write to the storage via `Emplace`:
210/// @snippet core/src/utils/statistics/by_label_storage_test.cpp by_label_storage emplace
211///
212/// ## Usage of MonotonicByLabelStorage with a group of per-label metrics
213///
214/// Any dumpable type is supported as `Metric`. When multiple metrics have the same labels,
215/// declare a struct with metrics and create a storage of structs instead of creating multiple storages.
216///
217/// Define the metric struct and its `DumpMetric`:
218/// @snippet core/src/utils/statistics/by_label_storage_test.cpp composite metric structs
219///
220/// Define the labels struct:
221/// @snippet core/src/utils/statistics/by_label_storage_test.cpp composite metric labels
222///
223/// Declare a @ref utils::statistics::MetricTag for the storage:
224/// @snippet core/src/utils/statistics/by_label_storage_test.cpp composite metric tag
225///
226/// Write to the storage:
227/// @snippet core/src/utils/statistics/by_label_storage_test.cpp composite metric usage
228///
229/// `MonotonicByLabelStorage` is also composable the other way around, it can be included in larger metric structures
230/// as a field.
231///
232/// ## Usage of MonotonicByLabelStorage with enum labels
233///
234/// An enum can be used as a label as long as it has `ToStringView` defined. Usage example:
235///
236/// @snippet core/src/utils/statistics/by_label_storage_test.cpp enum label ToStringView
237///
238/// @snippet core/src/utils/statistics/by_label_storage_test.cpp enum label labels
239///
240/// @snippet core/src/utils/statistics/by_label_storage_test.cpp enum label metric tag
241///
242/// @snippet core/src/utils/statistics/by_label_storage_test.cpp enum label usage
243///
244/// @tparam Labels An aggregate type whose fields are convertible to `std::string_view`.
245/// @tparam Metric The metric type. Must support `DumpMetric(Writer&, const Metric&)`.
246template <typename Labels, typename Metric>
247requires impl::LabelsAggregate<Labels>
249public:
250 /// @brief Create an empty storage.
252
253 MonotonicByLabelStorage(MonotonicByLabelStorage&&) = delete;
255
256 /// @brief Get or create a default-constructed metric for the given label values.
257 /// @param labels Label values.
258 /// @return Reference to the metric, valid until the storage's destruction.
259 Metric& operator[](const Labels& labels)
260 requires std::default_initializable<Metric>
261 {
262 return Emplace(labels);
263 }
264
265 /// @brief Get or create a metric for the given label values.
266 /// @param labels Label values.
267 /// @param args Arguments forwarded to `Metric` constructor on first insertion.
268 /// @return Reference to the metric, valid until the storage's destruction.
269 template <typename... Args>
270 requires std::constructible_from<Metric, Args...>
271 Metric& Emplace(const Labels& labels, Args&&... args) {
272 const auto view_array = impl::LabelsStructToViewArray(labels);
273 auto [entry, inserted] = set_.TryEmplace(view_array, view_array, std::forward<Args>(args)...);
274 (void)inserted;
275 return entry.metric;
276 }
277
278 /// @brief Find a metric by label values without creating it.
279 /// @return Pointer to the metric (valid until the storage's destruction), or nullptr if not found.
280 Metric* GetIfExists(const Labels& labels) {
281 const auto view_array = impl::LabelsStructToViewArray(labels);
282 auto ref = set_.Find(view_array);
283 if (ref) {
284 return &ref->metric;
285 }
286 return nullptr;
287 }
288
289 /// @brief Visit all stored metrics.
290 ///
291 /// Requires that all fields of `Labels` are constructible from `std::string_view`.
292 ///
293 /// @param func Callable accepting `(const Labels&, const Metric&)`.
294 void VisitAll(std::invocable<const Labels&, const Metric&> auto func) const
296 {
298 );
299 }
300
301 /// @brief Dump all metrics to a Writer, using label names from `Labels` fields.
302 friend void DumpMetric(Writer& writer, const MonotonicByLabelStorage& storage)
303 requires impl::DumpableMetric<Metric>
304 {
305 static constexpr auto kLabelNames = impl::GetLabelNames<Labels>();
306 static constexpr std::size_t kFieldCount = boost::pfr::tuple_size_v<Labels>;
307
308 std::vector<LabelView> label_views;
309 label_views.reserve(kFieldCount);
310
311 storage.set_.Visit([&writer, &label_views](const Entry& entry) {
312 label_views.clear();
313 for (std::size_t i = 0; i < kFieldCount; ++i) {
314 label_views.emplace_back(kLabelNames[i], entry.labels[i]);
315 }
316 writer.ValueWithLabels(entry.metric, label_views);
317 });
318 }
319
320 /// @brief Reset all metrics (only available if `Metric` has ADL-found `ResetMetric`).
322 requires impl::ResettableMetric<Metric>
323 {
324 storage.set_.Visit([](Entry& entry) { ResetMetric(entry.metric); });
325 }
326
327private:
328 using Entry = impl::ByLabelEntry<Metric>;
329 using Set = concurrent::impl::MonotonicConcurrentSet<
330 Entry,
331 impl::ByLabelEntryHash<Metric>,
332 impl::ByLabelEntryEqual<Metric>>;
333
334 Set set_;
335};
336
337} // namespace utils::statistics
338
339USERVER_NAMESPACE_END