userver: utils::statistics::Snapshot Class Reference
Loading...
Searching...
No Matches
utils::statistics::Snapshot Class Referencefinal

#include <userver/utils/statistics/testing.hpp>

Detailed Description

A snapshot of metrics dumped via utils::statistics::Writer.

Lifetime of returned views

Returned utils::statistics::MetricView and utils::statistics::MetricValue objects refer to snapshot data, not to the vector returned by utils::statistics::Snapshot::AllMetrics.

  • Copy construction/assignment preserves source views without extending their lifetime.
  • Move construction/assignment preserves source views, tying their lifetime to the destination instead.
  • Assignment invalidates the destination's previous views; destruction invalidates views still tied to that snapshot. Existing copies do not prevent invalidation.

Definition at line 126 of file testing.hpp.

Public Member Functions

 Snapshot (const HasWriterSupport auto &metric, const SnapshotBuildOptions &options={})
 Create a snapshot by dumping metric via utils::statistics::Writer.
 Snapshot (WriterFuncRef writer, const SnapshotBuildOptions &options={})
 Create a snapshot by invoking writer.
template<std::convertible_to< std::string > Prefix = std::string>
 Snapshot (const HasWriterSupport auto &metric, Prefix &&prefix, std::vector< Label > require_labels={})
template<std::convertible_to< std::string > Prefix = std::string>
 Snapshot (WriterFuncRef writer, Prefix &&prefix, std::vector< Label > require_labels={})
std::vector< MetricView > AllMetrics () const
 Returns all metrics collected in this snapshot.
MetricValue SingleMetric (std::string path, std::vector< Label > require_labels={}) const
 Find a single metric by the given filter.
std::optional< MetricValue > SingleMetricOptional (std::string path, std::vector< Label > require_labels={}) const
 Find a single metric by the given filter.
bool EqualsNumerically (const Snapshot &other) const
 Collected metrics compared with a reference.
Copying and moving
See also
statistics_snapshot_view_lifetime
 Snapshot (const Snapshot &other)=default
 Snapshot (Snapshot &&other) noexcept=default
Snapshot & operator= (const Snapshot &other)=default
Snapshot & operator= (Snapshot &&other) noexcept=default

Static Public Member Functions

static Snapshot FromJson (const formats::json::Value &json, const SnapshotLoadOptions &options={})
 Load metrics from the JSON object produced by utils::statistics::ToJsonFormat.
static Snapshot FromLayeredJson (const formats::json::Value &json, const SnapshotLoadOptions &options={})
 Load metrics from a layered JSON object.

Constructor & Destructor Documentation

◆ Snapshot() [1/4]

utils::statistics::Snapshot::Snapshot ( const HasWriterSupport auto & metric,
const SnapshotBuildOptions & options = {} )
inlineexplicit

Create a snapshot by dumping metric via utils::statistics::Writer.

metric is any type with utils::statistics::Writer support. For simple metrics prefer a type with DumpMetric and pass it directly:

namespace {
struct SampleMetrics {
utils::statistics::RateCounter foo;
utils::statistics::RateCounter bar;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const SampleMetrics& metrics) {
writer["foo"] = metrics.foo;
writer["bar"].ValueWithLabels(metrics.bar, {"kind", "x"});
}
} // namespace
TEST(Snapshot, FromMetric) {
SampleMetrics metrics;
metrics.foo = utils::statistics::Rate{1};
metrics.bar = utils::statistics::Rate{2};
const utils::statistics::Snapshot snapshot{metrics};
EXPECT_EQ(snapshot.SingleMetric("foo"), utils::statistics::Rate{1});
EXPECT_EQ(snapshot.SingleMetric("bar", {{"kind", "x"}}), utils::statistics::Rate{2});
EXPECT_EQ(snapshot.SingleMetricOptional("missing"), std::nullopt);
}

When metrics are split into several subgroups (different paths or label sets), dump metric once and take child snapshots with utils::statistics::SnapshotBuildOptions instead of repeating paths and labels in every check:

namespace {
struct PathOnlySubgroup {
utils::statistics::RateCounter queued;
utils::statistics::RateCounter dropped;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const PathOnlySubgroup& subgroup) {
writer["queued"] = subgroup.queued;
writer["dropped"] = subgroup.dropped;
}
struct PathAndLabelSubgroup {
utils::statistics::RateCounter processed;
utils::statistics::RateCounter failed;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const PathAndLabelSubgroup& subgroup) {
writer["processed"] = subgroup.processed;
writer["failed"] = subgroup.failed;
}
struct SubgroupSampleMetrics {
PathOnlySubgroup ingress;
PathAndLabelSubgroup handler;
};
[[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const SubgroupSampleMetrics& metrics) {
writer["ingress"] = metrics.ingress;
writer["handler"].ValueWithLabels(metrics.handler, {"handler", "/create"});
}
} // namespace
TEST(Snapshot, SubgroupSlicesFromMetricSnapshot) {
SubgroupSampleMetrics metrics;
metrics.ingress.queued = utils::statistics::Rate{2};
metrics.ingress.dropped = utils::statistics::Rate{1};
metrics.handler.processed = utils::statistics::Rate{7};
metrics.handler.failed = utils::statistics::Rate{3};
const utils::statistics::Snapshot all{metrics};
all,
{.require_prefix = "ingress"},
};
EXPECT_EQ(ingress.SingleMetric("queued"), utils::statistics::Rate{2});
EXPECT_EQ(ingress.SingleMetric("dropped"), utils::statistics::Rate{1});
all,
{.require_prefix = "handler", .require_labels = {{"handler", "/create"}}},
};
EXPECT_EQ(handler.SingleMetric("processed"), utils::statistics::Rate{7});
EXPECT_EQ(handler.SingleMetric("failed"), utils::statistics::Rate{3});
}

Prefer passing the concrete metric (a struct with DumpMetric) or utils::statistics::MetricsStorage. utils::statistics::Storage also satisfies utils::statistics::HasWriterSupport, but is awkward in tests: utils::statistics::Storage::RegisterWriter is usually more boilerplate than passing the metric directly. Use Storage when the code under test is a non-component type that registers writers on Storage internally — then snapshot Storage to exercise that wiring. Example:

namespace {
class ToyMetrics {
public:
ToyMetrics(utils::ResourceScopeStorage& scopes, utils::statistics::Storage& storage) {
storage.RegisterWriter(scopes, "toy", [this](utils::statistics::Writer& writer) {
writer["foo"] = foo;
writer["bar"] = bar;
});
}
utils::statistics::RateCounter foo;
utils::statistics::RateCounter bar;
};
} // namespace
UTEST(Snapshot, FromStorage) {
utils::WithResourceScopes<ToyMetrics> toy(std::in_place, storage);
toy->foo = utils::statistics::Rate{1};
toy->bar = utils::statistics::Rate{2};
const utils::statistics::Snapshot snapshot{storage};
EXPECT_EQ(snapshot.SingleMetric("toy.foo"), utils::statistics::Rate{1});
EXPECT_EQ(snapshot.SingleMetric("toy.bar"), utils::statistics::Rate{2});
}

If the metric exposes a custom dump routine instead of DumpMetric, use the WriterFuncRef overload below.

Unlike production, a metric with an empty full path is allowed.

Parameters
optionsFilters and slicing mode; see utils::statistics::SnapshotBuildOptions. By default, the required prefix and labels are removed on collection.
Exceptions
utils::statistics::InvalidMetricErrorif two metrics have the same path and labels, or one metric lists the same label name more than once.
std::invalid_argumentif utils::statistics::SnapshotBuildOptions::require_prefix contains an empty string, or, with slicing enabled, ends with ., or a selected path becomes ambiguous after removing the prefix and ..
std::exceptionif the utils::statistics::Writer dump throws.

Definition at line 157 of file testing.hpp.

◆ Snapshot() [2/4]

utils::statistics::Snapshot::Snapshot ( WriterFuncRef writer,
const SnapshotBuildOptions & options = {} )
explicit

Create a snapshot by invoking writer.

Use this overload when the metric under test does not provide DumpMetric and you call a dedicated method (for example WriteStatistics) inside writer.

utils::statistics::SnapshotBuildOptions::require_prefix is not prepended to paths emitted by writer; it filters them according to utils::statistics::SnapshotBuildOptions::sliced. Unlike production, a metric with an empty full path is allowed.

Parameters
optionsFilters and slicing mode; see utils::statistics::SnapshotBuildOptions. By default, the required prefix and labels are removed on collection.
Exceptions
utils::statistics::InvalidMetricErrorif two metrics have the same path and labels, or one metric lists the same label name more than once.
std::invalid_argumentif utils::statistics::SnapshotBuildOptions::require_prefix contains an empty string, or, with slicing enabled, ends with ., or a selected path becomes ambiguous after removing the prefix and ..

◆ Snapshot() [3/4]

template<std::convertible_to< std::string > Prefix = std::string>
utils::statistics::Snapshot::Snapshot ( const HasWriterSupport auto & metric,
Prefix && prefix,
std::vector< Label > require_labels = {} )
inlineexplicit
Deprecated
Use the constructor taking utils::statistics::SnapshotBuildOptions instead. Uses slicing: prefix and require_labels are removed during collection. An empty prefix means no prefix filter.

Definition at line 183 of file testing.hpp.

◆ Snapshot() [4/4]

template<std::convertible_to< std::string > Prefix = std::string>
utils::statistics::Snapshot::Snapshot ( WriterFuncRef writer,
Prefix && prefix,
std::vector< Label > require_labels = {} )
inlineexplicit
Deprecated
Use the constructor taking utils::statistics::SnapshotBuildOptions instead. Uses slicing: prefix and require_labels are removed during collection. An empty prefix means no prefix filter.

Definition at line 195 of file testing.hpp.

Member Function Documentation

◆ AllMetrics()

std::vector< MetricView > utils::statistics::Snapshot::AllMetrics ( ) const

Returns all metrics collected in this snapshot.

Each element is a utils::statistics::MetricView; see statistics_snapshot_view_lifetime.

Returns stored paths and labels: when utils::statistics::SnapshotBuildOptions::sliced was true during collection, utils::statistics::SnapshotBuildOptions::require_prefix and utils::statistics::SnapshotBuildOptions::require_labels have already been removed. Otherwise, full paths and all labels are preserved.

Order: element order is not guaranteed; do not rely on it in tests or production checks.

The returned vector supports building a filtered utils::statistics::Snapshot through utils::statistics::Snapshot(WriterFuncRef), for example:

TEST(Snapshot, FilterByIteratingAllMetrics) {
const SampleMetrics metrics = MakePopulatedSampleMetrics();
const utils::statistics::Snapshot source{metrics};
const utils::statistics::Snapshot filtered{[&source](utils::statistics::Writer& writer) {
for (const utils::statistics::MetricView metric : source.AllMetrics()) {
if (metric.path != "foo") {
continue;
}
DumpMetric(writer, metric);
}
}};
EXPECT_EQ(std::ranges::distance(filtered.AllMetrics()), 1);
EXPECT_EQ(filtered.SingleMetric("foo"), utils::statistics::Rate{1});
EXPECT_EQ(filtered.SingleMetricOptional("bar", {{"kind", "x"}}), std::nullopt);
}

◆ EqualsNumerically()

bool utils::statistics::Snapshot::EqualsNumerically ( const Snapshot & other) const

Collected metrics compared with a reference.

Stored paths, labels and values are compared with those of other. Order does not matter. Constructor filters are not retained: utils::statistics::SnapshotBuildOptions::sliced affects equality through the stored paths and labels.

std::int64_t, double and utils::statistics::Rate compare as numbers: 4, 4.0 and Rate{4} are equal. A snapshot loaded from JSON can therefore match metrics collected in a test.

utils::statistics::Snapshot::SingleMetric still returns the stored utils::statistics::MetricValue. Its operator== keeps the type, so an integer metric is not equal to 4.0.

In a gtest, compare a snapshot with a reference via utils::statistics::EqualsNumerically(const Snapshot& expected) rather than this method, so the failure message shows both snapshots.

◆ FromJson()

Snapshot utils::statistics::Snapshot::FromJson ( const formats::json::Value & json,
const SnapshotLoadOptions & options = {} )
static

Load metrics from the JSON object produced by utils::statistics::ToJsonFormat.

  • Top-level keys are metric paths.
  • Each value is an array of {"type", "value", "labels"}.
  • GAUGE is stored as std::int64_t when formats::json::Value::IsInt64 returns true, otherwise as double. This includes integral floating-point values such as 4.0. Integers outside the std::int64_t range may lose precision when converted to double; they are not inferred to be utils::statistics::Rate.
  • RATE is utils::statistics::Rate.
  • HIST_RATE is a histogram (bounds, buckets, inf). sum, when present, is the total sum and is restored. Sums of individual buckets are not part of the format and are not restored.
    Parameters
    optionsPrepended to every path and added to every metric.
    TEST(Snapshot, FromJson) {
    "handler.requests": [
    {
    "type": "GAUGE",
    "value": 120,
    "labels": {"handler": "/orders", "http_code": "200"}
    }
    ],
    "handler.duration_seconds": [
    {"type": "GAUGE", "value": 1.5, "labels": {}}
    ],
    "db.queries": [
    {"type": "RATE", "value": 3, "labels": {"query": "select_order"}}
    ],
    "handler.timings": [
    {
    "type": "HIST_RATE",
    "labels": {},
    "value": {"bounds": [5.0, 10.0], "buckets": [2, 3], "inf": 1, "sum": 100.0}
    }
    ]
    })"));
    EXPECT_EQ(
    snapshot.SingleMetric("handler.requests", {{"handler", "/orders"}, {"http_code", "200"}}),
    std::int64_t{120}
    );
    EXPECT_EQ(snapshot.SingleMetric("handler.duration_seconds"), 1.5);
    EXPECT_EQ(snapshot.SingleMetric("db.queries", {{"query", "select_order"}}), utils::statistics::Rate{3});
    const auto timings = snapshot.SingleMetric("handler.timings").AsHistogram();
    EXPECT_EQ(timings.GetValueAt(0), 2);
    EXPECT_EQ(timings.GetValueAt(1), 3);
    EXPECT_EQ(timings.GetValueAtInf(), 1);
    EXPECT_EQ(timings.GetTotalSum(), 100.0);
    }
    Exceptions
    utils::statistics::InvalidMetricErrorif two metrics have the same path and labels, or one metric lists the same label name more than once.
    formats::json::ExceptionWithPathif json does not match the format above.

◆ FromLayeredJson()

Snapshot utils::statistics::Snapshot::FromLayeredJson ( const formats::json::Value & json,
const SnapshotLoadOptions & options = {} )
static

Load metrics from a layered JSON object.

  • Top-level keys are metric paths.
  • A nested key "name = value" (one space on each side of =) adds a label. The value may be empty. An empty name, extra spaces, or a missing space around = are rejected.
  • Label keys can be nested several levels deep, one label per level.
  • A field named labels is rejected. That field belongs to utils::statistics::Snapshot::FromJson.
  • A number is a GAUGE, stored as std::int64_t when formats::json::Value::IsInt64 returns true, otherwise as double, just as in utils::statistics::Snapshot::FromJson. Large integers outside the std::int64_t range may lose precision; use an explicit RATE object when that type is intended.
  • An object with bounds and buckets is a histogram. inf is required too. sum, when present, is the total sum and is restored. Sums of individual buckets are not part of the format and are not restored.
  • {"type": "RATE", "value": N} is also supported, and so are "GAUGE" and "HIST_RATE".
    namespace {
    struct DbMetrics {
    utils::statistics::RateCounter queries;
    };
    struct HandlerMetrics {
    utils::statistics::RateCounter requests;
    double duration_seconds{0};
    };
    struct ServiceMetrics {
    HandlerMetrics handler;
    DbMetrics db;
    };
    [[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const DbMetrics& metrics) {
    writer["queries"].ValueWithLabels(metrics.queries, {"query", "select_order"});
    }
    [[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const HandlerMetrics& metrics) {
    writer["requests"].ValueWithLabels(metrics.requests, {"http_code", "200"});
    writer["duration_seconds"] = metrics.duration_seconds;
    }
    [[maybe_unused]] void DumpMetric(utils::statistics::Writer& writer, const ServiceMetrics& metrics) {
    writer["handler"] = metrics.handler;
    writer["db"] = metrics.db;
    }
    } // namespace
    TEST(Snapshot, NestedMetricsMatchLayeredReference) {
    ServiceMetrics metrics;
    metrics.handler.requests = utils::statistics::Rate{120};
    metrics.handler.duration_seconds = 1.5;
    metrics.db.queries = utils::statistics::Rate{3};
    const utils::statistics::Snapshot snapshot{metrics};
    "handler.requests": {"http_code = 200": 120},
    "handler.duration_seconds": 1.5,
    "db.queries": {"query = select_order": 3}
    })"));
    EXPECT_THAT(snapshot, EqualsNumerically(reference));
    }
    Exceptions
    utils::statistics::InvalidMetricErrorif two metrics have the same path and labels, or one metric lists the same label name more than once.
    formats::json::ExceptionWithPathif json does not match the format above.

◆ SingleMetric()

MetricValue utils::statistics::Snapshot::SingleMetric ( std::string path,
std::vector< Label > require_labels = {} ) const

Find a single metric by the given filter.

path and require_labels refer to stored metrics, as returned by utils::statistics::Snapshot::AllMetrics. When utils::statistics::SnapshotBuildOptions::sliced is true, do not repeat the prefix or labels removed during collection. When it is false, use full paths and original labels. The constructor's filter is never reapplied to queries.

Parameters
pathThe path of the target metric.
require_labelsLabels that the target metric should have; additional labels are allowed.
Returns
The value of the single found metric.
See also
statistics_snapshot_view_lifetime
Exceptions
utils::statistics::MetricQueryErrorif none or multiple metrics are found.
TEST(Snapshot, SlicedAndUnslicedQueries) {
const auto writer = [](utils::statistics::Writer& out) {
out["api.requests"].ValueWithLabels(std::int64_t{2}, {{"service", "orders"}, {"code", "200"}});
};
sliced{writer, {.require_prefix = "api", .require_labels = {{"service", "orders"}}}};
EXPECT_EQ(sliced.SingleMetric("requests", {{"code", "200"}}), std::int64_t{2});
unsliced{writer, {.require_prefix = "api", .require_labels = {{"service", "orders"}}, .sliced = false}};
EXPECT_EQ(unsliced.SingleMetric("api.requests", {{"service", "orders"}, {"code", "200"}}), std::int64_t{2});
}

◆ SingleMetricOptional()

std::optional< MetricValue > utils::statistics::Snapshot::SingleMetricOptional ( std::string path,
std::vector< Label > require_labels = {} ) const

Find a single metric by the given filter.

Parameters
pathThe path of the target metric.
require_labelsLabels that the target metric should have; additional labels are allowed.
Returns
The value when one metric matches, or std::nullopt when none match.
See also
statistics_snapshot_view_lifetime
Exceptions
utils::statistics::MetricQueryErrorwhen more than one metric matches.
See also
utils::statistics::Snapshot::SingleMetric for sliced and unsliced query examples.

◆ DumpMetric

void DumpMetric ( Writer & writer,
const Snapshot & snapshot )
friend

Writes snapshot metrics through writer.

Writes the stored paths and labels of snapshot as is. If utils::statistics::SnapshotBuildOptions::sliced was true during collection, emits shortened paths and remaining labels; otherwise, emits full paths and all labels. Removed prefixes and labels are not restored. Makes Snapshot satisfy utils::statistics::HasWriterSupport.

◆ PrintTo

void PrintTo ( const Snapshot & data,
std::ostream *  )
friend

Support for gtest diagnostics for utils::statistics::Snapshot.

Warning
Never check the printed value programmatically! The string is not stable and may change, depending on the version of stdlib and userver.

Valid usage:

EXPECT_EQ(..., ...) << testing::PrintToString(snapshot);

Invalid usage:

std::ostringstream stream;
PrintTo(snapshot, &stream);
EXPECT_EQ(stream.str(), ...);

The documentation for this class was generated from the following file: