Overview / Math, game & observability

telemetry

Metrics, traces in the W3C Trace Context standard and export to Prometheus, OTLP (protobuf and JSON), StatsD and JSON lines. It has no built-in thread, socket or address: export runs when the integrator calls <code>Tick</code>.

Optional module: turn it on with -DETHEREAL_TELEMETRY=ONInclude #include <ethereal/cpp/telemetry/telemetry_inc.hpp>C layer

telemetry_inc.hpp

#include <ethereal/cpp/telemetry/telemetry_inc.hpp>

Aggregate entry point of the Telemetry module.

Metrics with labels and bounded cardinality, W3C traces, and the export (Prometheus, OTLP, StatsD, JSON lines) driven by 'Tick'. The module only exists with ETHEREAL_TELEMETRY=ON. Without it, the ETL_TELEMETRY_* macros expand to nothing.

telemetry_export.hpp

#include <ethereal/cpp/telemetry/telemetry_export.hpp>

Export of the Telemetry module: encoders, sinks and exporter.

No thread, no server, no address built in. The export runs when the integrator calls 'CExporter::Tick' (or a dispatcher of theirs does). Sending goes through 'ITransport', which the integrator implements (the HTTP POST for OTLP, the datagram for StatsD). This module opens no connections and has no address compiled in. Nothing is ever sent to us.

Prometheus is pull based and the module does not start an HTTP server: 'RenderPrometheus' produces the exposition text, and the integrator serves it in their own handler.

The span queue is bounded with an overflow policy (in 'STracerParams'), and retries have jitter: ten thousand agents exporting in the same second of the clock are an attack of the client on its own collector. The metric interval also starts at a random point.

struct

ITransport

Ethereal::Telemetry#
C++
struct   ITransport
{
    ///
    /// Post
    ///
    /// @brief  An HTTP POST.
    ///
    /// @param sUrl                Full URL.
    /// @param sContentType        Content type of the body.
    /// @param Body                The body.
    /// @param pHttpStatus        Receives the HTTP status (200...).
    ///
    /// @return  eOk, or eTransport when it did not arrive (it will be tried again).
    ///
    virtual ETelemetryStatus Post( std::string_view sUrl, std::string_view sContentType,
                                   std::span< const std::uint8_t > Body, int * pHttpStatus ) noexcept = 0;


    /// @brief  A datagram (StatsD). The default has none and returns eNotFound.
    ///
    virtual ETelemetryStatus SendDatagram( std::span< const std::uint8_t > ) noexcept    { return ETelemetryStatus::eNotFound; }


    /// @brief  Destructor.
    ///
    virtual ~ITransport() = default;
};

Sending, done by the integrator.

struct

ISink

Ethereal::Telemetry#
C++
struct   ISink
{
    /// @brief  Exports a metric batch.
    ///
    virtual ETelemetryStatus Export( const SMetricBatch & Batch ) noexcept = 0;


    /// @brief  Exports a span batch.
    ///
    virtual ETelemetryStatus Export( const SSpanBatch & Batch ) noexcept = 0;


    /// @brief  Destructor.
    ///
    virtual ~ISink() = default;
};

A destination of the export.

eTransport means it failed in a way worth trying again.

function

RenderPrometheus

Ethereal::Telemetry#
void RenderPrometheus( const SMetricBatch & Batch, std::string * pOut );

The Prometheus exposition format (text 0.0.4).

HELP, TYPE, series with escaped labels, histograms with cumulative '_bucket{le=...}', '_sum' and '_count', summaries with '{quantile=...}'. The resource attributes are left out (Prometheus adds them on the scraping side: 'job', 'instance').

Batch
Collected metrics.
pOut
Receives the text.
enum

EOtlpEncoding

Ethereal::Telemetry#
C++
enum class   EOtlpEncoding : std::uint8_t { eProtobuf = 0, eJson };

Encoding of the OTLP requests: protobuf or JSON.

function

EncodeOtlpMetrics

Ethereal::Telemetry#
void EncodeOtlpMetrics( const SMetricBatch & Batch, EOtlpEncoding e, std::vector< std::uint8_t > * pOut );

OTLP 'ExportMetricsServiceRequest' (opentelemetry-proto v1).

Batch
Collected metrics.
e
Encoding.
pOut
Receives the request.
function

EncodeOtlpTraces

Ethereal::Telemetry#
void EncodeOtlpTraces( const SSpanBatch & Batch, EOtlpEncoding e, std::vector< std::uint8_t > * pOut );

OTLP 'ExportTraceServiceRequest'.

Batch
Finished spans.
e
Encoding.
pOut
Receives the request.
class

CPrometheusSink

Ethereal::Telemetry#

Keeps the Prometheus text of the last collection, for the integrator to serve.

class CPrometheusSink final : public ISink
function

Export

#
ETelemetryStatus Export( const SMetricBatch & Batch ) noexcept override;

Renders the batch and keeps the text.

function

Export

#
ETelemetryStatus Export( const SSpanBatch & ) noexcept override

Spans are ignored.

function

Text

#
std::string_view Text() const noexcept

Text of the last collection.

class

COtlpHttpSink

Ethereal::Telemetry#

OTLP over HTTP: POST to '<base>/v1/metrics' and '<base>/v1/traces'.

class COtlpHttpSink final : public ISink

2xx is accepted. 429, 502, 503 and 504 (the ones the OTLP/HTTP spec says can be retried) and a transport failure are tried again (eTransport). Any other 4xx or 5xx loses the batch (a refused request does not get better when repeated), is counted in 'Rejected', and returns eInvalidArgument.

constructor

COtlpHttpSink

#
COtlpHttpSink( ITransport & T, std::string_view sBaseUrl, EOtlpEncoding e = EOtlpEncoding::eProtobuf );

Constructor.

T
Transport. Must outlive the sink.
sBaseUrl
Base URL. Trailing slashes are removed.
e
Encoding.
function

Export

#
ETelemetryStatus Export( const SMetricBatch & Batch ) noexcept override;

Encodes and posts a metric batch.

function

Export

#
ETelemetryStatus Export( const SSpanBatch & Batch ) noexcept override;

Encodes and posts a span batch. An empty batch is not sent.

function

Rejected

#
std::uint64_t Rejected() const noexcept

Batches lost to a status that is not retried.

class

CStatsdSink

Ethereal::Telemetry#

StatsD over datagrams.

class CStatsdSink final : public ISink

Counters go as the difference since the last export ('|c'), gauges as '|g', and of histograms and summaries the count and the sum (as '|g' in '<name>.count' and '<name>.sum'). StatsD wants raw samples and here there are only aggregates: this is said instead of making samples up.

Labels go as DogStatsD tags ('|#key:value,...'), which Datadog, Telegraf and the Prometheus statsd_exporter understand. The original StatsD has no labels and ignores them. ':', '|', '@', '#' and ',' in names and values become '_'. Several lines per datagram, up to uMaxDatagram (1432 fits an Ethernet frame with IPv6 without fragmenting). A failed datagram is not repeated (StatsD is UDP, losing is normal), but the counter difference stays for next time.

constructor

CStatsdSink

#
CStatsdSink( ITransport & T, std::string_view sPrefix = {}, std::size_t uMaxDatagram = 1432 );

Constructor.

T
Transport. Must outlive the sink.
sPrefix
Prefix of the names. A '.' is added when missing.
uMaxDatagram
Maximum datagram size, at least 64.
function

Export

#
ETelemetryStatus Export( const SMetricBatch & Batch ) noexcept override;

Sends the batch as datagrams.

function

Export

#
ETelemetryStatus Export( const SSpanBatch & ) noexcept override

Spans are ignored.

class

CJsonLinesSink

Ethereal::Telemetry#

JSON lines appended to a file, for installations without network: one line per series and per span.

class CJsonLinesSink final : public ISink
constructor

CJsonLinesSink

#
explicit CJsonLinesSink( std::string_view sPath );

Constructor.

sPath
Path of the file, UTF-8.
function

Export

#
ETelemetryStatus Export( const SMetricBatch & Batch ) noexcept override;

Appends one line per series.

function

Export

#
ETelemetryStatus Export( const SSpanBatch & Batch ) noexcept override;

Appends one line per span.

function

ExportLog

#
ETelemetryStatus ExportLog( std::int64_t iTimeUnixNs, int iLevel, std::string_view sText, const STraceContext & Ctx ) noexcept;

Appends a log record (the Log bridge sends them here).

iTimeUnixNs
Time of the record, Unix ns.
iLevel
Log level.
sText
Text of the record.
Ctx
Trace context. Written only when valid.
eOk, eFull or eIo.
struct

SExporterParams

Ethereal::Telemetry#
C++
struct   SExporterParams
{
    /// @brief  sizeof( SExporterParams ), checked by Init.
    std::uint32_t        uStructSize = sizeof( SExporterParams );

    /// @brief  Registry. Null: no metrics.
    CRegistry *            pRegistry = nullptr;

    /// @brief  Tracer. Null: no spans.
    CTracer *            pTracer = nullptr;

    /// @brief  The sinks, at most 32.
    ISink * const *        apSinks = nullptr;
    std::size_t            nSinks = 0;

    /// @brief  Interval between metric exports.
    std::uint32_t        uMetricIntervalMs = 10000;

    /// @brief  Maximum spans in one batch.
    std::uint32_t        uMaxSpanBatch = 512;

    /// @brief  First retry wait, doubled on each failure up to uRetryMaxMs.
    std::uint32_t        uRetryBaseMs = 500;
    std::uint32_t        uRetryMaxMs = 60000;

    /// @brief  Jitter: the wait of each retry falls in [1 - j, 1] of the computed one.
    double                dJitter = 0.5;

    /// @brief  Jitter seed. 0 takes it from the clock (the jitter must differ between agents).
    std::uint64_t        uSeed = 0;

    /// @brief  Monotonic clock. Null: the system one.
    Time::IClock *        pClock = nullptr;
};

Exporter parameters.

struct

SExporterStats

Ethereal::Telemetry#
C++
struct   SExporterStats
{
    /// @brief  Metric exports done.
    std::uint64_t        uMetricExports = 0;

    /// @brief  Span batches exported.
    std::uint64_t        uSpanExports = 0;

    /// @brief  Spans exported.
    std::uint64_t        uSpansExported = 0;

    /// @brief  Failures, of any sink.
    std::uint64_t        uFailures = 0;

    /// @brief  Retries waiting (metrics, spans).
    std::uint64_t        uRetriesPending = 0;

    /// @brief  Time of the next attempt, on the exporter clock.
    std::int64_t        iNextAttemptNs = 0;
};

Exporter counters.

class

CExporter

Ethereal::Telemetry#

The exporter, driven by Tick.

class CExporter
constructor

CExporter

#
CExporter() noexcept = default;

Default constructor. Call Init before use.

function

Init

#
ETelemetryStatus Init( const SExporterParams & P ) noexcept;

Validates the parameters and reserves the span batch.

P
Exporter parameters.
eOk, eInvalidArgument, eFull, or eNotLicensed when the library is not licensed.
function

Tick

#
ETelemetryStatus Tick() noexcept;

Does what is due: metrics on the interval, finished spans, and the retries whose time came. With nothing to do it does nothing (it reads the clock only once).

function

Flush

#
ETelemetryStatus Flush() noexcept;

Exports everything now (at process end, for example), ignoring the times.

function

Stats

#
SExporterStats Stats() const noexcept;

Current counters.

function

RegisterProcessMetrics

Ethereal::Telemetry#
ETelemetryStatus RegisterProcessMetrics( CRegistry & R ) noexcept;

Registers the process metrics (off by default, call this to have them).

CPU time, resident memory, number of threads, and the time since the registry Init. There is no "open handles" nor the process uptime: the platform layer does not provide them, and they are not made up.

R
The registry.
eOk, or the first registration error.

telemetry_meta.hpp

#include <ethereal/cpp/telemetry/telemetry_meta.hpp>

Meta described structs as gauges and as redacted text.

'RegisterStruct' registers the numeric fields of a struct described by the Meta module as gauges, in one call. 'RedactedText' writes the struct as one line of text for the log. Both honour 'Meta::Sensitive'.

function

RegisterStruct

Ethereal::Telemetry#
template < typename T > ETelemetryStatus RegisterStruct( CRegistry & R, const std::string_view sPrefix, const T & Obj ) noexcept

Registers the numeric fields of Obj (except the 'Sensitive' ones) as gauges '<sPrefix>_<field>'.

R
The registry.
sPrefix
Prefix of the gauge names.
Obj
The object. Must outlive the registry.
eOk, or the first error (registration stops there).
function

RedactedText

Ethereal::Telemetry#
template < typename T > std::string RedactedText( const T & Obj )

A Meta described struct as one line of text ("{ name = value, ... }"), with the 'Sensitive' fields written "<sensitive>".

The rule of the metrics and of the Testing failure messages, for what goes to the log.

Obj
The object.
The text.

telemetry_metrics.hpp

#include <ethereal/cpp/telemetry/telemetry_metrics.hpp>

Metrics of the Telemetry module: registry and instruments.

Counters, sharded counters, gauges, exponential histograms and summaries, with labels and bounded cardinality. A metric is resolved once, at registration, into a pointer. The hot path (Inc, Add, Set, Record) never looks up a name.

Without ETL_TELEMETRY (the ETHEREAL_TELEMETRY CMake option off) the ETL_TELEMETRY_* macros expand to nothing and the types are only forward declared.

macro

ETL_TELEMETRY_INC

#
#define ETL_TELEMETRY_INC( pCounter ) ( pCounter )->Inc()

Adds one to a counter.

macro

ETL_TELEMETRY_ADD

#
#define ETL_TELEMETRY_ADD( pCounter, n ) ( pCounter )->Add( n )

Adds n to a counter.

macro

ETL_TELEMETRY_SET

#
#define ETL_TELEMETRY_SET( pGauge, v ) ( pGauge )->Set( v )

Sets the value of a gauge.

macro

ETL_TELEMETRY_RECORD

#
#define ETL_TELEMETRY_RECORD( pHist, v ) ( pHist )->Record( v )

Records a value in a histogram.

enum

ETelemetryStatus

Ethereal::Telemetry#
C++
enum class   ETelemetryStatus : std::uint8_t
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  An argument is out of range.
    eInvalidArgument,

    /// @brief  The capacity given to Init is exhausted.
    eFull,

    /// @brief  The family already has its maximum of series.
    eCardinality,

    /// @brief  The name already exists with another type or other labels.
    eExists,

    /// @brief  Not found.
    eNotFound,

    /// @brief  Init was not called.
    eNotInitialized,

    /// @brief  The queue is full.
    eQueueFull,

    /// @brief  The output buffer is too small.
    eBufferTooSmall,

    /// @brief  Sending failed. It will be tried again.
    eTransport,

    /// @brief  Input or output error.
    eIo,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///             has ended, or the license passed was refused (see
    ///             Bundle::UnlockBundle).
    eNotLicensed,
};

Result of the Telemetry calls.

function

StatusName

Ethereal::Telemetry#
const char * StatusName( ETelemetryStatus e ) noexcept;

Text of a status, for messages.

e
The status.
A static text, never null.
const

kCell

Ethereal::Telemetry#
constexpr std::size_t kCell = 64;

Size of a cell: one cache line, so there is no false sharing.

struct

SCell

Ethereal::Telemetry#
C++
struct   alignas( kCell )   SCell
{
    /// @brief  The value.
    std::atomic< std::uint64_t >    v{ 0 };

    /// @brief  Explicit padding. MSVC warns (C4324) about the implicit one.
    char                            aPadding[ kCell - sizeof( std::atomic< std::uint64_t > ) ];
};

A cell of a counter or gauge, alone on its cache line.

class

CCounter

Ethereal::Telemetry#

A counter, it only goes up. Inc is one relaxed atomic add.

class CCounter
function

Inc

#
void Inc() noexcept

Adds one.

function

Add

#
void Add( const std::uint64_t n ) noexcept

Adds n.

function

WithLabels

#
CCounter * WithLabels( std::span< const std::string_view > Values ) noexcept;

The series of these label values.

Call once and keep the pointer: this looks up, Inc does not.

Values
Label values, in the order of the names given to the registry.
The series, or an inert counter on error. Never null.
function

TryWithLabels

#
ETelemetryStatus TryWithLabels( std::span< const std::string_view > Values, CCounter ** pOut ) noexcept;

Same as WithLabels, returning the error.

Values
Label values, in the order of the names given to the registry.
pOut
Receives the series.
eOk, eInvalidArgument, eNotInitialized, eCardinality or eFull.
function

Value

#
std::uint64_t Value() const noexcept

Current value.

class

CShardedCounter

Ethereal::Telemetry#

A counter split per thread. Each thread adds in its own cell and the collection sums them all.

class CShardedCounter
function

Inc

#
void Inc() noexcept

Adds one in the cell of the calling thread.

function

Add

#
void Add( const std::uint64_t n ) noexcept

Adds n in the cell of the calling thread.

function

WithLabels

#
CShardedCounter * WithLabels( std::span< const std::string_view > Values ) noexcept;

The series of these label values. Call once and keep the pointer.

Values
Label values, in the order of the names given to the registry.
The series, or an inert counter on error. Never null.
function

TryWithLabels

#
ETelemetryStatus TryWithLabels( std::span< const std::string_view > Values, CShardedCounter ** pOut ) noexcept;

Same as WithLabels, returning the error.

Values
Label values, in the order of the names given to the registry.
pOut
Receives the series.
eOk, eInvalidArgument, eNotInitialized, eCardinality or eFull.
function

Value

#
std::uint64_t Value() const noexcept;

Sum of all the cells.

function

ThreadCellIndex

#
static std::uint32_t ThreadCellIndex() noexcept;

Cell index of the calling thread, given round robin on first use.

class

CGauge

Ethereal::Telemetry#

A value that goes up and down (a double, stored by its bits).

class CGauge
function

Set

#
void Set( const double d ) noexcept

Sets the value.

function

Add

#
void Add( double d ) noexcept;

Adds d (a compare and swap loop).

function

Inc

#
void Inc() noexcept

Adds one.

function

Dec

#
void Dec() noexcept

Subtracts one.

function

Value

#
double Value() const noexcept

Current value.

function

WithLabels

#
CGauge * WithLabels( std::span< const std::string_view > Values ) noexcept;

The series of these label values. Call once and keep the pointer.

Values
Label values, in the order of the names given to the registry.
The series, or an inert gauge on error. Never null.
function

TryWithLabels

#
ETelemetryStatus TryWithLabels( std::span< const std::string_view > Values, CGauge ** pOut ) noexcept;

Same as WithLabels, returning the error.

Values
Label values, in the order of the names given to the registry.
pOut
Receives the series.
eOk, eInvalidArgument, eNotInitialized, eCardinality or eFull.
struct

SHistogramSpec

Ethereal::Telemetry#
C++
struct   SHistogramSpec
{
    /// @brief  Lower limit, rounded down to a power of 2.
    double            dMin = 1e-6;

    /// @brief  Upper limit, rounded up to a power of 2.
    double            dMax = 1e6;

    /// @brief  Log2 of the number of buckets in each power of 2.
    std::uint32_t    uSubLog2 = 2;
};

Buckets of a histogram. Exponential, so the index comes from arithmetic.

From 2^floor(log2(dMin)) to 2^ceil(log2(dMax)) (the limits are rounded outwards to powers of 2), each power of 2 split into 2^uSubLog2 equal buckets (2 gives 4 per power, width <= 25%, 3 gives 8, <= 12.5%). One more bucket for "up to the minimum" and one for "above the maximum".

Arbitrary boundaries are not accepted: they need a search, and the spec forbids one in the hot path.

Valid: dMin >= DBL_MIN (normal), dMax > dMin and finite, uSubLog2 <= 8, at most 64 powers of 2 between the two.

class

CHistogram

Ethereal::Telemetry#

A histogram of exponential buckets. Record finds the index from the bits.

class CHistogram
function

Record

#
void Record( const double v ) noexcept

Records one value.

The buckets are (from, to], like the Prometheus 'le': a value equal to a limit counts in the bucket of that limit. For that the index comes from the bits of the double right below v (the bits minus 1, v is positive and normal here).

function

WithLabels

#
CHistogram * WithLabels( std::span< const std::string_view > Values ) noexcept;

The series of these label values. Call once and keep the pointer.

Values
Label values, in the order of the names given to the registry.
The series, or an inert histogram on error. Never null.
function

TryWithLabels

#
ETelemetryStatus TryWithLabels( std::span< const std::string_view > Values, CHistogram ** pOut ) noexcept;

Same as WithLabels, returning the error.

Values
Label values, in the order of the names given to the registry.
pOut
Receives the series.
eOk, eInvalidArgument, eNotInitialized, eCardinality or eFull.
function

Buckets

#
std::uint32_t Buckets() const noexcept

Number of buckets.

function

UpperBound

#
double UpperBound( std::uint32_t i ) const noexcept;

Upper limit of a bucket.

i
Bucket index.
The limit. The last bucket returns +inf.
function

BucketCount

#
std::uint64_t BucketCount( const std::uint32_t i ) const noexcept

Count of bucket i.

function

Sum

#
double Sum() const noexcept

Sum of the recorded values.

class

CSummary

Ethereal::Telemetry#

Quantiles from a fine histogram (64 buckets per power of 2).

class CSummary

Each quantile has a relative error <= 0.8% (half the bucket width, the midpoint is returned), over all the values recorded since the start. It is a sum, not a window. The range is 2^-20 (~1e-6) to 2^40 (~1e12). Outside it the quantile saturates at the end.

function

Record

#
void Record( const double v ) noexcept

Records one value.

function

WithLabels

#
CSummary * WithLabels( std::span< const std::string_view > Values ) noexcept;

The series of these label values. Call once and keep the pointer.

Values
Label values, in the order of the names given to the registry.
The series, or an inert summary on error. Never null.
function

TryWithLabels

#
ETelemetryStatus TryWithLabels( std::span< const std::string_view > Values, CSummary ** pOut ) noexcept;

Same as WithLabels, returning the error.

Values
Label values, in the order of the names given to the registry.
pOut
Receives the series.
eOk, eInvalidArgument, eNotInitialized, eCardinality or eFull.
function

Quantile

#
double Quantile( double q ) const noexcept;

A quantile, now.

q
The quantile, 0 to 1.
The value, or NaN when nothing was recorded.
function

Histogram

#
const CHistogram & Histogram() const noexcept

The underlying histogram.

enum

EMetricType

Ethereal::Telemetry#
C++
enum class   EMetricType : std::uint8_t { eCounter = 0, eGauge, eHistogram, eSummary };

Type of a metric family: counter, gauge, histogram or summary.

struct

SLabel

Ethereal::Telemetry#
C++
struct   SLabel
{
    /// @brief  Key.
    std::string_view    sKey;

    /// @brief  Value.
    std::string_view    sValue;
};

A label: key and value.

struct

SMetricPoint

Ethereal::Telemetry#
C++
struct   SMetricPoint
{
    /// @brief  Labels of the series.
    std::span< const SLabel >            Labels;

    /// @brief  Value of a counter or gauge.
    double                                dValue = 0.0;

    /// @brief  Histogram: upper limits (the last is +inf).
    std::span< const double >            Bounds;

    /// @brief  Histogram: count of each bucket (not cumulative).
    std::span< const std::uint64_t >    Counts;

    /// @brief  Summary: the quantiles asked for.
    std::span< const double >            Quantiles;

    /// @brief  Summary: the value of each quantile.
    std::span< const double >            QuantileValues;

    /// @brief  Histogram and summary: sum of the values.
    double                                dSum = 0.0;

    /// @brief  Histogram and summary: number of values.
    std::uint64_t                        uCount = 0;
};

A series at the moment of the collection.

The spans point to memory of the registry, valid until the next collection.

struct

SMetricFamily

Ethereal::Telemetry#
C++
struct   SMetricFamily
{
    /// @brief  Name.
    std::string_view                    sName;

    /// @brief  Help text.
    std::string_view                    sHelp;

    /// @brief  Type.
    EMetricType                            eType = EMetricType::eCounter;

    /// @brief  Its series.
    std::span< const SMetricPoint >        Points;
};

A metric family at the moment of the collection.

struct

SMetricBatch

Ethereal::Telemetry#
C++
struct   SMetricBatch
{
    /// @brief  The families.
    std::span< const SMetricFamily >    Families;

    /// @brief  Resource attributes (service, version...).
    std::span< const SLabel >            Resource;

    /// @brief  Time of the collection, Unix ns.
    std::int64_t                        iTimeUnixNs = 0;

    /// @brief  Init of the registry, Unix ns: the start of the cumulative values.
    std::int64_t                        iStartUnixNs = 0;
};

Everything a collection returns.

struct

SRegistryParams

Ethereal::Telemetry#
C++
struct   SRegistryParams
{
    /// @brief  sizeof( SRegistryParams ), checked by Init.
    std::uint32_t        uStructSize = sizeof( SRegistryParams );

    /// @brief  Maximum number of families.
    std::uint32_t        uMaxFamilies = 256;

    /// @brief  Maximum number of series, of all families together.
    std::uint32_t        uMaxSeries = 4096;

    /// @brief  Series per family when the registration does not say.
    std::uint32_t        uDefaultCardinality = 100;

    /// @brief  Bytes of all the stored label values.
    std::uint32_t        uMaxLabelBytes = 1u << 18;

    /// @brief  Cells of a CShardedCounter, a power of 2 up to 64. 0 uses the cores.
    std::uint32_t        uShards = 0;
};

Registry parameters.

alias

double

Ethereal::Telemetry#
using FGaugeReader = double ( * )( const void * pContext ) noexcept;

A gauge read at collection: the value comes from this function (the Meta and the process metrics use it).

class

CRegistry

Ethereal::Telemetry#

The metric registry, with fixed capacity.

class CRegistry
constructor

CRegistry

#
CRegistry() noexcept = default;

Default constructor. Call Init before use.

function

Init

#
ETelemetryStatus Init( const SRegistryParams & P ) noexcept;

Validates the parameters and reserves the whole capacity.

P
Registry parameters.
eOk, eInvalidArgument, eFull, or eNotLicensed when the library is not licensed.
function

Counter

#
CCounter * Counter( std::string_view sName, std::string_view sHelp, std::span< const std::string_view > LabelNames = {}, std::uint32_t uCardinality = 0 ) noexcept;

Registers a counter.

The same name with the same type and labels returns the one that already exists. Without labels, the single series comes ready.

sName
Name, in the Prometheus form.
sHelp
Help text.
LabelNames
Label names.
uCardinality
Maximum of series. 0 uses 'uDefaultCardinality'.
The counter, or an inert one on error. Never null.
function

ShardedCounter

#
CShardedCounter * ShardedCounter( std::string_view sName, std::string_view sHelp, std::span< const std::string_view > LabelNames = {}, std::uint32_t uCardinality = 0 ) noexcept;

Registers a counter split per thread. Same rules as Counter.

sName
Name, in the Prometheus form.
sHelp
Help text.
LabelNames
Label names.
uCardinality
Maximum of series. 0 uses 'uDefaultCardinality'.
The counter, or an inert one on error. Never null.
function

Gauge

#
CGauge * Gauge( std::string_view sName, std::string_view sHelp, std::span< const std::string_view > LabelNames = {}, std::uint32_t uCardinality = 0 ) noexcept;

Registers a gauge. Same rules as Counter.

sName
Name, in the Prometheus form.
sHelp
Help text.
LabelNames
Label names.
uCardinality
Maximum of series. 0 uses 'uDefaultCardinality'.
The gauge, or an inert one on error. Never null.
function

Histogram

#
CHistogram * Histogram( std::string_view sName, std::string_view sHelp, const SHistogramSpec & Spec, std::span< const std::string_view > LabelNames = {}, std::uint32_t uCardinality = 0 ) noexcept;

Registers a histogram. Same rules as Counter.

sName
Name, in the Prometheus form.
sHelp
Help text.
Spec
Buckets.
LabelNames
Label names.
uCardinality
Maximum of series. 0 uses 'uDefaultCardinality'.
The histogram, or an inert one on error. Never null.
function

Summary

#
CSummary * Summary( std::string_view sName, std::string_view sHelp, std::span< const double > Quantiles, std::span< const std::string_view > LabelNames = {}, std::uint32_t uCardinality = 0 ) noexcept;

Registers a summary. Same rules as Counter.

sName
Name, in the Prometheus form.
sHelp
Help text.
Quantiles
Quantiles to export, 0 to 1, at most 16.
LabelNames
Label names.
uCardinality
Maximum of series. 0 uses 'uDefaultCardinality'.
The summary, or an inert one on error. Never null.
function

GaugeFunction

#
ETelemetryStatus GaugeFunction( std::string_view sName, std::string_view sHelp, FGaugeReader pFn, const void * pContext ) noexcept;

Registers a gauge whose value is read at collection, by pFn( pContext ).

sName
Name, in the Prometheus form.
sHelp
Help text.
pFn
Reader function.
pContext
Passed to pFn. Must outlive the registry.
eOk, eNotInitialized, eInvalidArgument, eExists or eFull.
function

LastError

#
ETelemetryStatus LastError() const noexcept;

Error of the last registration that failed.

function

CardinalityRejections

#
std::uint64_t CardinalityRejections() const noexcept;

Number of series refused by the cardinality limit.

function

Collect

#
ETelemetryStatus Collect( SMetricBatch * pOut, std::int64_t iTimeUnixNs = 0 ) noexcept;

Takes a snapshot of everything, without blocking whoever records.

The spans of the result are valid until the next collection. Not to be called from two threads at the same time.

pOut
Receives the batch.
iTimeUnixNs
Time of the collection. 0 reads the system clock.
eOk, eInvalidArgument, eNotInitialized or eFull.
function

SetResource

#
ETelemetryStatus SetResource( std::span< const SLabel > Attributes ) noexcept;

Sets the resource attributes (service name, version, instance, host), attached to every export.

Attributes
The attributes, at most 32.
eOk, eNotInitialized, eInvalidArgument or eFull.
function

IsInitialized

#
bool IsInitialized() const noexcept

true after a successful Init.

function

Impl

#
Detail::SRegistryImpl * Impl() noexcept

The internals, for the other files of the module.

telemetry_trace.hpp

#include <ethereal/cpp/telemetry/telemetry_trace.hpp>

Traces of the Telemetry module: W3C context, tracer and span.

The context is the W3C Trace Context ('traceparent' and 'tracestate'), not a format of our own: that is what makes the data usable in the tools the client already has. It travels in the Rpc metadata (the 'telemetry_rpc' glue) and in any HTTP header ('FormatTraceparent' / 'ParseTraceparent').

Sampling is decided once, at the root, and travels in the 'sampled' bit of the flags. A child never decides again (always, never, ratio, and "by the parent").

A span that is not sampled is inert: it records nothing and reserves nothing. It only exists so the context (the ids) keeps propagating. A sampled one comes from a pool of fixed capacity reserved in Init. When the pool is empty the span is born inert and is counted in 'DroppedSpans'.

Attributes go in fixed memory inside the span (up to 'kMaxAttributes' and 'kSpanBytes' of text). What does not fit is lost and counted. A span is not a log record.

The current context is kept per thread (thread_local) by default, and per fiber when the Coroutine glue plugs in the 'IContextStorage' seam (a thread_local in a fiber that changes thread would be wrong).

struct

STraceContext

Ethereal::Telemetry#
C++
struct   STraceContext
{
    /// @brief  Trace id.
    std::uint8_t    aTraceId[ 16 ] = {};

    /// @brief  Span id.
    std::uint8_t    aSpanId[ 8 ] = {};

    /// @brief  Flags. Bit 0: sampled.
    std::uint8_t    uFlags = 0;


    /// @brief  true when the trace id and the span id are not all zeros.
    ///
    bool IsValid() const noexcept
    {
        /// Three 64 bit reads (a byte loop becomes a slow vector reduction).
        std::uint64_t t0, t1, s;
        std::memcpy( &t0, aTraceId, 8 );
        std::memcpy( &t1, aTraceId + 8, 8 );
        std::memcpy( &s, aSpanId, 8 );
        return ( t0 | t1 ) != 0 && s != 0;
    }


    /// @brief  true when the sampled bit is set.
    ///
    bool IsSampled() const noexcept        { return ( uFlags & 1u ) != 0; }
};

The W3C context: 25 bytes, trivially copyable.

The 'tracestate', optional and bounded, goes apart in 'STraceState'.

struct

STraceState

Ethereal::Telemetry#
C++
struct   STraceState
{
    /// @brief  The members, separated by commas.
    char            aText[ 512 ] = {};

    /// @brief  Bytes used in aText.
    std::uint16_t    nText = 0;


    /// @brief  The text as a view.
    ///
    std::string_view View() const noexcept    { return std::string_view( aText, nText ); }
};

The W3C 'tracestate', bounded: up to 32 members and 512 bytes (the limit of the standard).

const

kTraceparentLen

Ethereal::Telemetry#
constexpr std::size_t kTraceparentLen = 55;

Length of a 'traceparent': "00-" + 32 + "-" + 16 + "-" + 2.

function

FormatTraceparent

Ethereal::Telemetry#
std::size_t FormatTraceparent( const STraceContext & Ctx, std::span< char > Out ) noexcept;

Writes the 'traceparent' ("00-<trace>-<span>-<flags>", lowercase).

Ctx
The context.
Out
Output, at least 55 chars. Not terminated.
55, or 0 when Out is too small.
function

ParseTraceparent

Ethereal::Telemetry#
bool ParseTraceparent( std::string_view s, STraceContext * pOut ) noexcept;

Reads a 'traceparent'.

Refuses what the standard says to refuse: uppercase hex, all zero ids, version ff, wrong sizes. A future version (> 00) is read by its first 55 characters when the 56th is '-', as the standard asks.

s
The text.
pOut
Receives the context.
true when valid.
function

ParseTracestate

Ethereal::Telemetry#
bool ParseTracestate( std::string_view s, STraceState * pOut ) noexcept;

Checks and stores a 'tracestate' ("key=value" members separated by commas, up to 32 and 512 bytes).

s
The text.
pOut
Receives the members. Left empty when invalid.
true when valid.
function

TrimHeaderValue

Ethereal::Telemetry#
inline std::string_view TrimHeaderValue( std::string_view s ) noexcept

Removes the spaces and tabs at the ends (HTTP allows them around the value).

const

kTraceparentHeader

Ethereal::Telemetry#
inline constexpr std::string_view kTraceparentHeader = "traceparent";

Header names (lowercase, as the standard writes them).

const

kTracestateHeader

Ethereal::Telemetry#
inline constexpr std::string_view kTracestateHeader = "tracestate";
function

InjectHttpHeaders

Ethereal::Telemetry#
template < class TSet > bool InjectHttpHeaders( const STraceContext & Ctx, const STraceState * pState, TSet && Set )

Writes the context into headers: 'Set( kTraceparentHeader, "00-..." )' and, when pState is neither null nor empty, 'Set( kTracestateHeader, ... )'.

C++
Telemetry::CSpan S = Tracer.StartSpan( "GET /account", { Telemetry::ESpanKind::eClient } );
Telemetry::InjectHttpHeaders( S.Context(), nullptr,
    [ & ]( std::string_view n, std::string_view v ) { Request.SetHeader( n, v ); } );
Ctx
The context.
pState
Optional 'tracestate'.
Set
Function of the caller that writes a header.
false (and nothing written) when the context is invalid.
function

ExtractHttpHeaders

Ethereal::Telemetry#
template < class TGet, typename = std::enable_if_t< std::is_invocable_r_v< std::string_view, TGet, std::string_view > > > bool ExtractHttpHeaders( TGet && Get, STraceContext * pOut, STraceState * pState = nullptr )

Reads the context from headers.

'Get( name )' returns the value (empty when there is none), comparing names ignoring case. With several 'tracestate', the function of the caller joins them with commas.

Get
Function of the caller that reads a header.
pOut
Receives the context.
pState
Optional. Receives the 'tracestate' (empty when it did not come or is invalid).
true when a valid 'traceparent' came. false starts a new trace, and pState is left empty.
struct

SHttpHeader

Ethereal::Telemetry#
C++
struct   SHttpHeader
{
    /// @brief  Name.
    std::string_view    sName;

    /// @brief  Value.
    std::string_view    sValue;
};

A header: name and value, like those of the list the ready form reads.

function

ExtractHttpHeaders

Ethereal::Telemetry#
bool ExtractHttpHeaders( std::span< const SHttpHeader > Headers, STraceContext * pOut, STraceState * pState = nullptr ) noexcept;

The ready form: reads the context from a list of headers.

Names ignore case. Several 'tracestate' are joined with commas. When together they go over the 512 bytes of the standard, the 'tracestate' is dropped.

Headers
The headers.
pOut
Receives the context.
pState
Optional. Receives the 'tracestate'.
true when a valid 'traceparent' came.
struct

IContextStorage

Ethereal::Telemetry#
C++
struct   IContextStorage
{
    /// @brief  The active context, or null.
    ///
    virtual const STraceContext * Get() noexcept = 0;


    /// @brief  Sets the active context. Null clears.
    ///
    virtual void Set( const STraceContext * p ) noexcept = 0;


    /// @brief  Destructor.
    ///
    virtual ~IContextStorage() = default;
};

Where the active context is kept. By default, one per thread.

It keeps only a pointer. The active context lives inside the 'CSpan::SScope' that activated it (on the stack of whoever activated it, the fiber stack in a fiber), and scopes nest as a stack, so the pointer is valid until the next Set. A pointer fits a per fiber storage slot of the Coroutine without reserving any memory, which is why it works this way.

Get returns the active context, or null. Set(null) clears. Neither may allocate.

function

SetContextStorage

Ethereal::Telemetry#
void SetContextStorage( IContextStorage * p ) noexcept;

Replaces the storage (before there are spans). Null goes back to the thread_local.

enum

ESampler

Ethereal::Telemetry#
C++
enum class   ESampler : std::uint8_t { eAlways = 0, eNever, eRatio, eParentBased };

Who decides whether a trace is sampled.

A child of the current context (the one of the same process) always inherits the decision of the parent, whatever the sampler: the decision belongs to the root and is never evaluated again. The sampler only decides roots and children of a parent given in 'SSpanOptions::pParent' (typically the one that came from outside, through Rpc): eParentBased inherits it, the others decide on their own.

eRatio decides by the trace id itself (the last 8 bytes, big endian, against dRatio * 2^64). It is deterministic, so two services with the same ratio decide the same for the same trace.

enum

ESpanKind

Ethereal::Telemetry#
C++
enum class   ESpanKind : std::uint8_t { eInternal = 0, eServer, eClient, eProducer, eConsumer };

Kind of a span, as in OpenTelemetry.

enum

ESpanStatus

Ethereal::Telemetry#
C++
enum class   ESpanStatus : std::uint8_t { eUnset = 0, eOk, eError };

Status of a span, as in OpenTelemetry.

const

kMaxAttributes

Ethereal::Telemetry#
constexpr std::size_t kMaxAttributes = 16;

Maximum attributes of a span.

const

kMaxEvents

Ethereal::Telemetry#
constexpr std::size_t kMaxEvents = 8;

Maximum events of a span.

const

kSpanBytes

Ethereal::Telemetry#
constexpr std::size_t kSpanBytes = 512;

Text of name, attributes, events and status of one span.

enum

EOverflow

Ethereal::Telemetry#
C++
enum class   EOverflow : std::uint8_t { eDropOldest = 0, eDropNewest, eBlock };

What to do when the queue of finished spans (to export) is full.

eBlock waits (up to 'uBlockTimeoutMs') for a 'Drain' in another thread to make room, and then drops the new one. It only works with a dispatcher in another thread, because without any thread nobody empties the queue while it waits.

struct

STracerParams

Ethereal::Telemetry#
C++
struct   STracerParams
{
    /// @brief  sizeof( STracerParams ), checked by Init.
    std::uint32_t        uStructSize = sizeof( STracerParams );

    /// @brief  Sampled spans in flight or waiting for export (the pool).
    std::uint32_t        uMaxSpans = 1024;

    /// @brief  Maximum finished spans waiting for export.
    std::uint32_t        uQueueCapacity = 512;

    /// @brief  Policy when the queue is full.
    EOverflow            eOverflow = EOverflow::eDropOldest;

    /// @brief  Maximum wait of eBlock.
    std::uint32_t        uBlockTimeoutMs = 100;

    /// @brief  Sampler.
    ESampler            eSampler = ESampler::eParentBased;

    /// @brief  For eParentBased: how a root decides.
    ESampler            eRootSampler = ESampler::eAlways;

    /// @brief  For eRatio (and roots of eParentBased with eRatio).
    double                dRatio = 1.0;

    /// @brief  Wall clock. Null: the system one.
    Time::IClock *        pClock = nullptr;
};

Tracer parameters.

struct

SSpanOptions

Ethereal::Telemetry#
C++
struct   SSpanOptions
{
    /// @brief  Kind.
    ESpanKind                eKind = ESpanKind::eInternal;

    /// @brief  Parent. Null: the current context.
    const STraceContext *    pParent = nullptr;

    /// @brief  Ignores the current context (starts a new trace).
    bool                    bRoot = false;
};

Options of a new span.

struct

SSpanAttribute

Ethereal::Telemetry#
C++
struct   SSpanAttribute
{
    /// @brief  Key.
    std::string_view    sKey;

    /// @brief  Type: 0 text, 1 integer, 2 double, 3 bool.
    std::uint8_t        uType = 0;

    /// @brief  Value of each type (a bool goes in iValue).
    std::string_view    sValue;
    std::int64_t        iValue = 0;
    double                dValue = 0.0;
};

A recorded attribute (for the export).

struct

SSpanEvent

Ethereal::Telemetry#
C++
struct   SSpanEvent
{
    /// @brief  Name.
    std::string_view    sName;

    /// @brief  Time, Unix ns.
    std::int64_t        iTimeUnixNs = 0;
};

A recorded event.

struct

SSpanData

Ethereal::Telemetry#
C++
struct   SSpanData
{
    /// @brief  Context of the span.
    STraceContext                        Context;

    /// @brief  Span id of the parent, valid when bHasParent.
    std::uint8_t                        aParentSpanId[ 8 ] = {};
    bool                                bHasParent = false;

    /// @brief  Name.
    std::string_view                    sName;

    /// @brief  Kind.
    ESpanKind                            eKind = ESpanKind::eInternal;

    /// @brief  Start and end, Unix ns.
    std::int64_t                        iStartUnixNs = 0;
    std::int64_t                        iEndUnixNs = 0;

    /// @brief  Status and its message (only on an error).
    ESpanStatus                            eStatus = ESpanStatus::eUnset;
    std::string_view                    sStatusMessage;

    /// @brief  Attributes and events.
    std::span< const SSpanAttribute >    Attributes;
    std::span< const SSpanEvent >        Events;

    /// @brief  Attributes, events and texts lost for lack of room.
    std::uint32_t                        uDroppedAttributes = 0;
};

A finished span, as the export sees it.

struct

SSpanBatch

Ethereal::Telemetry#
C++
struct   SSpanBatch
{
    /// @brief  The spans.
    std::span< const SSpanData >        Spans;

    /// @brief  Resource attributes.
    std::span< const SLabel >            Resource;
};

Spans handed to a sink.

class

CSpan

Ethereal::Telemetry#

A span. Move only, the destructor ends it. An inert one records nothing.

class CSpan
A span is used by one thread at a time (it may change thread, not be shared). The tracer must outlive its spans.
constructor

CSpan

#
CSpan() noexcept = default;

An inert span.

constructor

CSpan

#
CSpan( CSpan && o ) noexcept;

Move. o becomes inert.

operator

operator=

#
CSpan & operator=( CSpan && o ) noexcept;

Move. Ends this span first, o becomes inert.

function

SetAttribute

#
void SetAttribute( std::string_view sKey, std::string_view sValue ) noexcept;

Sets a text attribute. The same key replaces the value.

function

SetAttribute

#
void SetAttribute( std::string_view sKey, std::int64_t iValue ) noexcept;

Sets an integer attribute.

function

SetAttribute

#
void SetAttribute( std::string_view sKey, double dValue ) noexcept;

Sets a double attribute.

function

SetAttribute

#
void SetAttribute( std::string_view sKey, bool bValue ) noexcept;

Sets a bool attribute.

function

AddEvent

#
void AddEvent( std::string_view sName ) noexcept;

Adds an event, at the current time.

function

SetStatus

#
void SetStatus( ESpanStatus e, std::string_view sMessage = {} ) noexcept;

Sets the status. The message is kept only on eError.

function

End

#
void End() noexcept;

Ends the span (once, later calls do nothing) and hands it to the export.

function

Context

#
const STraceContext & Context() const noexcept

Context of the span.

function

IsRecording

#
bool IsRecording() const noexcept

true when the span records (sampled and with a slot).

class

SScope

#
class SScope

Makes this the current context until the returned 'SScope' dies (which restores the previous one).

Scopes nest as a stack: end them in reverse order.

The scope keeps the active context (a copy: the span may move or end first) and is neither moved nor copied. It is born in the place of whoever receives it ('auto E = S.Activate();', by the guaranteed elision of C++17), because the storage points inside it.

function

Activate

#
SScope Activate() noexcept

See SScope.

class

CTracer

Ethereal::Telemetry#

The tracer: pool of spans, sampling and queue of finished spans.

class CTracer
constructor

CTracer

#
CTracer() noexcept = default;

Default constructor. Call Init before use.

function

Init

#
ETelemetryStatus Init( const STracerParams & P ) noexcept;

Validates the parameters and reserves the pool and the queue.

P
Tracer parameters.
eOk, eInvalidArgument, eFull, or eNotLicensed when the library is not licensed.
function

StartSpan

#
CSpan StartSpan( std::string_view sName, const SSpanOptions & O = SSpanOptions{} ) noexcept;

A new span, child of the current context (or of O.pParent).

The sampling decision belongs to the root, the child inherits it.

sName
Name of the span.
O
Options.
The span. Inert when not sampled or the pool is empty.
function

CurrentContext

#
static STraceContext CurrentContext() noexcept;

The active context in this thread (or fiber). Invalid when there is none.

function

Drain

#
std::size_t Drain( std::span< SSpanData > Out ) noexcept;

Takes finished spans (up to Out.size()) for export.

Out
Receives the spans. The text they point to is valid until Release.
Number of spans taken.
function

Release

#
void Release( std::size_t n ) noexcept;

Gives back to the pool the first n taken by the last Drain.

function

DroppedSpans

#
std::uint64_t DroppedSpans() const noexcept;

Spans lost: pool empty or queue overflow.

function

FinishedSpans

#
std::uint64_t FinishedSpans() const noexcept;

Spans that entered the queue.

function

Impl

#
Detail::STracerImpl * Impl() noexcept

The internals, for the other files of the module.