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,109 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Observability/Context.hpp>
|
||||
|
||||
#include <coroutine>
|
||||
#include <functional>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Observability
|
||||
{
|
||||
|
||||
/// Wrap any callable/task with an owned ContextSnapshot so execution on a
|
||||
/// worker or executor installs ScopedContext across the invocation and restores
|
||||
/// the worker thread's previous context afterward.
|
||||
template <typename Fn>
|
||||
class BoundContextCallable
|
||||
{
|
||||
public:
|
||||
BoundContextCallable(ContextSnapshot snapshot, Fn fn)
|
||||
: snapshot_(std::move(snapshot))
|
||||
, fn_(std::move(fn))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
requires std::invocable<Fn&, Args...>
|
||||
decltype(auto) operator()(Args&&... args)
|
||||
{
|
||||
ScopedContext guard{snapshot_};
|
||||
return std::invoke(fn_, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
requires std::invocable<const Fn&, Args...>
|
||||
decltype(auto) operator()(Args&&... args) const
|
||||
{
|
||||
ScopedContext guard{snapshot_};
|
||||
return std::invoke(fn_, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
[[nodiscard]] const ContextSnapshot& context() const noexcept
|
||||
{
|
||||
return snapshot_;
|
||||
}
|
||||
|
||||
private:
|
||||
ContextSnapshot snapshot_;
|
||||
Fn fn_;
|
||||
};
|
||||
|
||||
template <typename Fn>
|
||||
[[nodiscard]] BoundContextCallable<std::decay_t<Fn>>
|
||||
bind_context(ContextSnapshot snapshot, Fn&& fn)
|
||||
{
|
||||
return BoundContextCallable<std::decay_t<Fn>>{
|
||||
std::move(snapshot),
|
||||
std::forward<Fn>(fn)};
|
||||
}
|
||||
|
||||
/// Coroutine awaitable adapter that binds an owned ContextSnapshot without
|
||||
/// keeping a thread-local ScopedContext active across coroutine suspension.
|
||||
template <typename Awaitable>
|
||||
class ContextAwaitable
|
||||
{
|
||||
public:
|
||||
ContextAwaitable(ContextSnapshot snapshot, Awaitable awaitable)
|
||||
: snapshot_(std::move(snapshot))
|
||||
, inner_(std::move(awaitable))
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] decltype(auto) await_ready()
|
||||
{
|
||||
return inner_.await_ready();
|
||||
}
|
||||
|
||||
[[nodiscard]] decltype(auto) await_suspend(std::coroutine_handle<> handle)
|
||||
{
|
||||
return inner_.await_suspend(handle);
|
||||
}
|
||||
|
||||
decltype(auto) await_resume()
|
||||
{
|
||||
ScopedContext guard{snapshot_};
|
||||
return inner_.await_resume();
|
||||
}
|
||||
|
||||
[[nodiscard]] const ContextSnapshot& context() const noexcept
|
||||
{
|
||||
return snapshot_;
|
||||
}
|
||||
|
||||
private:
|
||||
ContextSnapshot snapshot_;
|
||||
Awaitable inner_;
|
||||
};
|
||||
|
||||
template <typename Awaitable>
|
||||
[[nodiscard]] ContextAwaitable<std::decay_t<Awaitable>>
|
||||
with_context(ContextSnapshot snapshot, Awaitable&& awaitable)
|
||||
{
|
||||
return ContextAwaitable<std::decay_t<Awaitable>>{
|
||||
std::move(snapshot),
|
||||
std::forward<Awaitable>(awaitable)};
|
||||
}
|
||||
|
||||
} // namespace Void::Observability
|
||||
@@ -0,0 +1,553 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<std::int32_t>(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 <std::size_t N>
|
||||
[[nodiscard]] inline std::string bytes_to_hex(
|
||||
const std::array<std::byte, N>& 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<unsigned int>(bytes[i]);
|
||||
out[i * 2] = kHex[(v >> 4) & 0x0Fu];
|
||||
out[i * 2 + 1] = kHex[v & 0x0Fu];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
template <std::size_t N>
|
||||
[[nodiscard]] inline Void::Result::Result<std::array<std::byte, N>>
|
||||
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<std::byte, N> 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<std::byte>((hi << 4) | lo);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
template <std::size_t N, std::uniform_random_bit_generator G>
|
||||
[[nodiscard]] inline std::array<std::byte, N> generate_nonzero_bytes(G& gen)
|
||||
{
|
||||
std::uniform_int_distribution<unsigned int> dist{0, 255};
|
||||
std::array<std::byte, N> out{};
|
||||
bool non_zero = false;
|
||||
do {
|
||||
non_zero = false;
|
||||
for (auto& b : out) {
|
||||
const auto v = static_cast<std::uint8_t>(dist(gen));
|
||||
b = static_cast<std::byte>(v);
|
||||
non_zero = non_zero || (v != 0);
|
||||
}
|
||||
} while (!non_zero);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Detail
|
||||
|
||||
struct TraceId {
|
||||
std::array<std::byte, 16> 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<TraceId>
|
||||
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<TraceId> 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<std::byte, 8> 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<SpanId>
|
||||
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<SpanId> 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<TraceContext>
|
||||
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<std::uint8_t>((*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<void> 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<ContextSnapshot> create(
|
||||
std::optional<TraceContext> trace = std::nullopt,
|
||||
std::span<const BaggageItem> 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>();
|
||||
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>(*data_)
|
||||
: std::make_shared<Data>();
|
||||
next->trace = trace;
|
||||
return ContextSnapshot{std::move(next)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<ContextSnapshot>
|
||||
with_baggage(std::string_view key, std::string_view value) const
|
||||
{
|
||||
auto next = data_ ? std::make_shared<Data>(*data_)
|
||||
: std::make_shared<Data>();
|
||||
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<std::string_view>
|
||||
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<const BaggageItem> 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<TraceContext>& trace() const noexcept
|
||||
{
|
||||
static const std::optional<TraceContext> 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<TraceContext> trace{};
|
||||
std::vector<BaggageItem> baggage{};
|
||||
std::size_t baggage_bytes{0};
|
||||
};
|
||||
|
||||
explicit ContextSnapshot(std::shared_ptr<const Data> 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<void>
|
||||
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<const Data> 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
|
||||
@@ -0,0 +1,428 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Observability
|
||||
{
|
||||
|
||||
enum class MetricKind : std::uint8_t {
|
||||
counter = 0,
|
||||
gauge,
|
||||
histogram
|
||||
};
|
||||
|
||||
struct AttributeView {
|
||||
std::string_view key{};
|
||||
std::string_view value{};
|
||||
};
|
||||
|
||||
struct MetricPoint {
|
||||
std::string_view name{};
|
||||
MetricKind kind{MetricKind::counter};
|
||||
double value{0.0};
|
||||
std::uint64_t integer_delta{0};
|
||||
std::span<const AttributeView> attributes{};
|
||||
};
|
||||
|
||||
struct DiagnosticEvent {
|
||||
std::string_view component{};
|
||||
std::string_view message{};
|
||||
bool is_error{false};
|
||||
};
|
||||
|
||||
/// Zero-dependency synchronous observation callback table.
|
||||
/// Null hooks perform no allocation or backend initialization.
|
||||
struct ObservationHooks {
|
||||
void* state{nullptr};
|
||||
void (*record)(void* state, const MetricPoint& point) noexcept{nullptr};
|
||||
void (*diagnostic)(void* state, const DiagnosticEvent& event) noexcept{nullptr};
|
||||
|
||||
[[nodiscard]] constexpr bool active() const noexcept
|
||||
{
|
||||
return record != nullptr || diagnostic != nullptr;
|
||||
}
|
||||
|
||||
void emit_metric(const MetricPoint& point) const noexcept
|
||||
{
|
||||
if (record != nullptr) {
|
||||
record(state, point);
|
||||
}
|
||||
}
|
||||
|
||||
void emit_diagnostic(const DiagnosticEvent& event) const noexcept
|
||||
{
|
||||
if (diagnostic != nullptr) {
|
||||
diagnostic(state, event);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
inline constexpr ObservationHooks kNullObservationHooks{};
|
||||
|
||||
enum class DrainStatus : std::uint8_t {
|
||||
drained = 0,
|
||||
not_found,
|
||||
would_deadlock
|
||||
};
|
||||
|
||||
using HookRegistrationId = std::uint64_t;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
|
||||
struct HookControl {
|
||||
HookRegistrationId id{0};
|
||||
ObservationHooks raw_hooks{};
|
||||
std::function<void(const MetricPoint&)> guarded_record{};
|
||||
std::function<void(const DiagnosticEvent&)> guarded_diagnostic{};
|
||||
bool is_guarded{false};
|
||||
std::shared_ptr<const void> owner{};
|
||||
std::atomic<bool> detached{false};
|
||||
std::atomic<bool> quarantined{false};
|
||||
std::atomic<std::size_t> active_calls{0};
|
||||
std::atomic<std::uint64_t> failed_calls{0};
|
||||
std::mutex drain_mutex;
|
||||
std::condition_variable drain_cv;
|
||||
};
|
||||
|
||||
inline thread_local std::vector<const HookControl*> t_active_hook_controls;
|
||||
|
||||
struct HookCallScope {
|
||||
const HookControl* control{nullptr};
|
||||
|
||||
explicit HookCallScope(const HookControl* ctrl) : control(ctrl)
|
||||
{
|
||||
if (control != nullptr) {
|
||||
t_active_hook_controls.push_back(control);
|
||||
}
|
||||
}
|
||||
|
||||
~HookCallScope() noexcept
|
||||
{
|
||||
if (control != nullptr && !t_active_hook_controls.empty()) {
|
||||
t_active_hook_controls.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
HookCallScope(const HookCallScope&) = delete;
|
||||
HookCallScope& operator=(const HookCallScope&) = delete;
|
||||
|
||||
[[nodiscard]] static bool is_active_on_thread(const HookControl* ctrl) noexcept
|
||||
{
|
||||
for (const auto* entry : t_active_hook_controls) {
|
||||
if (entry == ctrl) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Detail
|
||||
|
||||
/// Move-only RAII lease retaining hook callback/owner state across an invocation
|
||||
/// outside any internal configuration mutex.
|
||||
class HookLease
|
||||
{
|
||||
public:
|
||||
HookLease() noexcept = default;
|
||||
|
||||
~HookLease() noexcept { reset(); }
|
||||
|
||||
HookLease(HookLease&& other) noexcept
|
||||
: control_(std::exchange(other.control_, nullptr))
|
||||
{
|
||||
}
|
||||
|
||||
HookLease& operator=(HookLease&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
reset();
|
||||
control_ = std::exchange(other.control_, nullptr);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
HookLease(const HookLease&) = delete;
|
||||
HookLease& operator=(const HookLease&) = delete;
|
||||
|
||||
[[nodiscard]] explicit operator bool() const noexcept
|
||||
{
|
||||
return control_ != nullptr;
|
||||
}
|
||||
|
||||
[[nodiscard]] HookRegistrationId registration_id() const noexcept
|
||||
{
|
||||
return control_ != nullptr ? control_->id : 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_quarantined() const noexcept
|
||||
{
|
||||
return control_ != nullptr &&
|
||||
control_->quarantined.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
void reset() noexcept
|
||||
{
|
||||
auto ctrl = std::exchange(control_, nullptr);
|
||||
if (!ctrl) {
|
||||
return;
|
||||
}
|
||||
if (ctrl->active_calls.fetch_sub(1, std::memory_order_acq_rel) == 1) {
|
||||
std::lock_guard lock{ctrl->drain_mutex};
|
||||
ctrl->drain_cv.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
friend class HookSlot;
|
||||
|
||||
explicit HookLease(std::shared_ptr<Detail::HookControl> ctrl) noexcept
|
||||
: control_(std::move(ctrl))
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<Detail::HookControl> control_{};
|
||||
};
|
||||
|
||||
/// Thread-safe hook registration owner supporting safe replacement, explicit
|
||||
/// detach-and-drain synchronization, recursion suppression, and exception quarantine.
|
||||
class HookSlot
|
||||
{
|
||||
public:
|
||||
HookSlot() = default;
|
||||
|
||||
~HookSlot() noexcept { (void)detach_and_drain(0); }
|
||||
|
||||
HookSlot(const HookSlot&) = delete;
|
||||
HookSlot& operator=(const HookSlot&) = delete;
|
||||
HookSlot(HookSlot&&) = delete;
|
||||
HookSlot& operator=(HookSlot&&) = delete;
|
||||
|
||||
HookRegistrationId install(ObservationHooks hooks,
|
||||
std::shared_ptr<const void> owner = {})
|
||||
{
|
||||
if (!hooks.active() && !owner) {
|
||||
std::shared_ptr<Detail::HookControl> old;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
old = std::exchange(active_, nullptr);
|
||||
if (old) {
|
||||
old->detached.store(true, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
auto next = std::make_shared<Detail::HookControl>();
|
||||
next->raw_hooks = hooks;
|
||||
next->owner = std::move(owner);
|
||||
next->is_guarded = false;
|
||||
return swap_active(std::move(next));
|
||||
}
|
||||
|
||||
HookRegistrationId install_guarded(
|
||||
std::function<void(const MetricPoint&)> record_fn,
|
||||
std::function<void(const DiagnosticEvent&)> diagnostic_fn = {},
|
||||
std::shared_ptr<const void> owner = {})
|
||||
{
|
||||
auto next = std::make_shared<Detail::HookControl>();
|
||||
next->guarded_record = std::move(record_fn);
|
||||
next->guarded_diagnostic = std::move(diagnostic_fn);
|
||||
next->owner = std::move(owner);
|
||||
next->is_guarded = true;
|
||||
return swap_active(std::move(next));
|
||||
}
|
||||
|
||||
[[nodiscard]] HookLease acquire_lease() const noexcept
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
if (!active_ || active_->detached.load(std::memory_order_acquire)) {
|
||||
return {};
|
||||
}
|
||||
active_->active_calls.fetch_add(1, std::memory_order_acq_rel);
|
||||
return HookLease{active_};
|
||||
}
|
||||
|
||||
DrainStatus detach_and_drain(HookRegistrationId id = 0) noexcept
|
||||
{
|
||||
std::shared_ptr<Detail::HookControl> target;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
prune_retired_locked();
|
||||
if (id == 0) {
|
||||
target = active_;
|
||||
} else if (active_ && active_->id == id) {
|
||||
target = active_;
|
||||
} else if (const auto it = known_.find(id); it != known_.end()) {
|
||||
target = it->second.lock();
|
||||
}
|
||||
|
||||
if (!target) {
|
||||
return DrainStatus::not_found;
|
||||
}
|
||||
if (Detail::HookCallScope::is_active_on_thread(target.get())) {
|
||||
return DrainStatus::would_deadlock;
|
||||
}
|
||||
|
||||
target->detached.store(true, std::memory_order_release);
|
||||
if (target == active_) {
|
||||
active_.reset();
|
||||
}
|
||||
known_.erase(target->id);
|
||||
}
|
||||
|
||||
{
|
||||
std::unique_lock drain_lock{target->drain_mutex};
|
||||
target->drain_cv.wait(drain_lock, [&target] {
|
||||
return target->active_calls.load(std::memory_order_acquire) == 0;
|
||||
});
|
||||
}
|
||||
target.reset();
|
||||
return DrainStatus::drained;
|
||||
}
|
||||
|
||||
void invoke_metric(const MetricPoint& point) noexcept
|
||||
{
|
||||
auto lease = acquire_lease();
|
||||
if (!lease) {
|
||||
return;
|
||||
}
|
||||
auto* ctrl = lease.control_.get();
|
||||
if (ctrl->quarantined.load(std::memory_order_acquire)) {
|
||||
return;
|
||||
}
|
||||
if (Detail::HookCallScope::is_active_on_thread(ctrl)) {
|
||||
reentrant_calls_.fetch_add(1, std::memory_order_relaxed);
|
||||
return;
|
||||
}
|
||||
Detail::HookCallScope scope{ctrl};
|
||||
if (!ctrl->is_guarded) {
|
||||
ctrl->raw_hooks.emit_metric(point);
|
||||
return;
|
||||
}
|
||||
if (!ctrl->guarded_record) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ctrl->guarded_record(point);
|
||||
} catch (...) {
|
||||
ctrl->failed_calls.fetch_add(1, std::memory_order_relaxed);
|
||||
failed_calls_.fetch_add(1, std::memory_order_relaxed);
|
||||
ctrl->quarantined.store(true, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
void invoke_diagnostic(const DiagnosticEvent& event) noexcept
|
||||
{
|
||||
auto lease = acquire_lease();
|
||||
if (!lease) {
|
||||
return;
|
||||
}
|
||||
auto* ctrl = lease.control_.get();
|
||||
if (ctrl->quarantined.load(std::memory_order_acquire)) {
|
||||
return;
|
||||
}
|
||||
if (Detail::HookCallScope::is_active_on_thread(ctrl)) {
|
||||
reentrant_calls_.fetch_add(1, std::memory_order_relaxed);
|
||||
return;
|
||||
}
|
||||
Detail::HookCallScope scope{ctrl};
|
||||
if (!ctrl->is_guarded) {
|
||||
ctrl->raw_hooks.emit_diagnostic(event);
|
||||
return;
|
||||
}
|
||||
if (!ctrl->guarded_diagnostic) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ctrl->guarded_diagnostic(event);
|
||||
} catch (...) {
|
||||
ctrl->failed_calls.fetch_add(1, std::memory_order_relaxed);
|
||||
failed_calls_.fetch_add(1, std::memory_order_relaxed);
|
||||
ctrl->quarantined.store(true, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool active() const noexcept
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
return active_ != nullptr && !active_->detached.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_quarantined() const noexcept
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
return active_ != nullptr &&
|
||||
active_->quarantined.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
void reset_quarantine() noexcept
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
if (active_) {
|
||||
active_->quarantined.store(false, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t failed_calls() const noexcept
|
||||
{
|
||||
return failed_calls_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t reentrant_calls() const noexcept
|
||||
{
|
||||
return reentrant_calls_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
private:
|
||||
HookRegistrationId swap_active(std::shared_ptr<Detail::HookControl> next)
|
||||
{
|
||||
std::shared_ptr<Detail::HookControl> old;
|
||||
HookRegistrationId id = 0;
|
||||
{
|
||||
std::lock_guard lock{mutex_};
|
||||
prune_retired_locked();
|
||||
id = ++next_id_;
|
||||
next->id = id;
|
||||
known_.emplace(id, next);
|
||||
old = std::exchange(active_, std::move(next));
|
||||
if (old) {
|
||||
old->detached.store(true, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
old.reset();
|
||||
return id;
|
||||
}
|
||||
|
||||
void prune_retired_locked()
|
||||
{
|
||||
for (auto it = known_.begin(); it != known_.end();) {
|
||||
if (it->second.expired()) {
|
||||
it = known_.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
HookRegistrationId next_id_{0};
|
||||
std::shared_ptr<Detail::HookControl> active_{};
|
||||
std::unordered_map<HookRegistrationId, std::weak_ptr<Detail::HookControl>> known_;
|
||||
std::atomic<std::uint64_t> failed_calls_{0};
|
||||
std::atomic<std::uint64_t> reentrant_calls_{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Observability
|
||||
@@ -0,0 +1,144 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Observability/Context.hpp>
|
||||
#include <Void/Observability/Hooks.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Observability
|
||||
{
|
||||
|
||||
struct MetricsLimits {
|
||||
std::size_t max_instruments{256};
|
||||
std::size_t max_series_per_instrument{1024};
|
||||
std::size_t max_total_series{4096};
|
||||
std::size_t max_labels_per_point{8};
|
||||
std::size_t max_key_bytes{128};
|
||||
std::size_t max_value_bytes{256};
|
||||
std::size_t max_producer_shards{32};
|
||||
std::size_t max_storage_bytes{32ULL * 1024ULL * 1024ULL};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> validate() const;
|
||||
};
|
||||
|
||||
[[nodiscard]] inline std::vector<double> default_duration_buckets_seconds()
|
||||
{
|
||||
return {0.0001, 0.0005, 0.001, 0.005, 0.01, 0.025, 0.05,
|
||||
0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0};
|
||||
}
|
||||
|
||||
struct InstrumentSpec {
|
||||
std::string name{};
|
||||
std::string unit{};
|
||||
MetricKind kind{MetricKind::counter};
|
||||
std::vector<std::string> label_keys{};
|
||||
std::vector<double> bucket_bounds{};
|
||||
};
|
||||
|
||||
struct InstrumentHandle {
|
||||
std::size_t index{0};
|
||||
std::uint64_t registry_id{0};
|
||||
|
||||
[[nodiscard]] constexpr bool valid() const noexcept
|
||||
{
|
||||
return registry_id != 0;
|
||||
}
|
||||
};
|
||||
|
||||
struct HistogramSnapshot {
|
||||
std::vector<double> bounds{};
|
||||
std::vector<std::uint64_t> bucket_counts{};
|
||||
std::uint64_t count{0};
|
||||
double sum{0.0};
|
||||
};
|
||||
|
||||
struct SeriesSnapshot {
|
||||
std::vector<std::pair<std::string, std::string>> labels{};
|
||||
bool is_overflow{false};
|
||||
std::uint64_t counter_value{0};
|
||||
bool counter_saturated{false};
|
||||
double gauge_value{0.0};
|
||||
bool has_gauge_sample{false};
|
||||
Void::Time::MonotonicClock::time_point gauge_timestamp{};
|
||||
HistogramSnapshot histogram{};
|
||||
};
|
||||
|
||||
struct InstrumentSnapshot {
|
||||
InstrumentSpec spec{};
|
||||
std::vector<SeriesSnapshot> series{};
|
||||
std::uint64_t dropped_series{0};
|
||||
std::uint64_t overflow_events{0};
|
||||
};
|
||||
|
||||
struct MetricsSnapshot {
|
||||
std::uint64_t epoch{1};
|
||||
std::vector<InstrumentSnapshot> instruments{};
|
||||
std::uint64_t dropped_series{0};
|
||||
std::uint64_t overflow_events{0};
|
||||
std::uint64_t rejected_invalid_points{0};
|
||||
std::uint64_t shared_shard_fallbacks{0};
|
||||
std::uint64_t unregistered_hook_points{0};
|
||||
std::size_t shard_count{0};
|
||||
std::size_t estimated_bytes{0};
|
||||
};
|
||||
|
||||
/// Thread-safe, sharded, cardinality- and byte-bounded metric registry with
|
||||
/// frozen schemas and cumulative snapshot export.
|
||||
class MetricRegistry
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] static Void::Result::Result<MetricRegistry> create(
|
||||
MetricsLimits limits = {},
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance());
|
||||
|
||||
MetricRegistry(MetricRegistry&&) noexcept = default;
|
||||
MetricRegistry& operator=(MetricRegistry&&) noexcept = default;
|
||||
MetricRegistry(const MetricRegistry&) = delete;
|
||||
MetricRegistry& operator=(const MetricRegistry&) = delete;
|
||||
~MetricRegistry();
|
||||
|
||||
[[nodiscard]] Void::Result::Result<InstrumentHandle>
|
||||
register_instrument(InstrumentSpec spec);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> add_counter(
|
||||
InstrumentHandle handle,
|
||||
std::uint64_t delta,
|
||||
std::span<const AttributeView> attributes = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> set_gauge(
|
||||
InstrumentHandle handle,
|
||||
double value,
|
||||
std::span<const AttributeView> attributes = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> observe_histogram(
|
||||
InstrumentHandle handle,
|
||||
double value,
|
||||
std::span<const AttributeView> attributes = {});
|
||||
|
||||
[[nodiscard]] MetricsSnapshot snapshot() const;
|
||||
void reset_epoch();
|
||||
|
||||
[[nodiscard]] ObservationHooks make_hooks() const noexcept;
|
||||
[[nodiscard]] std::shared_ptr<const void> keepalive() const noexcept;
|
||||
[[nodiscard]] const MetricsLimits& limits() const noexcept;
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
explicit MetricRegistry(std::shared_ptr<Impl> impl) noexcept;
|
||||
|
||||
std::shared_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace Void::Observability
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Observability/AsyncContext.hpp>
|
||||
#include <Void/Observability/Context.hpp>
|
||||
#include <Void/Observability/Hooks.hpp>
|
||||
#include <Void/Observability/Metrics.hpp>
|
||||
#include <Void/Observability/Tracing.hpp>
|
||||
@@ -0,0 +1,243 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Observability/Context.hpp>
|
||||
#include <Void/Observability/Metrics.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Observability
|
||||
{
|
||||
|
||||
struct TracingLimits {
|
||||
std::size_t max_active_spans{1024};
|
||||
std::size_t max_active_bytes{8ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_completed_spans{8192};
|
||||
std::size_t max_completed_bytes{16ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_attributes_per_span{32};
|
||||
std::size_t max_events_per_span{32};
|
||||
std::size_t max_bytes_per_span{8ULL * 1024ULL};
|
||||
std::size_t max_key_bytes{128};
|
||||
std::size_t max_value_bytes{256};
|
||||
std::size_t max_export_batch_spans{256};
|
||||
std::size_t max_export_batch_bytes{512ULL * 1024ULL};
|
||||
std::uint64_t root_sample_denominator{100};
|
||||
std::size_t max_export_retries{2};
|
||||
std::chrono::nanoseconds export_retry_budget{std::chrono::seconds{5}};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> validate() const;
|
||||
};
|
||||
|
||||
enum class SpanStatus : std::uint8_t {
|
||||
unset = 0,
|
||||
ok,
|
||||
error,
|
||||
abandoned
|
||||
};
|
||||
|
||||
struct SpanSpec {
|
||||
std::string name{};
|
||||
std::vector<std::pair<std::string, std::string>> attributes{};
|
||||
std::optional<TraceId> explicit_root_trace_id{};
|
||||
};
|
||||
|
||||
struct SpanEvent {
|
||||
std::string name{};
|
||||
Void::Time::MonotonicClock::time_point timestamp{};
|
||||
};
|
||||
|
||||
struct CompletedSpan {
|
||||
TraceContext context{};
|
||||
std::optional<SpanId> parent_span_id{};
|
||||
std::string name{};
|
||||
Void::Time::MonotonicClock::time_point start_time{};
|
||||
Void::Time::MonotonicClock::time_point end_time{};
|
||||
Void::Time::CivilClock::time_point civil_start_time{};
|
||||
SpanStatus status{SpanStatus::unset};
|
||||
std::vector<std::pair<std::string, std::string>> attributes{};
|
||||
std::vector<SpanEvent> events{};
|
||||
bool truncated{false};
|
||||
std::size_t estimated_bytes{0};
|
||||
};
|
||||
|
||||
struct ExportBatch {
|
||||
std::vector<CompletedSpan> spans{};
|
||||
std::size_t estimated_bytes{0};
|
||||
};
|
||||
|
||||
struct ExportReport {
|
||||
std::uint64_t exported_spans{0};
|
||||
std::uint64_t failed_spans{0};
|
||||
std::uint64_t dropped_spans{0};
|
||||
std::uint64_t duplicate_ends{0};
|
||||
std::uint64_t retries{0};
|
||||
bool timed_out{false};
|
||||
bool cancelled{false};
|
||||
};
|
||||
|
||||
struct ExportOptions {
|
||||
std::stop_token stop{};
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
|
||||
};
|
||||
|
||||
struct TracerStats {
|
||||
std::size_t active_spans{0};
|
||||
std::size_t active_bytes{0};
|
||||
std::size_t completed_spans{0};
|
||||
std::size_t completed_bytes{0};
|
||||
std::size_t in_flight_export_bytes{0};
|
||||
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};
|
||||
bool closed{false};
|
||||
};
|
||||
|
||||
class SpanExporter
|
||||
{
|
||||
public:
|
||||
virtual ~SpanExporter() = default;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
export_spans(std::span<const CompletedSpan> spans) = 0;
|
||||
};
|
||||
|
||||
class CallbackSpanExporter final : public SpanExporter
|
||||
{
|
||||
public:
|
||||
using Callback =
|
||||
std::function<Void::Result::Result<void>(std::span<const CompletedSpan>)>;
|
||||
|
||||
explicit CallbackSpanExporter(Callback callback);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
export_spans(std::span<const CompletedSpan> spans) override;
|
||||
|
||||
[[nodiscard]] std::uint64_t reentrant_drops() const noexcept
|
||||
{
|
||||
return reentrant_drops_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
private:
|
||||
Callback callback_;
|
||||
std::atomic<std::uint64_t> reentrant_drops_{0};
|
||||
};
|
||||
|
||||
class TextSnapshotExporter final : public SpanExporter
|
||||
{
|
||||
public:
|
||||
explicit TextSnapshotExporter(
|
||||
std::size_t max_output_bytes = 64ULL * 1024ULL);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
export_spans(std::span<const CompletedSpan> spans) override;
|
||||
|
||||
[[nodiscard]] static std::string render_metrics(
|
||||
const MetricsSnapshot& metrics,
|
||||
std::size_t max_output_bytes = 64ULL * 1024ULL);
|
||||
|
||||
[[nodiscard]] static std::string render_spans(
|
||||
std::span<const CompletedSpan> spans,
|
||||
std::size_t max_output_bytes = 64ULL * 1024ULL);
|
||||
|
||||
[[nodiscard]] std::string text() const;
|
||||
void clear();
|
||||
|
||||
private:
|
||||
std::size_t max_output_bytes_;
|
||||
mutable std::mutex mutex_;
|
||||
std::string buffer_;
|
||||
};
|
||||
|
||||
class Tracer;
|
||||
|
||||
/// Move-only span handle owning child TraceContext (never a raw parent pointer).
|
||||
/// Destroying an active unended handle terminates it with SpanStatus::abandoned.
|
||||
class Span
|
||||
{
|
||||
public:
|
||||
Span() = default;
|
||||
~Span() noexcept;
|
||||
|
||||
Span(Span&& other) noexcept;
|
||||
Span& operator=(Span&& other) noexcept;
|
||||
Span(const Span&) = delete;
|
||||
Span& operator=(const Span&) = delete;
|
||||
|
||||
[[nodiscard]] const ContextSnapshot& context() const noexcept
|
||||
{
|
||||
return context_;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_recording() const noexcept
|
||||
{
|
||||
return state_ != nullptr && !ended_;
|
||||
}
|
||||
|
||||
void set_attribute(std::string_view key, std::string_view value);
|
||||
void add_event(std::string_view name);
|
||||
void end(SpanStatus status = SpanStatus::ok) noexcept;
|
||||
|
||||
private:
|
||||
friend class Tracer;
|
||||
struct State;
|
||||
|
||||
Span(ContextSnapshot context, std::shared_ptr<State> state) noexcept;
|
||||
|
||||
ContextSnapshot context_{};
|
||||
std::shared_ptr<State> state_{};
|
||||
bool ended_{false};
|
||||
};
|
||||
|
||||
/// Head-sampled, byte-bounded tracer with explicit synchronous batch export
|
||||
/// and no implicit background worker threads.
|
||||
class Tracer
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] static Void::Result::Result<Tracer> create(
|
||||
TracingLimits limits = {},
|
||||
std::shared_ptr<SpanExporter> exporter = nullptr,
|
||||
const Void::Time::MonotonicClock& clock =
|
||||
Void::Time::SystemMonotonicClock::instance(),
|
||||
const Void::Time::CivilClock& civil_clock =
|
||||
Void::Time::SystemCivilClock::instance());
|
||||
|
||||
Tracer(Tracer&&) noexcept = default;
|
||||
Tracer& operator=(Tracer&&) noexcept = default;
|
||||
Tracer(const Tracer&) = delete;
|
||||
Tracer& operator=(const Tracer&) = delete;
|
||||
~Tracer();
|
||||
|
||||
[[nodiscard]] Span start_span(const ContextSnapshot& parent, SpanSpec spec);
|
||||
|
||||
[[nodiscard]] ExportReport flush(ExportOptions options = {});
|
||||
[[nodiscard]] ExportReport close(ExportOptions options = {});
|
||||
[[nodiscard]] TracerStats stats() const;
|
||||
|
||||
private:
|
||||
friend class Span;
|
||||
struct Impl;
|
||||
|
||||
explicit Tracer(std::shared_ptr<Impl> impl) noexcept;
|
||||
|
||||
std::shared_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace Void::Observability
|
||||
Reference in new issue
Block a user