feat(Observability): add zero-dep hooks, HookLease, ContextSnapshot, bounded metrics/tracing, and snapshot exporter (S-OBSERVABILITY-01..04)
This commit is contained in:
1 parent
809b6f548d
commit
fe99051ded
16 files changed
+3545
No files matched your search
@@ -0,0 +1,808 @@
|
||||
#include <Void/Observability/Metrics.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Observability
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
constexpr std::size_t kPerSeriesOverheadBytes = 128;
|
||||
|
||||
[[nodiscard]] bool valid_token(std::string_view sv) noexcept
|
||||
{
|
||||
for (const unsigned char ch : sv) {
|
||||
if (ch < 0x20 || ch == 0x7F) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid_label_name(std::string_view sv) noexcept
|
||||
{
|
||||
if (sv.empty() || !valid_token(sv)) {
|
||||
return false;
|
||||
}
|
||||
for (const char ch : sv) {
|
||||
if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
struct CanonicalLabels {
|
||||
std::string key;
|
||||
std::vector<std::string> values;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::uint64_t saturating_add_u64(
|
||||
std::uint64_t lhs,
|
||||
std::uint64_t rhs,
|
||||
bool& saturated) noexcept
|
||||
{
|
||||
constexpr auto kMax = std::numeric_limits<std::uint64_t>::max();
|
||||
if (rhs > kMax - lhs) {
|
||||
saturated = true;
|
||||
return kMax;
|
||||
}
|
||||
return lhs + rhs;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<void> MetricsLimits::validate() const
|
||||
{
|
||||
if (max_instruments == 0 || max_series_per_instrument == 0 ||
|
||||
max_total_series == 0 || max_labels_per_point == 0 ||
|
||||
max_key_bytes == 0 || max_value_bytes == 0 ||
|
||||
max_producer_shards == 0 || max_storage_bytes == 0) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"MetricsLimits values must be non-zero"));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
struct MetricRegistry::Impl {
|
||||
struct SeriesMeta {
|
||||
std::size_t series_id{0};
|
||||
bool is_overflow{false};
|
||||
std::vector<std::pair<std::string, std::string>> labels{};
|
||||
std::size_t byte_cost{0};
|
||||
};
|
||||
|
||||
struct InstrumentData {
|
||||
InstrumentSpec spec{};
|
||||
std::vector<SeriesMeta> series{};
|
||||
std::unordered_map<std::string, std::size_t> key_to_series{};
|
||||
std::atomic<bool> overflow_seen{false};
|
||||
std::atomic<std::uint64_t> dropped_series{0};
|
||||
std::atomic<std::uint64_t> overflow_events{0};
|
||||
};
|
||||
|
||||
struct SeriesAccumulator {
|
||||
std::uint64_t counter_value{0};
|
||||
bool counter_saturated{false};
|
||||
double gauge_value{0.0};
|
||||
bool has_gauge_sample{false};
|
||||
std::uint64_t gauge_seq{0};
|
||||
Void::Time::MonotonicClock::time_point gauge_timestamp{};
|
||||
std::vector<std::uint64_t> hist_buckets{};
|
||||
std::uint64_t hist_count{0};
|
||||
double hist_sum{0.0};
|
||||
};
|
||||
|
||||
struct Shard {
|
||||
std::mutex mutex;
|
||||
// Indexed by [instrument_idx][series_id]
|
||||
std::vector<std::vector<SeriesAccumulator>> data;
|
||||
};
|
||||
|
||||
struct TlsShardEntry {
|
||||
std::uint64_t registry_id{0};
|
||||
std::weak_ptr<Shard> shard{};
|
||||
};
|
||||
|
||||
static std::uint64_t next_id() noexcept
|
||||
{
|
||||
static std::atomic<std::uint64_t> seq{1};
|
||||
return seq.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
explicit Impl(MetricsLimits lim, const Void::Time::MonotonicClock* clk)
|
||||
: id(next_id())
|
||||
, limits(lim)
|
||||
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
|
||||
, fallback_shard(std::make_shared<Shard>())
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<Shard> acquire_shard()
|
||||
{
|
||||
static thread_local std::vector<TlsShardEntry> tls_cache;
|
||||
|
||||
for (auto it = tls_cache.begin(); it != tls_cache.end();) {
|
||||
if (it->shard.expired()) {
|
||||
it = tls_cache.erase(it);
|
||||
continue;
|
||||
}
|
||||
if (it->registry_id == id) {
|
||||
if (auto locked = it->shard.lock()) {
|
||||
return locked;
|
||||
}
|
||||
it = tls_cache.erase(it);
|
||||
continue;
|
||||
}
|
||||
++it;
|
||||
}
|
||||
|
||||
std::shared_ptr<Shard> assigned;
|
||||
{
|
||||
std::lock_guard lock{shards_mutex};
|
||||
if (shards.size() < limits.max_producer_shards) {
|
||||
assigned = std::make_shared<Shard>();
|
||||
shards.push_back(assigned);
|
||||
} else {
|
||||
shared_shard_fallbacks.fetch_add(1, std::memory_order_relaxed);
|
||||
assigned = fallback_shard;
|
||||
}
|
||||
}
|
||||
tls_cache.push_back(TlsShardEntry{id, assigned});
|
||||
return assigned;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<CanonicalLabels> build_canonical_labels(
|
||||
const InstrumentData& inst,
|
||||
std::span<const AttributeView> attributes) const
|
||||
{
|
||||
if (attributes.size() > limits.max_labels_per_point) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Attribute count exceeds max_labels_per_point"));
|
||||
}
|
||||
|
||||
CanonicalLabels result;
|
||||
result.values.resize(inst.spec.label_keys.size());
|
||||
std::vector<bool> seen(inst.spec.label_keys.size(), false);
|
||||
|
||||
for (const auto& attr : attributes) {
|
||||
if (attr.key.empty() || attr.key.size() > limits.max_key_bytes ||
|
||||
!valid_token(attr.key)) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Invalid attribute key"));
|
||||
}
|
||||
if (attr.value.size() > limits.max_value_bytes ||
|
||||
!valid_token(attr.value)) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Invalid attribute value"));
|
||||
}
|
||||
const auto key_it = std::find(inst.spec.label_keys.begin(),
|
||||
inst.spec.label_keys.end(),
|
||||
attr.key);
|
||||
if (key_it == inst.spec.label_keys.end()) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Undeclared metric label key"));
|
||||
}
|
||||
const auto pos = static_cast<std::size_t>(
|
||||
std::distance(inst.spec.label_keys.begin(), key_it));
|
||||
if (seen[pos]) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Duplicate metric label key in single observation"));
|
||||
}
|
||||
seen[pos] = true;
|
||||
result.values[pos].assign(attr.value);
|
||||
}
|
||||
|
||||
std::size_t total_len = result.values.size() * 4;
|
||||
for (const auto& v : result.values) {
|
||||
total_len += v.size();
|
||||
}
|
||||
result.key.reserve(total_len);
|
||||
for (const auto& v : result.values) {
|
||||
result.key.append(std::to_string(v.size()));
|
||||
result.key.push_back(':');
|
||||
result.key.append(v);
|
||||
result.key.push_back('\x1f');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t resolve_or_create_series(
|
||||
std::size_t inst_idx,
|
||||
const CanonicalLabels& canonical)
|
||||
{
|
||||
std::unique_lock dir_lock{dir_mutex};
|
||||
auto& inst = *instruments[inst_idx];
|
||||
|
||||
if (const auto it = inst.key_to_series.find(canonical.key);
|
||||
it != inst.key_to_series.end()) {
|
||||
return it->second;
|
||||
}
|
||||
|
||||
const std::size_t current_normal =
|
||||
inst.series.empty() ? 0 : (inst.series.size() - 1);
|
||||
std::size_t label_bytes = 0;
|
||||
for (std::size_t i = 0; i < inst.spec.label_keys.size(); ++i) {
|
||||
label_bytes += inst.spec.label_keys[i].size() + canonical.values[i].size();
|
||||
}
|
||||
const std::size_t series_cost =
|
||||
kPerSeriesOverheadBytes + canonical.key.size() + label_bytes +
|
||||
(inst.spec.bucket_bounds.size() + 1) * sizeof(std::uint64_t);
|
||||
|
||||
const std::size_t used_bytes = estimated_bytes.load(std::memory_order_relaxed);
|
||||
const std::size_t used_series = total_series.load(std::memory_order_relaxed);
|
||||
|
||||
if (current_normal >= limits.max_series_per_instrument ||
|
||||
used_series >= limits.max_total_series ||
|
||||
series_cost > limits.max_storage_bytes - std::min(used_bytes, limits.max_storage_bytes)) {
|
||||
inst.overflow_seen.store(true, std::memory_order_release);
|
||||
inst.dropped_series.fetch_add(1, std::memory_order_relaxed);
|
||||
inst.overflow_events.fetch_add(1, std::memory_order_relaxed);
|
||||
dropped_series.fetch_add(1, std::memory_order_relaxed);
|
||||
overflow_events.fetch_add(1, std::memory_order_relaxed);
|
||||
return 0; // pre-registered __overflow__ slot
|
||||
}
|
||||
|
||||
const std::size_t new_id = inst.series.size();
|
||||
SeriesMeta meta;
|
||||
meta.series_id = new_id;
|
||||
meta.is_overflow = false;
|
||||
meta.byte_cost = series_cost;
|
||||
meta.labels.reserve(inst.spec.label_keys.size());
|
||||
for (std::size_t i = 0; i < inst.spec.label_keys.size(); ++i) {
|
||||
meta.labels.emplace_back(inst.spec.label_keys[i], canonical.values[i]);
|
||||
}
|
||||
inst.key_to_series.emplace(canonical.key, new_id);
|
||||
inst.series.push_back(std::move(meta));
|
||||
total_series.fetch_add(1, std::memory_order_relaxed);
|
||||
estimated_bytes.fetch_add(series_cost, std::memory_order_relaxed);
|
||||
return new_id;
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void mutate_slot(std::size_t inst_idx,
|
||||
std::size_t series_id,
|
||||
std::size_t hist_bucket_count,
|
||||
Fn&& fn)
|
||||
{
|
||||
auto shard = acquire_shard();
|
||||
std::lock_guard lock{shard->mutex};
|
||||
if (shard->data.size() <= inst_idx) {
|
||||
shard->data.resize(inst_idx + 1);
|
||||
}
|
||||
auto& inst_vec = shard->data[inst_idx];
|
||||
if (inst_vec.size() <= series_id) {
|
||||
inst_vec.resize(series_id + 1);
|
||||
}
|
||||
auto& slot = inst_vec[series_id];
|
||||
if (hist_bucket_count > 0 && slot.hist_buckets.size() != hist_bucket_count) {
|
||||
slot.hist_buckets.assign(hist_bucket_count, 0);
|
||||
}
|
||||
fn(slot);
|
||||
}
|
||||
|
||||
Void::Result::Result<void> add_counter_impl(
|
||||
std::size_t inst_idx,
|
||||
std::uint64_t delta,
|
||||
std::span<const AttributeView> attributes)
|
||||
{
|
||||
std::shared_lock dir_lock{dir_mutex};
|
||||
if (inst_idx >= instruments.size()) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Invalid InstrumentHandle index"));
|
||||
}
|
||||
const auto& inst = *instruments[inst_idx];
|
||||
if (inst.spec.kind != MetricKind::counter) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::schema_conflict,
|
||||
"Instrument is not a counter"));
|
||||
}
|
||||
auto canonical = build_canonical_labels(inst, attributes);
|
||||
if (!canonical) {
|
||||
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
|
||||
return Void::Result::fail(std::move(canonical).error());
|
||||
}
|
||||
dir_lock.unlock();
|
||||
|
||||
const auto sid = resolve_or_create_series(inst_idx, *canonical);
|
||||
mutate_slot(inst_idx, sid, 0, [delta](SeriesAccumulator& slot) {
|
||||
slot.counter_value = saturating_add_u64(
|
||||
slot.counter_value, delta, slot.counter_saturated);
|
||||
});
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> set_gauge_impl(
|
||||
std::size_t inst_idx,
|
||||
double value,
|
||||
std::span<const AttributeView> attributes)
|
||||
{
|
||||
if (!std::isfinite(value)) {
|
||||
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Gauge value must be finite"));
|
||||
}
|
||||
std::shared_lock dir_lock{dir_mutex};
|
||||
if (inst_idx >= instruments.size()) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Invalid InstrumentHandle index"));
|
||||
}
|
||||
const auto& inst = *instruments[inst_idx];
|
||||
if (inst.spec.kind != MetricKind::gauge) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::schema_conflict,
|
||||
"Instrument is not a gauge"));
|
||||
}
|
||||
auto canonical = build_canonical_labels(inst, attributes);
|
||||
if (!canonical) {
|
||||
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
|
||||
return Void::Result::fail(std::move(canonical).error());
|
||||
}
|
||||
dir_lock.unlock();
|
||||
|
||||
const auto sid = resolve_or_create_series(inst_idx, *canonical);
|
||||
const auto ts = clock->now();
|
||||
const auto seq = gauge_seq_gen.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
mutate_slot(inst_idx, sid, 0, [value, ts, seq](SeriesAccumulator& slot) {
|
||||
slot.gauge_value = value;
|
||||
slot.has_gauge_sample = true;
|
||||
slot.gauge_timestamp = ts;
|
||||
slot.gauge_seq = seq;
|
||||
});
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> observe_histogram_impl(
|
||||
std::size_t inst_idx,
|
||||
double value,
|
||||
std::span<const AttributeView> attributes)
|
||||
{
|
||||
if (!std::isfinite(value)) {
|
||||
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Histogram observation must be finite"));
|
||||
}
|
||||
std::shared_lock dir_lock{dir_mutex};
|
||||
if (inst_idx >= instruments.size()) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Invalid InstrumentHandle index"));
|
||||
}
|
||||
const auto& inst = *instruments[inst_idx];
|
||||
if (inst.spec.kind != MetricKind::histogram) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::schema_conflict,
|
||||
"Instrument is not a histogram"));
|
||||
}
|
||||
const auto bounds = inst.spec.bucket_bounds;
|
||||
auto canonical = build_canonical_labels(inst, attributes);
|
||||
if (!canonical) {
|
||||
rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
|
||||
return Void::Result::fail(std::move(canonical).error());
|
||||
}
|
||||
dir_lock.unlock();
|
||||
|
||||
const auto sid = resolve_or_create_series(inst_idx, *canonical);
|
||||
std::size_t bucket_idx = bounds.size();
|
||||
for (std::size_t i = 0; i < bounds.size(); ++i) {
|
||||
if (value <= bounds[i]) {
|
||||
bucket_idx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const std::size_t total_buckets = bounds.size() + 1;
|
||||
mutate_slot(inst_idx, sid, total_buckets, [value, bucket_idx](SeriesAccumulator& slot) {
|
||||
++slot.hist_buckets[bucket_idx];
|
||||
++slot.hist_count;
|
||||
slot.hist_sum += value;
|
||||
});
|
||||
return {};
|
||||
}
|
||||
|
||||
static void hook_record(void* state, const MetricPoint& pt) noexcept
|
||||
{
|
||||
if (state == nullptr) {
|
||||
return;
|
||||
}
|
||||
auto* self = static_cast<Impl*>(state);
|
||||
try {
|
||||
std::optional<std::size_t> idx;
|
||||
{
|
||||
std::shared_lock lock{self->dir_mutex};
|
||||
if (const auto it = self->name_to_index.find(std::string{pt.name});
|
||||
it != self->name_to_index.end()) {
|
||||
idx = it->second;
|
||||
}
|
||||
}
|
||||
if (!idx.has_value()) {
|
||||
self->unregistered_hook_points.fetch_add(1, std::memory_order_relaxed);
|
||||
return;
|
||||
}
|
||||
switch (pt.kind) {
|
||||
case MetricKind::counter: {
|
||||
const std::uint64_t delta = pt.integer_delta != 0
|
||||
? pt.integer_delta
|
||||
: (pt.value >= 0.0 && std::isfinite(pt.value)
|
||||
? static_cast<std::uint64_t>(pt.value)
|
||||
: 0ULL);
|
||||
(void)self->add_counter_impl(*idx, delta, pt.attributes);
|
||||
break;
|
||||
}
|
||||
case MetricKind::gauge:
|
||||
(void)self->set_gauge_impl(*idx, pt.value, pt.attributes);
|
||||
break;
|
||||
case MetricKind::histogram:
|
||||
(void)self->observe_histogram_impl(*idx, pt.value, pt.attributes);
|
||||
break;
|
||||
}
|
||||
} catch (...) {
|
||||
self->rejected_invalid_points.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
const std::uint64_t id;
|
||||
MetricsLimits limits;
|
||||
const Void::Time::MonotonicClock* clock;
|
||||
|
||||
mutable std::shared_mutex dir_mutex;
|
||||
std::vector<std::unique_ptr<InstrumentData>> instruments;
|
||||
std::unordered_map<std::string, std::size_t> name_to_index;
|
||||
|
||||
mutable std::mutex shards_mutex;
|
||||
std::vector<std::shared_ptr<Shard>> shards;
|
||||
std::shared_ptr<Shard> fallback_shard;
|
||||
|
||||
std::atomic<std::uint64_t> epoch{1};
|
||||
std::atomic<std::size_t> total_series{0};
|
||||
std::atomic<std::size_t> estimated_bytes{0};
|
||||
std::atomic<std::uint64_t> dropped_series{0};
|
||||
std::atomic<std::uint64_t> overflow_events{0};
|
||||
std::atomic<std::uint64_t> rejected_invalid_points{0};
|
||||
std::atomic<std::uint64_t> shared_shard_fallbacks{0};
|
||||
std::atomic<std::uint64_t> unregistered_hook_points{0};
|
||||
std::atomic<std::uint64_t> gauge_seq_gen{0};
|
||||
};
|
||||
|
||||
MetricRegistry::MetricRegistry(std::shared_ptr<Impl> impl) noexcept
|
||||
: impl_(std::move(impl))
|
||||
{
|
||||
}
|
||||
|
||||
MetricRegistry::~MetricRegistry() = default;
|
||||
|
||||
Void::Result::Result<MetricRegistry> MetricRegistry::create(
|
||||
MetricsLimits limits,
|
||||
const Void::Time::MonotonicClock& clock)
|
||||
{
|
||||
if (auto v = limits.validate(); !v) {
|
||||
return Void::Result::fail(std::move(v).error());
|
||||
}
|
||||
auto impl = std::make_shared<Impl>(limits, &clock);
|
||||
return MetricRegistry{std::move(impl)};
|
||||
}
|
||||
|
||||
Void::Result::Result<InstrumentHandle>
|
||||
MetricRegistry::register_instrument(InstrumentSpec spec)
|
||||
{
|
||||
if (!impl_) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::closed,
|
||||
"MetricRegistry is moved-from"));
|
||||
}
|
||||
if (spec.name.empty() || spec.name.size() > impl_->limits.max_key_bytes ||
|
||||
!valid_label_name(spec.name)) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Invalid instrument name"));
|
||||
}
|
||||
if (spec.unit.size() > impl_->limits.max_key_bytes || !valid_token(spec.unit)) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Invalid instrument unit"));
|
||||
}
|
||||
if (spec.label_keys.size() > impl_->limits.max_labels_per_point) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Instrument label key count exceeds max_labels_per_point"));
|
||||
}
|
||||
for (std::size_t i = 0; i < spec.label_keys.size(); ++i) {
|
||||
const auto& k = spec.label_keys[i];
|
||||
if (k.size() > impl_->limits.max_key_bytes || !valid_label_name(k)) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Invalid instrument label key"));
|
||||
}
|
||||
for (std::size_t j = 0; j < i; ++j) {
|
||||
if (spec.label_keys[j] == k) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Duplicate label key in InstrumentSpec"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (spec.kind == MetricKind::histogram) {
|
||||
if (spec.bucket_bounds.empty()) {
|
||||
spec.bucket_bounds = default_duration_buckets_seconds();
|
||||
} else {
|
||||
for (std::size_t i = 0; i < spec.bucket_bounds.size(); ++i) {
|
||||
if (!std::isfinite(spec.bucket_bounds[i]) ||
|
||||
(i > 0 && spec.bucket_bounds[i] <= spec.bucket_bounds[i - 1])) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Histogram bucket bounds must be strictly increasing finite numbers"));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (!spec.bucket_bounds.empty()) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"Only histogram instruments accept bucket bounds"));
|
||||
}
|
||||
|
||||
std::unique_lock lock{impl_->dir_mutex};
|
||||
if (const auto it = impl_->name_to_index.find(spec.name);
|
||||
it != impl_->name_to_index.end()) {
|
||||
const auto idx = it->second;
|
||||
const auto& existing = impl_->instruments[idx]->spec;
|
||||
if (existing.kind != spec.kind || existing.unit != spec.unit ||
|
||||
existing.label_keys != spec.label_keys ||
|
||||
existing.bucket_bounds != spec.bucket_bounds) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::schema_conflict,
|
||||
"Instrument already registered with conflicting schema: " + spec.name));
|
||||
}
|
||||
return InstrumentHandle{idx, impl_->id};
|
||||
}
|
||||
|
||||
if (impl_->instruments.size() >= impl_->limits.max_instruments) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::capacity_exceeded,
|
||||
"MetricRegistry max_instruments reached"));
|
||||
}
|
||||
|
||||
const std::size_t meta_cost =
|
||||
kPerSeriesOverheadBytes + spec.name.size() + spec.unit.size() +
|
||||
(spec.bucket_bounds.size() + 1) * sizeof(double);
|
||||
const std::size_t used_bytes = impl_->estimated_bytes.load(std::memory_order_relaxed);
|
||||
if (meta_cost > impl_->limits.max_storage_bytes - std::min(used_bytes, impl_->limits.max_storage_bytes)) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::capacity_exceeded,
|
||||
"MetricRegistry max_storage_bytes exceeded"));
|
||||
}
|
||||
|
||||
auto inst = std::make_unique<Impl::InstrumentData>();
|
||||
inst->spec = std::move(spec);
|
||||
|
||||
// Pre-register dedicated __overflow__ slot at index 0.
|
||||
Impl::SeriesMeta overflow_meta;
|
||||
overflow_meta.series_id = 0;
|
||||
overflow_meta.is_overflow = true;
|
||||
overflow_meta.labels = {{"__overflow__", "true"}};
|
||||
overflow_meta.byte_cost = meta_cost;
|
||||
inst->series.push_back(std::move(overflow_meta));
|
||||
|
||||
const std::size_t idx = impl_->instruments.size();
|
||||
impl_->name_to_index.emplace(inst->spec.name, idx);
|
||||
impl_->instruments.push_back(std::move(inst));
|
||||
impl_->estimated_bytes.fetch_add(meta_cost, std::memory_order_relaxed);
|
||||
return InstrumentHandle{idx, impl_->id};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> MetricRegistry::add_counter(
|
||||
InstrumentHandle handle,
|
||||
std::uint64_t delta,
|
||||
std::span<const AttributeView> attributes)
|
||||
{
|
||||
if (!impl_ || handle.registry_id != impl_->id) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"InstrumentHandle does not belong to this MetricRegistry"));
|
||||
}
|
||||
return impl_->add_counter_impl(handle.index, delta, attributes);
|
||||
}
|
||||
|
||||
Void::Result::Result<void> MetricRegistry::set_gauge(
|
||||
InstrumentHandle handle,
|
||||
double value,
|
||||
std::span<const AttributeView> attributes)
|
||||
{
|
||||
if (!impl_ || handle.registry_id != impl_->id) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"InstrumentHandle does not belong to this MetricRegistry"));
|
||||
}
|
||||
return impl_->set_gauge_impl(handle.index, value, attributes);
|
||||
}
|
||||
|
||||
Void::Result::Result<void> MetricRegistry::observe_histogram(
|
||||
InstrumentHandle handle,
|
||||
double value,
|
||||
std::span<const AttributeView> attributes)
|
||||
{
|
||||
if (!impl_ || handle.registry_id != impl_->id) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"InstrumentHandle does not belong to this MetricRegistry"));
|
||||
}
|
||||
return impl_->observe_histogram_impl(handle.index, value, attributes);
|
||||
}
|
||||
|
||||
MetricsSnapshot MetricRegistry::snapshot() const
|
||||
{
|
||||
MetricsSnapshot snap;
|
||||
if (!impl_) {
|
||||
return snap;
|
||||
}
|
||||
|
||||
std::shared_lock dir_lock{impl_->dir_mutex};
|
||||
std::vector<std::shared_ptr<Impl::Shard>> all_shards;
|
||||
{
|
||||
std::lock_guard slock{impl_->shards_mutex};
|
||||
all_shards = impl_->shards;
|
||||
all_shards.push_back(impl_->fallback_shard);
|
||||
}
|
||||
|
||||
snap.epoch = impl_->epoch.load(std::memory_order_acquire);
|
||||
snap.dropped_series = impl_->dropped_series.load(std::memory_order_relaxed);
|
||||
snap.overflow_events = impl_->overflow_events.load(std::memory_order_relaxed);
|
||||
snap.rejected_invalid_points =
|
||||
impl_->rejected_invalid_points.load(std::memory_order_relaxed);
|
||||
snap.shared_shard_fallbacks =
|
||||
impl_->shared_shard_fallbacks.load(std::memory_order_relaxed);
|
||||
snap.unregistered_hook_points =
|
||||
impl_->unregistered_hook_points.load(std::memory_order_relaxed);
|
||||
snap.estimated_bytes = impl_->estimated_bytes.load(std::memory_order_relaxed);
|
||||
snap.shard_count = all_shards.size() - 1;
|
||||
|
||||
snap.instruments.resize(impl_->instruments.size());
|
||||
std::vector<std::vector<std::uint64_t>> gauge_seqs(impl_->instruments.size());
|
||||
for (std::size_t i = 0; i < impl_->instruments.size(); ++i) {
|
||||
const auto& inst = *impl_->instruments[i];
|
||||
auto& out_inst = snap.instruments[i];
|
||||
out_inst.spec = inst.spec;
|
||||
out_inst.dropped_series = inst.dropped_series.load(std::memory_order_relaxed);
|
||||
out_inst.overflow_events = inst.overflow_events.load(std::memory_order_relaxed);
|
||||
out_inst.series.resize(inst.series.size());
|
||||
gauge_seqs[i].assign(inst.series.size(), 0);
|
||||
for (std::size_t s = 0; s < inst.series.size(); ++s) {
|
||||
out_inst.series[s].labels = inst.series[s].labels;
|
||||
out_inst.series[s].is_overflow = inst.series[s].is_overflow;
|
||||
if (inst.spec.kind == MetricKind::histogram) {
|
||||
out_inst.series[s].histogram.bounds = inst.spec.bucket_bounds;
|
||||
out_inst.series[s].histogram.bucket_counts.assign(
|
||||
inst.spec.bucket_bounds.size() + 1, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& shard : all_shards) {
|
||||
std::lock_guard lock{shard->mutex};
|
||||
const std::size_t max_inst =
|
||||
std::min(shard->data.size(), impl_->instruments.size());
|
||||
for (std::size_t i = 0; i < max_inst; ++i) {
|
||||
const auto& kind = impl_->instruments[i]->spec.kind;
|
||||
const auto& src_series = shard->data[i];
|
||||
const std::size_t max_ser =
|
||||
std::min(src_series.size(), snap.instruments[i].series.size());
|
||||
for (std::size_t s = 0; s < max_ser; ++s) {
|
||||
const auto& src = src_series[s];
|
||||
auto& dst = snap.instruments[i].series[s];
|
||||
switch (kind) {
|
||||
case MetricKind::counter:
|
||||
dst.counter_value = saturating_add_u64(
|
||||
dst.counter_value, src.counter_value, dst.counter_saturated);
|
||||
dst.counter_saturated = dst.counter_saturated || src.counter_saturated;
|
||||
break;
|
||||
case MetricKind::gauge:
|
||||
if (src.has_gauge_sample && src.gauge_seq >= gauge_seqs[i][s]) {
|
||||
gauge_seqs[i][s] = src.gauge_seq;
|
||||
dst.gauge_value = src.gauge_value;
|
||||
dst.gauge_timestamp = src.gauge_timestamp;
|
||||
dst.has_gauge_sample = true;
|
||||
}
|
||||
break;
|
||||
case MetricKind::histogram:
|
||||
dst.histogram.count += src.hist_count;
|
||||
dst.histogram.sum += src.hist_sum;
|
||||
for (std::size_t b = 0;
|
||||
b < std::min(src.hist_buckets.size(),
|
||||
dst.histogram.bucket_counts.size());
|
||||
++b) {
|
||||
dst.histogram.bucket_counts[b] += src.hist_buckets[b];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Omit the pre-registered __overflow__ entry when no overflow occurred.
|
||||
for (std::size_t i = 0; i < impl_->instruments.size(); ++i) {
|
||||
auto& out_inst = snap.instruments[i];
|
||||
if (!impl_->instruments[i]->overflow_seen.load(std::memory_order_acquire) &&
|
||||
!out_inst.series.empty() && out_inst.series.front().is_overflow) {
|
||||
out_inst.series.erase(out_inst.series.begin());
|
||||
}
|
||||
}
|
||||
return snap;
|
||||
}
|
||||
|
||||
void MetricRegistry::reset_epoch()
|
||||
{
|
||||
if (!impl_) {
|
||||
return;
|
||||
}
|
||||
std::unique_lock dir_lock{impl_->dir_mutex};
|
||||
std::vector<std::shared_ptr<Impl::Shard>> all_shards;
|
||||
{
|
||||
std::lock_guard slock{impl_->shards_mutex};
|
||||
all_shards = impl_->shards;
|
||||
all_shards.push_back(impl_->fallback_shard);
|
||||
}
|
||||
for (const auto& shard : all_shards) {
|
||||
std::lock_guard lock{shard->mutex};
|
||||
for (auto& inst_vec : shard->data) {
|
||||
for (auto& slot : inst_vec) {
|
||||
slot.counter_value = 0;
|
||||
slot.counter_saturated = false;
|
||||
slot.gauge_value = 0.0;
|
||||
slot.has_gauge_sample = false;
|
||||
slot.gauge_seq = 0;
|
||||
std::fill(slot.hist_buckets.begin(), slot.hist_buckets.end(), 0);
|
||||
slot.hist_count = 0;
|
||||
slot.hist_sum = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto& inst : impl_->instruments) {
|
||||
inst->overflow_seen.store(false, std::memory_order_release);
|
||||
inst->dropped_series.store(0, std::memory_order_relaxed);
|
||||
inst->overflow_events.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
impl_->dropped_series.store(0, std::memory_order_relaxed);
|
||||
impl_->overflow_events.store(0, std::memory_order_relaxed);
|
||||
impl_->epoch.fetch_add(1, std::memory_order_release);
|
||||
}
|
||||
|
||||
ObservationHooks MetricRegistry::make_hooks() const noexcept
|
||||
{
|
||||
if (!impl_) {
|
||||
return kNullObservationHooks;
|
||||
}
|
||||
return ObservationHooks{
|
||||
impl_.get(),
|
||||
&Impl::hook_record,
|
||||
nullptr};
|
||||
}
|
||||
|
||||
std::shared_ptr<const void> MetricRegistry::keepalive() const noexcept
|
||||
{
|
||||
return impl_;
|
||||
}
|
||||
|
||||
const MetricsLimits& MetricRegistry::limits() const noexcept
|
||||
{
|
||||
static const MetricsLimits kDefault{};
|
||||
return impl_ ? impl_->limits : kDefault;
|
||||
}
|
||||
|
||||
} // namespace Void::Observability
|
||||
@@ -0,0 +1,700 @@
|
||||
#include <Void/Observability/Tracing.hpp>
|
||||
#include <Void/Core/Hash.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <deque>
|
||||
#include <format>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Observability
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
constexpr std::size_t kBaseSpanBytes = 192;
|
||||
|
||||
[[nodiscard]] bool is_valid_text(std::string_view sv) noexcept
|
||||
{
|
||||
for (const unsigned char ch : sv) {
|
||||
if (ch < 0x20 || ch == 0x7F) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string truncate_with_marker(std::string_view sv,
|
||||
std::size_t max_bytes,
|
||||
bool& truncated)
|
||||
{
|
||||
if (sv.size() <= max_bytes) {
|
||||
return std::string{sv};
|
||||
}
|
||||
truncated = true;
|
||||
constexpr std::string_view kMarker = "...[truncated]";
|
||||
if (max_bytes <= kMarker.size()) {
|
||||
return std::string{sv.substr(0, max_bytes)};
|
||||
}
|
||||
std::string out{sv.substr(0, max_bytes - kMarker.size())};
|
||||
out += kMarker;
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view status_str(SpanStatus s) noexcept
|
||||
{
|
||||
switch (s) {
|
||||
case SpanStatus::unset: return "unset";
|
||||
case SpanStatus::ok: return "ok";
|
||||
case SpanStatus::error: return "error";
|
||||
case SpanStatus::abandoned: return "abandoned";
|
||||
}
|
||||
return "unset";
|
||||
}
|
||||
|
||||
inline thread_local std::vector<const void*> t_active_exporters;
|
||||
|
||||
struct ExporterRecursionGuard {
|
||||
const void* ptr{nullptr};
|
||||
bool reentered{false};
|
||||
|
||||
explicit ExporterRecursionGuard(const void* p) : ptr(p)
|
||||
{
|
||||
for (const auto* active : t_active_exporters) {
|
||||
if (active == ptr) {
|
||||
reentered = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
t_active_exporters.push_back(ptr);
|
||||
}
|
||||
|
||||
~ExporterRecursionGuard() noexcept
|
||||
{
|
||||
if (!reentered && !t_active_exporters.empty()) {
|
||||
t_active_exporters.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
ExporterRecursionGuard(const ExporterRecursionGuard&) = delete;
|
||||
ExporterRecursionGuard& operator=(const ExporterRecursionGuard&) = delete;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<void> TracingLimits::validate() const
|
||||
{
|
||||
if (max_active_spans == 0 || max_active_bytes == 0 ||
|
||||
max_completed_spans == 0 || max_completed_bytes == 0 ||
|
||||
max_attributes_per_span == 0 || max_events_per_span == 0 ||
|
||||
max_bytes_per_span == 0 || max_key_bytes == 0 ||
|
||||
max_value_bytes == 0 || max_export_batch_spans == 0 ||
|
||||
max_export_batch_bytes == 0 || root_sample_denominator == 0 ||
|
||||
export_retry_budget.count() < 0) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::invalid_argument,
|
||||
"TracingLimits values must be positive"));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
CallbackSpanExporter::CallbackSpanExporter(Callback callback)
|
||||
: callback_(std::move(callback))
|
||||
{
|
||||
}
|
||||
|
||||
Void::Result::Result<void> CallbackSpanExporter::export_spans(
|
||||
std::span<const CompletedSpan> spans)
|
||||
{
|
||||
ExporterRecursionGuard guard{this};
|
||||
if (guard.reentered) {
|
||||
reentrant_drops_.fetch_add(1, std::memory_order_relaxed);
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::would_deadlock,
|
||||
"Reentrant span export suppressed"));
|
||||
}
|
||||
if (!callback_) {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
return callback_(spans);
|
||||
} catch (const std::exception& e) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::quarantined,
|
||||
std::string{"Span exporter callback threw: "} + e.what()));
|
||||
} catch (...) {
|
||||
return Void::Result::fail(make_observability_error(
|
||||
ObservabilityErrorCode::quarantined,
|
||||
"Span exporter callback threw unknown exception"));
|
||||
}
|
||||
}
|
||||
|
||||
TextSnapshotExporter::TextSnapshotExporter(std::size_t max_output_bytes)
|
||||
: max_output_bytes_(max_output_bytes)
|
||||
{
|
||||
}
|
||||
|
||||
Void::Result::Result<void> TextSnapshotExporter::export_spans(
|
||||
std::span<const CompletedSpan> spans)
|
||||
{
|
||||
const auto rendered = render_spans(spans, max_output_bytes_);
|
||||
std::lock_guard lock{mutex_};
|
||||
if (buffer_.size() < max_output_bytes_) {
|
||||
const std::size_t rem = max_output_bytes_ - buffer_.size();
|
||||
if (rendered.size() <= rem) {
|
||||
buffer_ += rendered;
|
||||
} else {
|
||||
buffer_.append(rendered.data(), rem);
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::string TextSnapshotExporter::render_metrics(
|
||||
const MetricsSnapshot& metrics,
|
||||
std::size_t max_output_bytes)
|
||||
{
|
||||
std::string out;
|
||||
out += std::format("epoch={} instruments={} dropped_series={} overflow_events={}\n",
|
||||
metrics.epoch,
|
||||
metrics.instruments.size(),
|
||||
metrics.dropped_series,
|
||||
metrics.overflow_events);
|
||||
for (const auto& inst : metrics.instruments) {
|
||||
for (const auto& ser : inst.series) {
|
||||
std::string line = inst.spec.name;
|
||||
line += '{';
|
||||
for (std::size_t i = 0; i < ser.labels.size(); ++i) {
|
||||
if (i > 0) {
|
||||
line += ',';
|
||||
}
|
||||
line += ser.labels[i].first;
|
||||
line += '=';
|
||||
line += ser.labels[i].second;
|
||||
}
|
||||
line += '}';
|
||||
switch (inst.spec.kind) {
|
||||
case MetricKind::counter:
|
||||
line += std::format(" {}\n", ser.counter_value);
|
||||
break;
|
||||
case MetricKind::gauge:
|
||||
line += std::format(" {}\n", ser.gauge_value);
|
||||
break;
|
||||
case MetricKind::histogram:
|
||||
line += std::format(" count={} sum={}\n",
|
||||
ser.histogram.count,
|
||||
ser.histogram.sum);
|
||||
break;
|
||||
}
|
||||
if (out.size() + line.size() > max_output_bytes) {
|
||||
return out;
|
||||
}
|
||||
out += line;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string TextSnapshotExporter::render_spans(
|
||||
std::span<const CompletedSpan> spans,
|
||||
std::size_t max_output_bytes)
|
||||
{
|
||||
std::string out;
|
||||
for (const auto& sp : spans) {
|
||||
const auto dur_us =
|
||||
std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
sp.end_time >= sp.start_time ? (sp.end_time - sp.start_time)
|
||||
: std::chrono::nanoseconds{0})
|
||||
.count();
|
||||
std::string line = std::format(
|
||||
"span trace={} span={} name={} status={} duration_us={} attrs={} events={} truncated={}\n",
|
||||
sp.context.trace_id.to_hex(),
|
||||
sp.context.span_id.to_hex(),
|
||||
sp.name,
|
||||
status_str(sp.status),
|
||||
dur_us,
|
||||
sp.attributes.size(),
|
||||
sp.events.size(),
|
||||
sp.truncated ? 1 : 0);
|
||||
if (out.size() + line.size() > max_output_bytes) {
|
||||
break;
|
||||
}
|
||||
out += line;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string TextSnapshotExporter::text() const
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
return buffer_;
|
||||
}
|
||||
|
||||
void TextSnapshotExporter::clear()
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
buffer_.clear();
|
||||
}
|
||||
|
||||
struct Tracer::Impl {
|
||||
Impl(TracingLimits lim,
|
||||
std::shared_ptr<SpanExporter> exp,
|
||||
const Void::Time::MonotonicClock* clk,
|
||||
const Void::Time::CivilClock* civil)
|
||||
: limits(lim)
|
||||
, exporter(std::move(exp))
|
||||
, clock(clk != nullptr ? clk : &Void::Time::SystemMonotonicClock::instance())
|
||||
, civil_clock(civil != nullptr ? civil : &Void::Time::SystemCivilClock::instance())
|
||||
{
|
||||
}
|
||||
|
||||
void complete_span(CompletedSpan span, std::size_t reserved_active_bytes) noexcept
|
||||
{
|
||||
std::lock_guard lock{mutex};
|
||||
if (active_spans > 0) {
|
||||
--active_spans;
|
||||
}
|
||||
active_bytes =
|
||||
active_bytes >= reserved_active_bytes
|
||||
? (active_bytes - reserved_active_bytes)
|
||||
: 0;
|
||||
|
||||
if (span.status == SpanStatus::abandoned) {
|
||||
++abandoned_spans;
|
||||
}
|
||||
|
||||
const std::size_t budget_used = completed_bytes + in_flight_export_bytes;
|
||||
if (completed.size() >= limits.max_completed_spans ||
|
||||
span.estimated_bytes >
|
||||
limits.max_completed_bytes -
|
||||
std::min(budget_used, limits.max_completed_bytes)) {
|
||||
++dropped_completed_spans;
|
||||
return;
|
||||
}
|
||||
completed_bytes += span.estimated_bytes;
|
||||
completed.push_back(std::move(span));
|
||||
}
|
||||
|
||||
TracingLimits limits;
|
||||
std::shared_ptr<SpanExporter> exporter;
|
||||
const Void::Time::MonotonicClock* clock;
|
||||
const Void::Time::CivilClock* civil_clock;
|
||||
|
||||
mutable std::mutex mutex;
|
||||
std::size_t active_spans{0};
|
||||
std::size_t active_bytes{0};
|
||||
std::deque<CompletedSpan> completed{};
|
||||
std::size_t completed_bytes{0};
|
||||
std::size_t in_flight_export_bytes{0};
|
||||
bool closed{false};
|
||||
|
||||
std::uint64_t dropped_active_spans{0};
|
||||
std::uint64_t dropped_completed_spans{0};
|
||||
std::uint64_t duplicate_ends{0};
|
||||
std::uint64_t abandoned_spans{0};
|
||||
std::uint64_t exported_spans{0};
|
||||
std::uint64_t failed_exports{0};
|
||||
std::uint64_t reentrant_export_drops{0};
|
||||
};
|
||||
|
||||
struct Span::State {
|
||||
std::shared_ptr<Tracer::Impl> tracer;
|
||||
std::mutex mutex;
|
||||
CompletedSpan data{};
|
||||
std::size_t reserved_bytes{0};
|
||||
std::atomic<bool> ended{false};
|
||||
};
|
||||
|
||||
Span::Span(ContextSnapshot context, std::shared_ptr<State> state) noexcept
|
||||
: context_(std::move(context))
|
||||
, state_(std::move(state))
|
||||
{
|
||||
}
|
||||
|
||||
Span::~Span() noexcept
|
||||
{
|
||||
if (state_ && !ended_) {
|
||||
end(SpanStatus::abandoned);
|
||||
}
|
||||
}
|
||||
|
||||
Span::Span(Span&& other) noexcept
|
||||
: context_(std::move(other.context_))
|
||||
, state_(std::move(other.state_))
|
||||
, ended_(std::exchange(other.ended_, true))
|
||||
{
|
||||
}
|
||||
|
||||
Span& Span::operator=(Span&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
if (state_ && !ended_) {
|
||||
end(SpanStatus::abandoned);
|
||||
}
|
||||
context_ = std::move(other.context_);
|
||||
state_ = std::move(other.state_);
|
||||
ended_ = std::exchange(other.ended_, true);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Span::set_attribute(std::string_view key, std::string_view value)
|
||||
{
|
||||
if (!state_ || ended_ || key.empty() || !is_valid_text(key)) {
|
||||
return;
|
||||
}
|
||||
const auto& lim = state_->tracer->limits;
|
||||
std::lock_guard lock{state_->mutex};
|
||||
if (state_->ended.load(std::memory_order_acquire) ||
|
||||
state_->data.attributes.size() >= lim.max_attributes_per_span ||
|
||||
key.size() > lim.max_key_bytes) {
|
||||
return;
|
||||
}
|
||||
bool trunc = false;
|
||||
auto val_str = truncate_with_marker(value, lim.max_value_bytes, trunc);
|
||||
const std::size_t delta = key.size() + val_str.size();
|
||||
if (delta > lim.max_bytes_per_span -
|
||||
std::min(state_->data.estimated_bytes, lim.max_bytes_per_span)) {
|
||||
state_->data.truncated = true;
|
||||
return;
|
||||
}
|
||||
if (trunc) {
|
||||
state_->data.truncated = true;
|
||||
}
|
||||
state_->data.estimated_bytes += delta;
|
||||
state_->data.attributes.emplace_back(std::string{key}, std::move(val_str));
|
||||
}
|
||||
|
||||
void Span::add_event(std::string_view name)
|
||||
{
|
||||
if (!state_ || ended_ || name.empty() || !is_valid_text(name)) {
|
||||
return;
|
||||
}
|
||||
const auto& lim = state_->tracer->limits;
|
||||
std::lock_guard lock{state_->mutex};
|
||||
if (state_->ended.load(std::memory_order_acquire) ||
|
||||
state_->data.events.size() >= lim.max_events_per_span) {
|
||||
return;
|
||||
}
|
||||
bool trunc = false;
|
||||
auto evt_name = truncate_with_marker(name, lim.max_key_bytes, trunc);
|
||||
const std::size_t delta = evt_name.size() + sizeof(SpanEvent);
|
||||
if (delta > lim.max_bytes_per_span -
|
||||
std::min(state_->data.estimated_bytes, lim.max_bytes_per_span)) {
|
||||
state_->data.truncated = true;
|
||||
return;
|
||||
}
|
||||
if (trunc) {
|
||||
state_->data.truncated = true;
|
||||
}
|
||||
state_->data.estimated_bytes += delta;
|
||||
state_->data.events.push_back(
|
||||
SpanEvent{std::move(evt_name), state_->tracer->clock->now()});
|
||||
}
|
||||
|
||||
void Span::end(SpanStatus status) noexcept
|
||||
{
|
||||
if (!state_) {
|
||||
return;
|
||||
}
|
||||
bool expected = false;
|
||||
if (!state_->ended.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
|
||||
ended_ = true;
|
||||
std::lock_guard lock{state_->tracer->mutex};
|
||||
++state_->tracer->duplicate_ends;
|
||||
return;
|
||||
}
|
||||
ended_ = true;
|
||||
CompletedSpan finalized;
|
||||
std::size_t reserved = 0;
|
||||
{
|
||||
std::lock_guard lock{state_->mutex};
|
||||
state_->data.end_time = state_->tracer->clock->now();
|
||||
state_->data.status = status;
|
||||
finalized = std::move(state_->data);
|
||||
reserved = state_->reserved_bytes;
|
||||
}
|
||||
state_->tracer->complete_span(std::move(finalized), reserved);
|
||||
}
|
||||
|
||||
Tracer::Tracer(std::shared_ptr<Impl> impl) noexcept
|
||||
: impl_(std::move(impl))
|
||||
{
|
||||
}
|
||||
|
||||
Tracer::~Tracer() = default;
|
||||
|
||||
Void::Result::Result<Tracer> Tracer::create(
|
||||
TracingLimits limits,
|
||||
std::shared_ptr<SpanExporter> exporter,
|
||||
const Void::Time::MonotonicClock& clock,
|
||||
const Void::Time::CivilClock& civil_clock)
|
||||
{
|
||||
if (auto v = limits.validate(); !v) {
|
||||
return Void::Result::fail(std::move(v).error());
|
||||
}
|
||||
return Tracer{
|
||||
std::make_shared<Impl>(limits, std::move(exporter), &clock, &civil_clock)};
|
||||
}
|
||||
|
||||
Span Tracer::start_span(const ContextSnapshot& parent, SpanSpec spec)
|
||||
{
|
||||
if (!impl_) {
|
||||
return Span{};
|
||||
}
|
||||
|
||||
TraceId tid{};
|
||||
std::optional<SpanId> parent_sid;
|
||||
bool sampled = false;
|
||||
if (const auto& ptrace = parent.trace(); ptrace.has_value() && ptrace->valid()) {
|
||||
tid = ptrace->trace_id;
|
||||
parent_sid = ptrace->span_id;
|
||||
sampled = ptrace->sampled();
|
||||
} else {
|
||||
if (spec.explicit_root_trace_id.has_value() &&
|
||||
!spec.explicit_root_trace_id->is_zero()) {
|
||||
tid = *spec.explicit_root_trace_id;
|
||||
} else if (auto gen = TraceId::generate()) {
|
||||
tid = *gen;
|
||||
} else {
|
||||
tid = TraceId::generate_seeded(1);
|
||||
}
|
||||
const std::uint64_t h = Void::Hash::fnv1a64(
|
||||
std::span<const std::byte>{tid.bytes.data(), tid.bytes.size()});
|
||||
sampled = (h % impl_->limits.root_sample_denominator) == 0;
|
||||
}
|
||||
|
||||
SpanId sid{};
|
||||
if (auto gen_sid = SpanId::generate()) {
|
||||
sid = *gen_sid;
|
||||
} else {
|
||||
sid = SpanId::generate_seeded(1);
|
||||
}
|
||||
|
||||
const std::uint8_t flags = sampled ? kTraceFlagSampled : 0;
|
||||
ContextSnapshot child_ctx =
|
||||
parent.with_trace(TraceContext{tid, sid, flags});
|
||||
|
||||
if (!sampled) {
|
||||
return Span{std::move(child_ctx), nullptr};
|
||||
}
|
||||
|
||||
const auto& lim = impl_->limits;
|
||||
bool trunc = false;
|
||||
std::string clean_name =
|
||||
spec.name.empty() ? std::string{"unnamed"}
|
||||
: truncate_with_marker(spec.name, lim.max_key_bytes, trunc);
|
||||
|
||||
std::size_t initial_bytes = kBaseSpanBytes + clean_name.size();
|
||||
std::vector<std::pair<std::string, std::string>> clean_attrs;
|
||||
for (const auto& [k, v] : spec.attributes) {
|
||||
if (clean_attrs.size() >= lim.max_attributes_per_span) {
|
||||
trunc = true;
|
||||
break;
|
||||
}
|
||||
if (k.empty() || k.size() > lim.max_key_bytes || !is_valid_text(k)) {
|
||||
continue;
|
||||
}
|
||||
bool attr_trunc = false;
|
||||
auto val = truncate_with_marker(v, lim.max_value_bytes, attr_trunc);
|
||||
const std::size_t add = k.size() + val.size();
|
||||
if (initial_bytes + add > lim.max_bytes_per_span) {
|
||||
trunc = true;
|
||||
break;
|
||||
}
|
||||
if (attr_trunc) {
|
||||
trunc = true;
|
||||
}
|
||||
initial_bytes += add;
|
||||
clean_attrs.emplace_back(k, std::move(val));
|
||||
}
|
||||
|
||||
const std::size_t active_reserve = lim.max_bytes_per_span;
|
||||
{
|
||||
std::lock_guard lock{impl_->mutex};
|
||||
if (impl_->closed ||
|
||||
impl_->active_spans >= lim.max_active_spans ||
|
||||
active_reserve >
|
||||
lim.max_active_bytes -
|
||||
std::min(impl_->active_bytes, lim.max_active_bytes)) {
|
||||
++impl_->dropped_active_spans;
|
||||
child_ctx = parent.with_trace(TraceContext{tid, sid, 0});
|
||||
return Span{std::move(child_ctx), nullptr};
|
||||
}
|
||||
++impl_->active_spans;
|
||||
impl_->active_bytes += active_reserve;
|
||||
}
|
||||
|
||||
auto state = std::make_shared<Span::State>();
|
||||
state->tracer = impl_;
|
||||
state->reserved_bytes = active_reserve;
|
||||
state->data.context = TraceContext{tid, sid, flags};
|
||||
state->data.parent_span_id = parent_sid;
|
||||
state->data.name = std::move(clean_name);
|
||||
state->data.start_time = impl_->clock->now();
|
||||
state->data.end_time = state->data.start_time;
|
||||
state->data.civil_start_time = impl_->civil_clock->now();
|
||||
state->data.attributes = std::move(clean_attrs);
|
||||
state->data.truncated = trunc;
|
||||
state->data.estimated_bytes = initial_bytes;
|
||||
return Span{std::move(child_ctx), std::move(state)};
|
||||
}
|
||||
|
||||
ExportReport Tracer::flush(ExportOptions options)
|
||||
{
|
||||
ExportReport report;
|
||||
if (!impl_) {
|
||||
return report;
|
||||
}
|
||||
|
||||
std::size_t remaining_to_drain = 0;
|
||||
{
|
||||
std::lock_guard lock{impl_->mutex};
|
||||
report.duplicate_ends = impl_->duplicate_ends;
|
||||
report.dropped_spans =
|
||||
impl_->dropped_active_spans + impl_->dropped_completed_spans;
|
||||
remaining_to_drain = impl_->completed.size();
|
||||
}
|
||||
|
||||
while (remaining_to_drain > 0) {
|
||||
if (options.stop.stop_requested()) {
|
||||
report.cancelled = true;
|
||||
break;
|
||||
}
|
||||
if (options.deadline.has_value() && impl_->clock->now() >= *options.deadline) {
|
||||
report.timed_out = true;
|
||||
break;
|
||||
}
|
||||
|
||||
ExportBatch batch;
|
||||
{
|
||||
std::lock_guard lock{impl_->mutex};
|
||||
if (impl_->completed.empty()) {
|
||||
break;
|
||||
}
|
||||
const std::size_t cap_spans =
|
||||
std::min(remaining_to_drain, impl_->limits.max_export_batch_spans);
|
||||
while (!impl_->completed.empty() && batch.spans.size() < cap_spans) {
|
||||
const auto& front = impl_->completed.front();
|
||||
if (!batch.spans.empty() &&
|
||||
batch.estimated_bytes + front.estimated_bytes >
|
||||
impl_->limits.max_export_batch_bytes) {
|
||||
break;
|
||||
}
|
||||
batch.estimated_bytes += front.estimated_bytes;
|
||||
impl_->completed_bytes =
|
||||
impl_->completed_bytes >= front.estimated_bytes
|
||||
? (impl_->completed_bytes - front.estimated_bytes)
|
||||
: 0;
|
||||
batch.spans.push_back(std::move(impl_->completed.front()));
|
||||
impl_->completed.pop_front();
|
||||
--remaining_to_drain;
|
||||
}
|
||||
impl_->in_flight_export_bytes += batch.estimated_bytes;
|
||||
}
|
||||
|
||||
if (batch.spans.empty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
bool ok = true;
|
||||
if (impl_->exporter) {
|
||||
const auto retry_start = impl_->clock->now();
|
||||
ok = false;
|
||||
for (std::size_t attempt = 0;
|
||||
attempt <= impl_->limits.max_export_retries;
|
||||
++attempt) {
|
||||
if (options.stop.stop_requested()) {
|
||||
report.cancelled = true;
|
||||
break;
|
||||
}
|
||||
if (options.deadline.has_value() &&
|
||||
impl_->clock->now() >= *options.deadline) {
|
||||
report.timed_out = true;
|
||||
break;
|
||||
}
|
||||
if (attempt > 0) {
|
||||
if (impl_->clock->now() - retry_start >=
|
||||
impl_->limits.export_retry_budget) {
|
||||
report.timed_out = true;
|
||||
break;
|
||||
}
|
||||
++report.retries;
|
||||
}
|
||||
const auto res = impl_->exporter->export_spans(batch.spans);
|
||||
if (res.has_value()) {
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
if (res.error().code().value ==
|
||||
static_cast<std::int32_t>(ObservabilityErrorCode::would_deadlock)) {
|
||||
std::lock_guard lock{impl_->mutex};
|
||||
++impl_->reentrant_export_drops;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard lock{impl_->mutex};
|
||||
impl_->in_flight_export_bytes =
|
||||
impl_->in_flight_export_bytes >= batch.estimated_bytes
|
||||
? (impl_->in_flight_export_bytes - batch.estimated_bytes)
|
||||
: 0;
|
||||
if (ok) {
|
||||
impl_->exported_spans += batch.spans.size();
|
||||
report.exported_spans += batch.spans.size();
|
||||
} else {
|
||||
++impl_->failed_exports;
|
||||
report.failed_spans += batch.spans.size();
|
||||
}
|
||||
}
|
||||
|
||||
if (report.cancelled || report.timed_out) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
ExportReport Tracer::close(ExportOptions options)
|
||||
{
|
||||
if (!impl_) {
|
||||
return {};
|
||||
}
|
||||
{
|
||||
std::lock_guard lock{impl_->mutex};
|
||||
impl_->closed = true;
|
||||
}
|
||||
return flush(options);
|
||||
}
|
||||
|
||||
TracerStats Tracer::stats() const
|
||||
{
|
||||
TracerStats st;
|
||||
if (!impl_) {
|
||||
return st;
|
||||
}
|
||||
std::lock_guard lock{impl_->mutex};
|
||||
st.active_spans = impl_->active_spans;
|
||||
st.active_bytes = impl_->active_bytes;
|
||||
st.completed_spans = impl_->completed.size();
|
||||
st.completed_bytes = impl_->completed_bytes;
|
||||
st.in_flight_export_bytes = impl_->in_flight_export_bytes;
|
||||
st.dropped_active_spans = impl_->dropped_active_spans;
|
||||
st.dropped_completed_spans = impl_->dropped_completed_spans;
|
||||
st.duplicate_ends = impl_->duplicate_ends;
|
||||
st.abandoned_spans = impl_->abandoned_spans;
|
||||
st.exported_spans = impl_->exported_spans;
|
||||
st.failed_exports = impl_->failed_exports;
|
||||
st.reentrant_export_drops = impl_->reentrant_export_drops;
|
||||
st.closed = impl_->closed;
|
||||
return st;
|
||||
}
|
||||
|
||||
} // namespace Void::Observability
|
||||
@@ -0,0 +1,4 @@
|
||||
void_add_module(Observability
|
||||
INTERNAL_DEPS ObservabilityHooks Core Functional Time Memory
|
||||
EXCLUDE_HEADERS Void/Observability/Hooks.hpp
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(ObservabilityHooks
|
||||
EXTRA_HEADERS Void/Observability/Hooks.hpp
|
||||
)
|
||||
Reference in new issue
Block a user