#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Observability { enum class ObservabilityErrorCode : std::int32_t { invalid_argument = 1, invalid_traceparent = 2, schema_conflict = 3, capacity_exceeded = 4, cardinality_exceeded = 5, closed = 6, cancelled = 7, timeout = 8, unsupported_capability = 9, would_deadlock = 10, quarantined = 11 }; [[nodiscard]] inline Void::Result::Error make_observability_error(ObservabilityErrorCode code, std::string message = {}) { using Void::Result::Error; using Void::Result::ErrorCode; using Void::Result::ErrorKind; ErrorKind kind = ErrorKind::internal; switch (code) { case ObservabilityErrorCode::invalid_argument: case ObservabilityErrorCode::invalid_traceparent: kind = ErrorKind::invalid_argument; break; case ObservabilityErrorCode::schema_conflict: case ObservabilityErrorCode::would_deadlock: kind = ErrorKind::conflict; break; case ObservabilityErrorCode::capacity_exceeded: case ObservabilityErrorCode::cardinality_exceeded: kind = ErrorKind::exhausted; break; case ObservabilityErrorCode::closed: case ObservabilityErrorCode::cancelled: kind = ErrorKind::cancelled; break; case ObservabilityErrorCode::timeout: kind = ErrorKind::timeout; break; case ObservabilityErrorCode::unsupported_capability: kind = ErrorKind::unsupported; break; case ObservabilityErrorCode::quarantined: kind = ErrorKind::internal; break; } return Error{ kind, std::move(message), ErrorCode{Void::Result::kObservabilityErrorDomain, static_cast(code)}}; } namespace Detail { [[nodiscard]] constexpr int hex_nibble(char c) noexcept { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'a' && c <= 'f') { return 10 + (c - 'a'); } return -1; } template [[nodiscard]] inline std::string bytes_to_hex( const std::array& bytes) { constexpr char kHex[] = "0123456789abcdef"; std::string out; out.resize(N * 2); for (std::size_t i = 0; i < N; ++i) { const auto v = static_cast(bytes[i]); out[i * 2] = kHex[(v >> 4) & 0x0Fu]; out[i * 2 + 1] = kHex[v & 0x0Fu]; } return out; } template [[nodiscard]] inline Void::Result::Result> hex_to_bytes(std::string_view hex, std::string_view label) { if (hex.size() != N * 2) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::invalid_traceparent, std::string{label} + " hex length is invalid")); } std::array out{}; for (std::size_t i = 0; i < N; ++i) { const int hi = hex_nibble(hex[i * 2]); const int lo = hex_nibble(hex[i * 2 + 1]); if (hi < 0 || lo < 0) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::invalid_traceparent, std::string{label} + " contains non-hex or non-lowercase characters")); } out[i] = static_cast((hi << 4) | lo); } return out; } template [[nodiscard]] inline std::array generate_nonzero_bytes(G& gen) { std::uniform_int_distribution dist{0, 255}; std::array out{}; bool non_zero = false; do { non_zero = false; for (auto& b : out) { const auto v = static_cast(dist(gen)); b = static_cast(v); non_zero = non_zero || (v != 0); } } while (!non_zero); return out; } } // namespace Detail struct TraceId { std::array bytes{}; [[nodiscard]] constexpr bool operator==(const TraceId&) const noexcept = default; [[nodiscard]] constexpr bool is_zero() const noexcept { for (const auto b : bytes) { if (b != std::byte{0}) { return false; } } return true; } [[nodiscard]] std::string to_hex() const { return Detail::bytes_to_hex(bytes); } [[nodiscard]] static Void::Result::Result from_hex(std::string_view hex) { auto parsed = Detail::hex_to_bytes<16>(hex, "TraceId"); if (!parsed) { return Void::Result::fail(std::move(parsed).error()); } TraceId id{*parsed}; if (id.is_zero()) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::invalid_traceparent, "TraceId must not be all zeros")); } return id; } [[nodiscard]] static Void::Result::Result generate() { try { std::random_device rd; return TraceId{Detail::generate_nonzero_bytes<16>(rd)}; } catch (...) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::unsupported_capability, "System entropy unavailable for TraceId generation")); } } [[nodiscard]] static TraceId generate_seeded(std::uint64_t seed) { std::mt19937_64 rng{seed}; return TraceId{Detail::generate_nonzero_bytes<16>(rng)}; } }; struct SpanId { std::array bytes{}; [[nodiscard]] constexpr bool operator==(const SpanId&) const noexcept = default; [[nodiscard]] constexpr bool is_zero() const noexcept { for (const auto b : bytes) { if (b != std::byte{0}) { return false; } } return true; } [[nodiscard]] std::string to_hex() const { return Detail::bytes_to_hex(bytes); } [[nodiscard]] static Void::Result::Result from_hex(std::string_view hex) { auto parsed = Detail::hex_to_bytes<8>(hex, "SpanId"); if (!parsed) { return Void::Result::fail(std::move(parsed).error()); } SpanId id{*parsed}; if (id.is_zero()) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::invalid_traceparent, "SpanId must not be all zeros")); } return id; } [[nodiscard]] static Void::Result::Result generate() { try { std::random_device rd; return SpanId{Detail::generate_nonzero_bytes<8>(rd)}; } catch (...) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::unsupported_capability, "System entropy unavailable for SpanId generation")); } } [[nodiscard]] static SpanId generate_seeded(std::uint64_t seed) { std::mt19937_64 rng{seed}; return SpanId{Detail::generate_nonzero_bytes<8>(rng)}; } }; inline constexpr std::uint8_t kTraceFlagSampled = 0x01; struct TraceContext { TraceId trace_id{}; SpanId span_id{}; std::uint8_t flags{0}; [[nodiscard]] constexpr bool operator==(const TraceContext&) const noexcept = default; [[nodiscard]] constexpr bool valid() const noexcept { return !trace_id.is_zero() && !span_id.is_zero(); } [[nodiscard]] constexpr bool sampled() const noexcept { return (flags & kTraceFlagSampled) != 0; } [[nodiscard]] std::string to_traceparent() const { constexpr char kHex[] = "0123456789abcdef"; std::string out; out.reserve(55); out += "00-"; out += trace_id.to_hex(); out += '-'; out += span_id.to_hex(); out += '-'; out.push_back(kHex[(flags >> 4) & 0x0Fu]); out.push_back(kHex[flags & 0x0Fu]); return out; } [[nodiscard]] static Void::Result::Result from_traceparent(std::string_view header) { if (header.size() != 55 || header[0] != '0' || header[1] != '0' || header[2] != '-' || header[35] != '-' || header[52] != '-') { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::invalid_traceparent, "Malformed W3C traceparent framing or version")); } auto tid = TraceId::from_hex(header.substr(3, 32)); if (!tid) { return Void::Result::fail(std::move(tid).error()); } auto sid = SpanId::from_hex(header.substr(36, 16)); if (!sid) { return Void::Result::fail(std::move(sid).error()); } auto flags_bytes = Detail::hex_to_bytes<1>(header.substr(53, 2), "TraceFlags"); if (!flags_bytes) { return Void::Result::fail(std::move(flags_bytes).error()); } return TraceContext{ *tid, *sid, static_cast((*flags_bytes)[0])}; } }; struct ContextLimits { std::size_t max_baggage_items{16}; std::size_t max_baggage_bytes{2048}; std::size_t max_key_bytes{128}; std::size_t max_value_bytes{256}; [[nodiscard]] Void::Result::Result validate() const { if (max_baggage_items == 0 || max_baggage_bytes == 0 || max_key_bytes == 0 || max_value_bytes == 0) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::invalid_argument, "ContextLimits values must be non-zero")); } return {}; } }; struct BaggageItem { std::string key; std::string value; [[nodiscard]] bool operator==(const BaggageItem&) const = default; }; /// Immutable owning snapshot of TraceContext and bounded baggage carried across /// threads, tasks, and coroutine resumptions. class ContextSnapshot { public: ContextSnapshot() = default; [[nodiscard]] static Void::Result::Result create( std::optional trace = std::nullopt, std::span baggage = {}, ContextLimits limits = {}) { if (auto v = limits.validate(); !v) { return Void::Result::fail(std::move(v).error()); } if (trace.has_value() && !trace->valid()) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::invalid_argument, "TraceContext in ContextSnapshot must have non-zero IDs")); } auto data = std::make_shared(); data->limits = limits; data->trace = trace; for (const auto& item : baggage) { if (auto r = add_or_replace(*data, item.key, item.value); !r) { return Void::Result::fail(std::move(r).error()); } } return ContextSnapshot{std::move(data)}; } [[nodiscard]] ContextSnapshot with_trace(TraceContext trace) const { auto next = data_ ? std::make_shared(*data_) : std::make_shared(); next->trace = trace; return ContextSnapshot{std::move(next)}; } [[nodiscard]] Void::Result::Result with_baggage(std::string_view key, std::string_view value) const { auto next = data_ ? std::make_shared(*data_) : std::make_shared(); if (auto r = add_or_replace(*next, key, value); !r) { return Void::Result::fail(std::move(r).error()); } return ContextSnapshot{std::move(next)}; } [[nodiscard]] std::optional find_baggage(std::string_view key) const noexcept { if (!data_) { return std::nullopt; } for (const auto& item : data_->baggage) { if (item.key == key) { return std::string_view{item.value}; } } return std::nullopt; } [[nodiscard]] std::span baggage() const noexcept { if (!data_) { return {}; } return data_->baggage; } [[nodiscard]] std::size_t baggage_bytes() const noexcept { return data_ ? data_->baggage_bytes : 0; } [[nodiscard]] const std::optional& trace() const noexcept { static const std::optional kEmpty; return data_ ? data_->trace : kEmpty; } [[nodiscard]] bool empty() const noexcept { return !data_ || (!data_->trace.has_value() && data_->baggage.empty()); } private: struct Data { ContextLimits limits{}; std::optional trace{}; std::vector baggage{}; std::size_t baggage_bytes{0}; }; explicit ContextSnapshot(std::shared_ptr data) noexcept : data_(std::move(data)) { } static bool valid_key_or_value(std::string_view sv) noexcept { for (const unsigned char ch : sv) { if (ch < 0x20 || ch == 0x7F) { return false; } } return true; } static Void::Result::Result add_or_replace(Data& data, std::string_view key, std::string_view value) { if (key.empty() || key.size() > data.limits.max_key_bytes || !valid_key_or_value(key)) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::invalid_argument, "Invalid baggage key length or control character")); } if (value.size() > data.limits.max_value_bytes || !valid_key_or_value(value)) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::invalid_argument, "Invalid baggage value length or control character")); } for (auto& existing : data.baggage) { if (existing.key == key) { const std::size_t without = data.baggage_bytes - existing.value.size(); if (value.size() > data.limits.max_baggage_bytes - without) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::capacity_exceeded, "ContextSnapshot baggage byte budget exceeded")); } existing.value.assign(value); data.baggage_bytes = without + existing.value.size(); return {}; } } if (data.baggage.size() >= data.limits.max_baggage_items) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::capacity_exceeded, "ContextSnapshot baggage item limit exceeded")); } const std::size_t added = key.size() + value.size(); if (added > data.limits.max_baggage_bytes - data.baggage_bytes) { return Void::Result::fail(make_observability_error( ObservabilityErrorCode::capacity_exceeded, "ContextSnapshot baggage byte budget exceeded")); } data.baggage.push_back(BaggageItem{std::string{key}, std::string{value}}); data.baggage_bytes += added; return {}; } std::shared_ptr data_{}; }; /// Move-only RAII thread-local context scope that always restores the prior /// snapshot on normal exit or stack unwind. class ScopedContext { public: explicit ScopedContext(ContextSnapshot snapshot) noexcept : previous_(std::exchange(tls_slot(), std::move(snapshot))) , active_(true) { } ~ScopedContext() noexcept { if (active_) { tls_slot() = std::move(previous_); } } ScopedContext(ScopedContext&& other) noexcept : previous_(std::move(other.previous_)) , active_(std::exchange(other.active_, false)) { } ScopedContext& operator=(ScopedContext&&) = delete; ScopedContext(const ScopedContext&) = delete; ScopedContext& operator=(const ScopedContext&) = delete; [[nodiscard]] static ContextSnapshot current() noexcept { return tls_slot(); } private: static ContextSnapshot& tls_slot() noexcept { static thread_local ContextSnapshot current_context{}; return current_context; } ContextSnapshot previous_{}; bool active_{false}; }; } // namespace Void::Observability