#include #include #include #include #include #include #include #include #include #include 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 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 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 CallbackSpanExporter::export_spans( std::span 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 TextSnapshotExporter::export_spans( std::span 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 spans, std::size_t max_output_bytes) { std::string out; for (const auto& sp : spans) { const auto dur_us = std::chrono::duration_cast( 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 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 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 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; std::mutex mutex; CompletedSpan data{}; std::size_t reserved_bytes{0}; std::atomic ended{false}; }; Span::Span(ContextSnapshot context, std::shared_ptr 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) noexcept : impl_(std::move(impl)) { } Tracer::~Tracer() = default; Void::Result::Result Tracer::create( TracingLimits limits, std::shared_ptr 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(limits, std::move(exporter), &clock, &civil_clock)}; } Span Tracer::start_span(const ContextSnapshot& parent, SpanSpec spec) { if (!impl_) { return Span{}; } TraceId tid{}; std::optional 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{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> 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(); 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(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