-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathstateless_meters.h
More file actions
299 lines (252 loc) · 8.46 KB
/
stateless_meters.h
File metadata and controls
299 lines (252 loc) · 8.46 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#pragma once
#include <cassert>
#include <charconv>
#include <cmath>
#include "id.h"
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
namespace spectator {
namespace detail {
#include "valid_chars.inc"
// IEEE 754 double in fixed notation requires at most 1076 chars
// (sign + 1074 fractional digits + decimal point for minimum subnormal).
static constexpr size_t kMaxFixedDoubleLen = 1076;
inline std::string as_string(std::string_view v) {
return {v.data(), v.size()};
}
inline bool contains_non_atlas_char(const std::string& input) {
return std::any_of(input.begin(), input.end(), [](char c) { return !kAtlasChars[c]; });
}
inline std::string replace_invalid_characters(const std::string& input) {
if (contains_non_atlas_char(input)) {
std::string result{input};
for (char &c : result) {
if (!kAtlasChars[c]) {
c = '_';
}
}
return result;
} else {
return input;
}
}
inline std::string create_prefix(const Id& id, std::string_view type_name) {
std::string res = as_string(type_name) + ":" + replace_invalid_characters(id.Name());
for (const auto& tags : id.GetTags()) {
auto first = replace_invalid_characters(tags.first);
auto second = replace_invalid_characters(tags.second);
absl::StrAppend(&res, ",", first, "=", second);
}
absl::StrAppend(&res, ":");
return res;
}
// Single thread-local send buffer shared across all StatelessMeter instantiations.
// Non-template so all Pub types resolve to the same storage slot per thread.
// Not re-entrant: callers must complete send() before the buffer is safe to reuse.
inline std::string& tl_send_buf() {
thread_local std::string buf;
return buf;
}
template <typename T>
T restrict(T amount, T min, T max) {
auto r = amount;
if (r > max) {
r = max;
} else if (r < min) {
r = min;
}
return r;
}
} // namespace detail
template <typename Pub>
class StatelessMeter {
public:
StatelessMeter(IdPtr id, Pub* publisher)
: id_(std::move(id)), publisher_(publisher) {
assert(publisher_ != nullptr);
}
virtual ~StatelessMeter() = default;
std::string GetPrefix() {
ensure_prefix();
return value_prefix_;
}
[[nodiscard]] IdPtr MeterId() const noexcept { return id_; }
[[nodiscard]] virtual std::string_view Type() = 0;
protected:
void send(double value) {
ensure_prefix();
auto& tl_msg = detail::tl_send_buf();
tl_msg.assign(value_prefix_);
// Early exit: match absl::StrFormat("%f") behaviour for special values.
if (std::isnan(value)) {
tl_msg.append("nan");
publisher_->send(tl_msg);
return;
}
if (std::isinf(value)) {
tl_msg.append(value > 0 ? "inf" : "-inf");
publisher_->send(tl_msg);
return;
}
// std::to_chars with fixed format: no trailing zeros, no scientific notation,
// ~5-10x faster than absl::StrFormat("%s%f",...) + erase.
// Stack buffer covers typical values; heap fallback for extreme cases (subnormals).
char num_buf[64];
auto [ptr, ec] = std::to_chars(num_buf, num_buf + sizeof(num_buf), value,
std::chars_format::fixed);
if (ec == std::errc{}) {
tl_msg.append(num_buf, ptr);
} else {
// Fallback for subnormal values, which require up to 1076 chars in fixed
// notation. NaN/Inf are handled above, so this branch is subnormals only.
auto off = tl_msg.size();
tl_msg.resize(off + detail::kMaxFixedDoubleLen);
auto [heap_ptr, heap_ec] = std::to_chars(tl_msg.data() + off,
tl_msg.data() + tl_msg.size(), value,
std::chars_format::fixed);
assert(heap_ec == std::errc{});
tl_msg.resize(static_cast<size_t>(heap_ptr - tl_msg.data()));
}
publisher_->send(tl_msg);
}
void send_uint(uint64_t value) {
ensure_prefix();
char num_buf[24];
auto [ptr, ec] = std::to_chars(num_buf, num_buf + sizeof(num_buf), value);
assert(ec == std::errc{});
auto& tl_msg = detail::tl_send_buf();
tl_msg.assign(value_prefix_);
tl_msg.append(num_buf, ptr);
publisher_->send(tl_msg);
}
private:
IdPtr id_;
Pub* publisher_;
std::string value_prefix_;
void ensure_prefix() {
if (value_prefix_.empty()) {
value_prefix_ = detail::create_prefix(*id_, Type());
}
}
};
template <typename Pub>
class AgeGauge : public StatelessMeter<Pub> {
public:
AgeGauge(IdPtr id, Pub* publisher)
: StatelessMeter<Pub>(std::move(id), publisher) {}
void Now() noexcept { this->send(0); }
void Set(double value) noexcept { this->send(value); }
protected:
std::string_view Type() override { return "A"; }
};
template <typename Pub>
class Counter : public StatelessMeter<Pub> {
public:
Counter(IdPtr id, Pub* publisher)
: StatelessMeter<Pub>(std::move(id), publisher) {}
void Increment() noexcept { this->send(1); };
void Add(double delta) noexcept { this->send(delta); }
protected:
std::string_view Type() override { return "c"; }
};
template <typename Pub>
class DistributionSummary : public StatelessMeter<Pub> {
public:
DistributionSummary(IdPtr id, Pub* publisher)
: StatelessMeter<Pub>(std::move(id), publisher) {}
void Record(double amount) noexcept { this->send(amount); }
protected:
std::string_view Type() override { return "d"; }
};
template <typename Pub>
class Gauge : public StatelessMeter<Pub> {
public:
Gauge(IdPtr id, Pub* publisher)
: StatelessMeter<Pub>(std::move(id), publisher) {}
void Set(double value) noexcept { this->send(value); }
protected:
std::string_view Type() override { return "g"; }
};
template <typename Pub>
class MaxGauge : public StatelessMeter<Pub> {
public:
MaxGauge(IdPtr id, Pub* publisher)
: StatelessMeter<Pub>(std::move(id), publisher) {}
void Update(double value) noexcept { this->send(value); }
// synonym for Update for consistency with the Gauge interface
void Set(double value) noexcept { this->send(value); }
protected:
std::string_view Type() override { return "m"; }
};
template <typename Pub>
class MonotonicCounter : public StatelessMeter<Pub> {
public:
MonotonicCounter(IdPtr id, Pub* publisher)
: StatelessMeter<Pub>(std::move(id), publisher) {}
void Set(double amount) noexcept { this->send(amount); }
protected:
std::string_view Type() override { return "C"; }
};
template <typename Pub>
class MonotonicCounterUint : public StatelessMeter<Pub> {
public:
MonotonicCounterUint(IdPtr id, Pub* publisher)
: StatelessMeter<Pub>(std::move(id), publisher) {}
void Set(uint64_t amount) noexcept { this->send_uint(amount); }
protected:
std::string_view Type() override { return "U"; }
};
template <typename Pub>
class PercentileDistributionSummary : public StatelessMeter<Pub> {
public:
PercentileDistributionSummary(IdPtr id, Pub* publisher, int64_t min,
int64_t max)
: StatelessMeter<Pub>(std::move(id), publisher), min_{min}, max_{max} {}
void Record(int64_t amount) noexcept {
this->send(detail::restrict(amount, min_, max_));
}
protected:
std::string_view Type() override { return "D"; }
private:
int64_t min_;
int64_t max_;
};
template <typename Pub>
class PercentileTimer : public StatelessMeter<Pub> {
public:
PercentileTimer(IdPtr id, Pub* publisher, absl::Duration min,
absl::Duration max)
: StatelessMeter<Pub>(std::move(id), publisher), min_(min), max_(max) {}
PercentileTimer(IdPtr id, Pub* publisher, std::chrono::nanoseconds min,
std::chrono::nanoseconds max)
: PercentileTimer(std::move(id), publisher, absl::FromChrono(min),
absl::FromChrono(max)) {}
void Record(std::chrono::nanoseconds amount) noexcept {
Record(absl::FromChrono(amount));
}
void Record(absl::Duration amount) noexcept {
auto duration = detail::restrict(amount, min_, max_);
this->send(absl::ToDoubleSeconds(duration));
}
protected:
std::string_view Type() override { return "T"; }
private:
absl::Duration min_;
absl::Duration max_;
};
template <typename Pub>
class Timer : public StatelessMeter<Pub> {
public:
Timer(IdPtr id, Pub* publisher)
: StatelessMeter<Pub>(std::move(id), publisher) {}
void Record(std::chrono::nanoseconds amount) noexcept {
Record(absl::FromChrono(amount));
}
void Record(absl::Duration amount) noexcept {
auto secs = absl::ToDoubleSeconds(amount);
this->send(secs);
}
protected:
std::string_view Type() override { return "t"; }
};
} // namespace spectator