userver: userver/utils/statistics/writer.hpp Source File
Loading...
Searching...
No Matches
writer.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/statistics/writer.hpp
4/// @brief @copybrief utils::statistics::Writer
5/// @ingroup userver_universal
6
7#include <atomic>
8#include <cstdint>
9#include <initializer_list>
10#include <string_view>
11#include <type_traits>
12
13#include <userver/utils/impl/internal_tag.hpp>
14#include <userver/utils/statistics/histogram_view.hpp>
15#include <userver/utils/statistics/labels.hpp>
16#include <userver/utils/statistics/rate.hpp>
17
18USERVER_NAMESPACE_BEGIN
19
20namespace utils::statistics {
21
22class Writer;
23class MetricValue;
24
25namespace impl {
26struct WriterState;
27} // namespace impl
28
29/// @brief Returns true, if the `Metric` could be written by @ref utils::statistics::Writer.
30///
31/// In other words, checks that the `DumpMetric` for the `Metric` is provided or
32/// that the metric could be written without providing one.
33template <class Metric>
34concept HasWriterSupport = std::is_arithmetic_v<Metric> || requires(Writer& writer, const Metric& metric) {
35 DumpMetric(writer, metric);
36};
37
38/// @ingroup userver_universal
39///
40/// @brief Class for writing metrics that is provided by utils::statistics::Storage.
41///
42/// Usage is quite straightforward:
43///
44/// @snippet core/src/utils/statistics/storage_test.cpp Writer basic sample
45///
46/// The above sample would produce the following metrics:
47///
48/// @snippet core/src/utils/statistics/storage_test.cpp metrics pretty
49///
50/// The Writer can be customized for writing custom metric types by providing a
51/// `void DumpMetric(utils::statistics::Writer& writer, const CustomMetric& value)`
52/// function:
53///
54/// @snippet universal/src/utils/statistics/writer_test.cpp DumpMetric basic
55///
56/// DumpMetric functions nest well, labels are propagated to the nested
57/// DumpMetric:
58///
59/// @snippet universal/src/utils/statistics/writer_test.cpp DumpMetric nested
60///
61/// To use the above writers register the metric writer in
62/// @ref utils::statistics::Storage component:
63///
64/// @snippet core/src/utils/statistics/storage_test.cpp DumpMetric RegisterWriter
65///
66/// The above metrics in Graphite format would look like:
67/// @snippet core/src/utils/statistics/storage_test.cpp metrics graphite
68///
69/// The Writer is usable by the utils::statistics::MetricTag. For example, for
70/// the following structure:
71/// @snippet samples/tcp_full_duplex_service/main.cpp TCP sample - Stats definition
72///
73/// The DumpMetric function may look like:
74/// @snippet samples/tcp_full_duplex_service/main.cpp TCP sample - Stats tag
75///
76/// A writer and its children share mutable path and label state. Destroy a child before writing through its parent
77/// or creating a sibling. Use a nested block to delimit the child's lifetime when necessary. Writers are neither
78/// copyable nor movable; store a child in a local variable before passing it as `Writer&`.
79///
80/// Emit each metric, identified by its path and labels, once per collection. Writing a metric again does not replace
81/// its previously exported value. Compute the final value before exporting it.
82///
83/// For introduction to metrics see @ref scripts/docs/en/userver/metrics.md
84///
85/// For metrics testing in testsuite see @ref TESTSUITE_METRICS_TESTING "Testsuite - Metrics".
86/// For metrics testing in unit tests see @ref utils::statistics::Snapshot.
87class Writer final {
88public:
89 /// Path parts delimiter. In other words, writer["a"]["b"] becomes "a.b"
90 static constexpr char kDelimiter = '.';
91
92 Writer() = delete;
93 Writer(Writer&& other) = delete;
94 Writer(const Writer&) = delete;
95 Writer& operator=(Writer&&) = delete;
96 Writer& operator=(const Writer&) = delete;
97
98 ~Writer();
99
100 /// Returns a child writer with `path` appended, separated by a dot. Dots in `path` are separators too:
101 /// `writer["a.b"]` and `writer["a"]["b"]` produce the same path. Output formats handle escaping; do not replace
102 /// dots with underscores manually. The path's contents are copied during the call.
103 /// See @ref utils::statistics::Writer for child lifetime restrictions.
104 [[nodiscard]] Writer operator[](std::string_view path) &;
105
106 /// @overload
107 [[nodiscard]] Writer operator[](std::string_view path) &&;
108
109 /// Write metric value to metrics builder via using DumpMetric
110 /// function.
111 template <class T>
112 void operator=(const T& value) {
113 if constexpr (std::is_arithmetic_v<T> || std::is_same_v<std::decay_t<T>, Rate> ||
114 std::is_same_v<std::decay_t<T>, HistogramView> || std::is_same_v<std::decay_t<T>, MetricValue>)
115 {
116 Write(value);
117 } else {
118 if (state_) {
119 static_assert(
121 "Cast the metric to an arithmetic type or provide a "
122 "`void DumpMetric(utils::statistics::Writer& writer, "
123 "const Metric& value)` function for the `Metric` type"
124 );
125 DumpMetric(*this, value);
126 }
127 }
128 }
129
130 /// Writes a metric value with additional labels. Labels are inherited by all metrics exported by the value's
131 /// `DumpMetric`. Label strings are borrowed and must remain valid until this synchronous call returns, including
132 /// any nested exports.
133 template <class T>
134 void ValueWithLabels(const T& value, LabelsSpan labels) {
135 auto new_writer = MakeChild();
136 new_writer.AppendLabelsSpan(labels);
137 new_writer = value;
138 }
139
140 /// @overload
141 template <class T>
142 void ValueWithLabels(const T& value, std::initializer_list<LabelView> il) {
143 ValueWithLabels(value, LabelsSpan{il});
144 }
145
146 /// @overload
147 template <class T>
148 void ValueWithLabels(const T& value, const LabelView& label) {
149 ValueWithLabels(value, LabelsSpan{&label, &label + 1});
150 }
151
152 /// @cond
153 /// func must be called even for filtered out Writers, e.g. to always collect
154 /// totals
155 template <class Func>
156 void WithLabels(utils::impl::InternalTag, LabelsSpan labels, Func func) {
157 auto new_writer = MakeChild();
158 new_writer.AppendLabelsSpan(labels);
159 func(new_writer);
160 }
161
162 template <class Func>
163 void WithLabels(utils::impl::InternalTag, std::initializer_list<LabelView> il, Func func) {
164 WithLabels(utils::impl::InternalTag{}, LabelsSpan{il}, func);
165 }
166
167 template <class Func>
168 void WithLabels(utils::impl::InternalTag, const LabelView& label, Func func) {
169 WithLabels(utils::impl::InternalTag{}, LabelsSpan{&label, &label + 1}, func);
170 }
171 /// @endcond
172
173 /// Returns true if this writer would actually write data. Returns false if
174 /// the data is not required by request and metrics construction could be
175 /// skipped.
176 explicit operator bool() const noexcept { return !!state_; }
177
178 /// @cond
179 explicit Writer(impl::WriterState* state) noexcept;
180 explicit Writer(impl::WriterState& state, LabelsSpan labels);
181 /// @endcond
182
183private:
184 using ULongLong = unsigned long long;
185
186 using PathSizeType = std::uint16_t;
187 using LabelsSizeType = std::uint8_t;
188
189 void Write(unsigned long long value);
190 void Write(long long value);
191 void Write(double value);
192 void Write(Rate value);
193 void Write(HistogramView value);
194 void Write(MetricValue value);
195
196 void Write(float value) { Write(static_cast<double>(value)); }
197
198 void Write(unsigned long value) { Write(static_cast<ULongLong>(value)); }
199 void Write(long value) { Write(static_cast<long long>(value)); }
200 void Write(unsigned int value) { Write(static_cast<long long>(value)); }
201 void Write(int value) { Write(static_cast<long long>(value)); }
202 void Write(unsigned short value) { Write(static_cast<long long>(value)); }
203 void Write(short value) { Write(static_cast<long long>(value)); }
204
205 Writer MakeChild();
206
207 struct MoveTag {};
208 Writer(Writer& other, MoveTag) noexcept;
209
210 Writer MoveOut() noexcept { return Writer{*this, MoveTag{}}; }
211
212 void ResetState() noexcept;
213 void ValidateUsage();
214
215 void AppendPath(std::string_view path);
216 void AppendLabelsSpan(LabelsSpan labels);
217
218 impl::WriterState* state_;
219 const PathSizeType initial_path_size_;
220 PathSizeType current_path_size_;
221 const LabelsSizeType initial_labels_size_;
222 LabelsSizeType current_labels_size_;
223};
224
225template <class Metric>
226void DumpMetric(Writer& writer, const std::atomic<Metric>& m) {
227 static_assert(std::atomic<Metric>::is_always_lock_free, "std::atomic misuse");
228 writer = m.load();
229}
230
231} // namespace utils::statistics
232
233USERVER_NAMESPACE_END