diff --git a/BUILD.bazel b/BUILD.bazel index 0a854130..e8a1e8d4 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -75,7 +75,12 @@ cc_library( "src/datadog/tags.h", "src/datadog/telemetry/configuration.cpp", "src/datadog/telemetry/log.h", + "src/datadog/telemetry/log_bin_index.cpp", + "src/datadog/telemetry/log_bin_index.h", + "src/datadog/telemetry/log_binned_distr.cpp", + "src/datadog/telemetry/log_binned_distr.h", "src/datadog/telemetry/metric_context.h", + "src/datadog/telemetry/metric_handle.cpp", "src/datadog/telemetry/telemetry.cpp", "src/datadog/telemetry/telemetry_impl.cpp", "src/datadog/telemetry/telemetry_impl.h", @@ -147,6 +152,7 @@ cc_library( "include/datadog/span_sampler_config.h", "include/datadog/string_view.h", "include/datadog/telemetry/configuration.h", + "include/datadog/telemetry/metric_handle.h", "include/datadog/telemetry/metrics.h", "include/datadog/telemetry/product.h", "include/datadog/telemetry/telemetry.h", diff --git a/CMakeLists.txt b/CMakeLists.txt index dddf6158..679f8b03 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -135,6 +135,7 @@ target_sources(dd-trace-cpp-objects include/datadog/remote_config/listener.h include/datadog/remote_config/product.h include/datadog/telemetry/configuration.h + include/datadog/telemetry/metric_handle.h include/datadog/telemetry/metrics.h include/datadog/telemetry/product.h include/datadog/telemetry/telemetry.h @@ -183,6 +184,9 @@ target_sources(dd-trace-cpp-objects PRIVATE src/datadog/common/hash.cpp src/datadog/telemetry/configuration.cpp + src/datadog/telemetry/log_bin_index.cpp + src/datadog/telemetry/log_binned_distr.cpp + src/datadog/telemetry/metric_handle.cpp src/datadog/telemetry/telemetry.cpp src/datadog/telemetry/telemetry_impl.cpp src/datadog/baggage.cpp diff --git a/include/datadog/telemetry/metric_handle.h b/include/datadog/telemetry/metric_handle.h new file mode 100644 index 00000000..3348bbd4 --- /dev/null +++ b/include/datadog/telemetry/metric_handle.h @@ -0,0 +1,440 @@ +#pragma once + +// Metrics registered once with all their tags. Recording a point then takes +// plain values: no tag strings are built, copied or hashed. A +// details::MetricRegistry creates the handles and takes their series. +// +// A struct describes the tags. Its static `tag_fields()` returns a std::tuple +// of tag() calls, which bind each field to a tag name. String tags come in two +// kinds: +// * values known in advance: an enum field. `tag_value_names(Enum{})`, found +// by argument-dependent lookup, returns a std::array with one name per +// value, in order. +// * values not known in advance: a TagString field. +// test/telemetry/test_metric_handle.cpp has examples. +// +// Telemetry does not collect these handles yet. + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace datadog::telemetry { + +// A tag value not known in advance, such as a version. Creating one stores +// the string in a global table; copying it copies a small number. The table +// holds at most 65535 strings. Later new strings all read as "other". +class TagString { + public: + static constexpr std::uint64_t id_count = std::uint64_t{1} << 16; + + // The empty string. + TagString() = default; + explicit TagString(tracing::StringView value); + + std::uint16_t id() const { return id_; } + std::string value() const; + + private: + std::uint16_t id_ = 0; +}; + +namespace details { + +// Identifies one series of a metric: one combination of its tag values. Each +// tag's value is multiplied by the tag's stride, and the results added. +using SeriesId = std::uint64_t; + +// One tag of a metric: reads the tag's field from a tag struct, and renders +// the tag's values. The tag struct's type is hidden, so that MetricBase does +// not depend on it. +class TagCodec { + public: + virtual ~TagCodec() = default; + // The value of the tag's field in `*tags`, as a number. `tags` points to the + // tag struct that the codec was made for. + virtual std::uint64_t read(const void* tags) const = 0; + // "name:value", or an empty string if the tag is not sent. + virtual std::string render(std::uint64_t value) const = 0; +}; + +std::string interned_string(std::uint64_t id); +// "name:value_name" for each value name. +std::vector render_names( + const std::string& name, const std::vector& value_names); + +// A bool or enum field. Value i renders as rendered[i]. +template +class NamedTag final : public TagCodec { + public: + NamedTag(Field Tags::*field, std::vector rendered) + : field_(field), rendered_(std::move(rendered)) {} + + std::uint64_t read(const void* tags) const override { + return static_cast(static_cast(tags)->*field_); + } + + std::string render(std::uint64_t value) const override { + return rendered_[value]; + } + + private: + Field Tags::*field_; + std::vector rendered_; +}; + +// An optional enum field. Value 0 is an empty field, which is not sent. Value +// i + 1 renders as rendered[i]. +template +class OptionalTag final : public TagCodec { + public: + OptionalTag(tracing::Optional Tags::*field, + std::vector rendered) + : field_(field), rendered_(std::move(rendered)) {} + + std::uint64_t read(const void* tags) const override { + const auto& value = static_cast(tags)->*field_; + return value ? static_cast(*value) + 1 : 0; + } + + std::string render(std::uint64_t value) const override { + return value == 0 ? std::string() : rendered_[value - 1]; + } + + private: + tracing::Optional Tags::*field_; + std::vector rendered_; +}; + +// A TagString field. The value is the string's id. +template +class StringTag final : public TagCodec { + public: + StringTag(TagString Tags::*field, std::string name) + : field_(field), name_(std::move(name)) {} + + std::uint64_t read(const void* tags) const override { + return (static_cast(tags)->*field_).id(); + } + + std::string render(std::uint64_t value) const override { + return name_ + ":" + interned_string(value); + } + + private: + TagString Tags::*field_; + std::string name_; +}; + +template +constexpr std::uint64_t enum_value_count() { + return std::tuple_size< + std::decay_t>::value; +} + +template +std::vector enum_value_names() { + std::vector names; + for (const char* name : tag_value_names(Enum{})) names.emplace_back(name); + return names; +} + +// One tag of a metric. Build it with tag(). The tag's values are numbered +// from 0 to ValueCount - 1. +template +struct TagField { + using TagStruct = Tags; + static constexpr std::uint64_t value_count = ValueCount; + std::unique_ptr codec; +}; + +// True if each combination of the fields' values has its own SeriesId. +template +constexpr bool fits_in_series_id(const std::tuple*) { + std::uint64_t combinations = 1; + for (std::uint64_t count : + std::initializer_list{Fields::value_count...}) { + if (count == 0 || + combinations > std::numeric_limits::max() / count) { + return false; + } + combinations *= count; + } + return true; +} + +// Tags of a metric that has only fixed tags. +struct NoTags { + static std::tuple<> tag_fields() { return {}; } +}; + +// One series of a metric: the metric, the series' tags and its value. +template +struct MetricSeries { + Metric metric; + std::vector tags; + typename Metric::Value value; +}; + +class MetricRegistry; + +// The integer of each series. Counters add the values recorded for a series; +// rates keep the last one. Thread-safe. +template +class SeriesIntegers { + public: + using Value = std::uint64_t; + + void record(SeriesId series, std::uint64_t value) { + std::lock_guard lock(mutex_); + Value& current = values_[series]; + current = keep_last ? value : current + value; + } + + std::vector> take() { + std::unordered_map taken; + { + std::lock_guard lock(mutex_); + taken.swap(values_); + } + return {taken.begin(), taken.end()}; + } + + private: + std::mutex mutex_; + std::unordered_map values_; +}; + +// The sketch of each series. Recording adds the value to it. Thread-safe. +class SeriesSketches { + public: + using Value = EncodedSketch; + + SeriesSketches(); + ~SeriesSketches(); + + void record(SeriesId series, std::uint64_t value); + std::vector> take(); + + private: + struct Impl; + std::unique_ptr impl_; +}; + +// Everything about a metric handle that depends neither on its Tags type nor +// on how it stores its values. +template +class MetricBase { + public: + // Removes the series recorded so far, and appends them to `series`. + virtual void take_series(std::vector>& series) = 0; + + protected: + // Handles are not deleted through MetricBase. + ~MetricBase() = default; + + MetricBase(Metric metric, std::vector fixed_tags, + std::vector value_counts, + std::vector> tags); + + const Metric& metric() const { return metric_; } + // The series of the tag struct `*tags`. Empty if a value is out of range. + tracing::Optional series_id(const void* tags) const; + // The fixed tags, then the tags of series `id` that are sent. + std::vector series_tags(SeriesId id) const; + + private: + Metric metric_; + std::vector fixed_tags_; + std::vector value_counts_; + std::vector> tags_; + std::vector strides_; +}; + +// A metric registered with all its tags. Only a MetricRegistry creates them. +// `Store` keeps the value of each series: record() combines a new value into +// it, and take() removes them. record() is thread-safe. +template +class MetricHandle final : public MetricBase { + static_assert( + fits_in_series_id(static_cast(nullptr)), + "Too many combinations of tag values for a 64-bit SeriesId"); + static_assert( + std::is_same_v() + .take())::value_type::second_type, + typename Metric::Value>, + "The store's values must have the metric's Value type"); + + public: + void record(const Tags& tags, std::uint64_t value) { + if (const auto series = this->series_id(&tags)) { + store_.record(*series, value); + } + } + + void take_series(std::vector>& series) override { + for (auto& [id, value] : store_.take()) { + series.push_back( + {this->metric(), this->series_tags(id), std::move(value)}); + } + } + + private: + friend class MetricRegistry; + + MetricHandle(Metric metric, std::vector fixed_tags) + : MetricHandle(std::move(metric), std::move(fixed_tags), + Tags::tag_fields()) {} + + // The codecs read `Tags` structs, so every field must be one of Tags. + template + MetricHandle(Metric metric, std::vector fixed_tags, + std::tuple fields) + : MetricBase(std::move(metric), std::move(fixed_tags), + {Fields::value_count...}, + codecs(std::move(fields))) { + static_assert((std::is_same_v && ...), + "tag_fields() must only bind fields of its own struct"); + } + + template + static std::vector> codecs( + std::tuple fields) { + std::vector> codecs; + std::apply( + [&codecs](auto&... field) { + (codecs.push_back(std::move(field.codec)), ...); + }, + fields); + return codecs; + } + + Store store_; +}; + +} // namespace details + +template +details::TagField tag(const std::string& name, bool Tags::*field) { + return {std::make_unique>( + field, details::render_names(name, {"false", "true"}))}; +} + +template >> +details::TagField()> tag( + const std::string& name, Enum Tags::*field) { + return {std::make_unique>( + field, details::render_names(name, details::enum_value_names()))}; +} + +// An empty field is not sent. +template +details::TagField() + 1> tag( + const std::string& name, tracing::Optional Tags::*field) { + return {std::make_unique>( + field, details::render_names(name, details::enum_value_names()))}; +} + +template +details::TagField tag(const std::string& name, + TagString Tags::*field) { + return {std::make_unique>(field, name)}; +} + +// Recording a value adds it to the series' count. +template +using CounterHandle = + details::MetricHandle>; + +// Recording a value replaces the series' rate. +template +using RateHandle = + details::MetricHandle>; + +// Recording a value adds it to the series' sketch. +template +using DistributionHandle = + details::MetricHandle; + +namespace details { + +// Creates metric handles, and takes the series of those still in use. The +// registry holds only weak references: a handle that its caller drops is +// forgotten, with the values it recorded since the last take. Creating and +// taking lock the registry; recording does not. +class MetricRegistry { + public: + template + std::shared_ptr> counter( + Counter metric, std::vector fixed_tags = {}) { + return add>(std::move(metric), std::move(fixed_tags)); + } + + template + std::shared_ptr> rate( + Rate metric, std::vector fixed_tags = {}) { + return add>(std::move(metric), std::move(fixed_tags)); + } + + template + std::shared_ptr> distribution( + Distribution metric, std::vector fixed_tags = {}) { + return add>(std::move(metric), + std::move(fixed_tags)); + } + + // Removes and returns the series that the handles of `Metric` recorded + // since the last call. Forgets the handles that were dropped. + template + std::vector> take() { + std::vector> series; + std::lock_guard lock(mutex_); + auto& handles = std::get>(handles_); + for (const auto& weak_handle : handles) { + if (const auto handle = weak_handle.lock()) handle->take_series(series); + } + handles.erase(std::remove_if(handles.begin(), handles.end(), + [](const auto& weak_handle) { + return weak_handle.expired(); + }), + handles.end()); + return series; + } + + private: + template + using Handles = std::vector>>; + + template + std::shared_ptr add(Metric metric, + std::vector fixed_tags) { + std::shared_ptr handle( + new Handle(std::move(metric), std::move(fixed_tags))); + std::lock_guard lock(mutex_); + std::get>(handles_).push_back(handle); + return handle; + } + + std::mutex mutex_; + std::tuple, Handles, Handles> handles_; +}; + +} // namespace details +} // namespace datadog::telemetry diff --git a/include/datadog/telemetry/metrics.h b/include/datadog/telemetry/metrics.h index 3cca54e3..d83beeb4 100644 --- a/include/datadog/telemetry/metrics.h +++ b/include/datadog/telemetry/metrics.h @@ -1,6 +1,8 @@ #pragma once +#include #include +#include namespace datadog { namespace telemetry { @@ -9,11 +11,18 @@ namespace details { enum class MetricType : char { counter, rate, distribution }; } +/// A DDSketch protobuf message, as bytes. +using EncodedSketch = std::string; + /// TODO: pre-compute hash? template struct Metric final { /// The type of the metric. static constexpr details::MetricType type = T; + /// The value of one series: a count or a rate, or the sketch of a + /// distribution. + using Value = std::conditional_t; /// The name of the metric that will be published. A transformation occurs /// based on the name and whether it is "common" or "language-specific" when /// it is recorded. diff --git a/include/datadog/telemetry/telemetry.h b/include/datadog/telemetry/telemetry.h index c0da7bb6..0cb6497f 100644 --- a/include/datadog/telemetry/telemetry.h +++ b/include/datadog/telemetry/telemetry.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -115,12 +116,41 @@ void error(std::string message); void error(std::string message, std::string stacktrace); } // namespace log +namespace details { + +/// The registry of the running telemetry, or null if telemetry is not running. +MetricRegistry* metric_registry(); + +/// Calls `create` with the registry of the running telemetry. If telemetry is +/// not running, uses a registry that is never sent instead. +template +auto create_handle(const Create& create) { + if (MetricRegistry* registry = metric_registry()) return create(*registry); + MetricRegistry never_sent; + return create(never_sent); +} + +} // namespace details + /// The `counter` namespace provides functions to track values. /// Counters can be useful for tracking the total number of an event occurring /// in one time interval. For example, the amount of requests, errors or jobs /// processed every 10 seconds. namespace counter { +/// Creates a counter handle, sent by telemetry. Call it after `init`. Without +/// telemetry, the handle records values that are never sent. +/// +/// @param `metric` the counter. +/// @param `fixed_tags` tags sent with every point, as "name:value". +template +std::shared_ptr> create( + Counter metric, std::vector fixed_tags = {}) { + return details::create_handle([&](details::MetricRegistry& registry) { + return registry.counter(std::move(metric), std::move(fixed_tags)); + }); +} + /// Increments the specified counter by 1. /// /// @param `counter` the counter to increment. @@ -164,6 +194,19 @@ void set(const Counter& counter, const std::vector& tags, /// one time interval. For example, the number of requests per second. namespace rate { +/// Creates a rate handle, sent by telemetry. Call it after `init`. Without +/// telemetry, the handle records values that are never sent. +/// +/// @param `metric` the rate. +/// @param `fixed_tags` tags sent with every point, as "name:value". +template +std::shared_ptr> create( + Rate metric, std::vector fixed_tags = {}) { + return details::create_handle([&](details::MetricRegistry& registry) { + return registry.rate(std::move(metric), std::move(fixed_tags)); + }); +} + /// Sets the rate to a specific value. /// /// @param `rate` the rate to update. @@ -184,6 +227,21 @@ void set(const Rate& rate, const std::vector&, uint64_t value); /// payload sizes. namespace distribution { +/// Creates a distribution handle, sent by telemetry as DDSketches. Call it +/// after `init`. Without telemetry, the handle records values that are never +/// sent. +/// +/// @param `metric` the distribution. +/// @param `fixed_tags` tags sent with every series, as "name:value". +template +std::shared_ptr> create( + Distribution metric, std::vector fixed_tags = {}) { + return details::create_handle([&](details::MetricRegistry& registry) { + return registry.distribution(std::move(metric), + std::move(fixed_tags)); + }); +} + /// Adds a value to the distribution. /// /// @param `distribution` the distribution to update. diff --git a/src/datadog/base64.cpp b/src/datadog/base64.cpp index 35aa4833..fb52f17c 100644 --- a/src/datadog/base64.cpp +++ b/src/datadog/base64.cpp @@ -28,6 +28,12 @@ constexpr uint8_t k_base64_table[] = { _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _}; +namespace { + +void append_encoded_group(std::string& output, StringView group); + +} // namespace + std::string base64_decode(StringView input) { const size_t in_size = input.size(); @@ -84,5 +90,39 @@ std::string base64_decode(StringView input) { return output; } +std::string base64_encode(StringView input) { + std::string output; + output.reserve((input.size() + 2) / 3 * 4); + for (size_t offset = 0; offset < input.size(); offset += 3) { + append_encoded_group(output, input.substr(offset, 3)); + } + return output; +} + +namespace { + +constexpr char k_base64_alphabet[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// Appends the 4 characters for a group of 1 to 3 bytes. Missing bytes become +// '=' padding. +void append_encoded_group(std::string& output, StringView group) { + uint32_t bits = 0; + for (size_t position = 0; position < 3; ++position) { + bits <<= 8; + if (position < group.size()) { + bits |= static_cast(group[position]); + } + } + const size_t encoded_chars = group.size() + 1; + for (size_t position = 0; position < 4; ++position) { + const uint32_t sextet = (bits >> (18 - 6 * position)) & 0x3F; + output.push_back(position < encoded_chars ? k_base64_alphabet[sextet] + : '='); + } +} + +} // namespace + } // namespace tracing } // namespace datadog diff --git a/src/datadog/base64.h b/src/datadog/base64.h index aa56c925..4064722f 100644 --- a/src/datadog/base64.h +++ b/src/datadog/base64.h @@ -11,5 +11,8 @@ namespace tracing { // `input` is not padded, then return the empty string instead. std::string base64_decode(StringView input); +// Return the padded base64 encoding of the specified `input`. +std::string base64_encode(StringView input); + } // namespace tracing } // namespace datadog diff --git a/src/datadog/telemetry/log_bin_index.cpp b/src/datadog/telemetry/log_bin_index.cpp new file mode 100644 index 00000000..3062dcc6 --- /dev/null +++ b/src/datadog/telemetry/log_bin_index.cpp @@ -0,0 +1,245 @@ +#include "log_bin_index.h" + +#include +#include +#include +#include + +namespace datadog::telemetry::log_bins { +namespace { + +// Finds bins without computing a logarithm. +// +// A positive double is 2^e × (1 + f). The fraction f is in [0, 1) and is +// stored in 52 bits. The top 6 bits of f give an integer m from 0 to 63. +// This means f is in [m/64, (m + 1)/64). The exponent e and m form a key. +// For example, between 1 and 2, the key with m = 0 holds [1, 1.015625). +// The key with m = 1 holds [1.015625, 1.03125). +// +// A key's doubles go from 2^e × (1 + m/64) up to, but excluding, +// 2^e × (1 + (m + 1)/64). Its largest and smallest doubles satisfy +// largest/smallest < (65 + m)/(64 + m) <= 65/64. +// The fraction (65 + m)/(64 + m) equals 65/64 only when m = 0. +// So every key has largest/smallest strictly below 65/64. +// The bin ratio is 65/64. Neighbouring bin edges are 65/64 apart. +// So at most one bin edge falls inside a key. Its doubles are in one bin +// or in two neighbouring bins. +// +// This holds for the exact logarithm. The bins come from a rounded `log`, +// so two edges may be a few doubles less than 65/64 apart. When m = 0, +// a key spans almost exactly 65/64. If an edge fell just after its first +// double, the next edge could also fall inside the key. Its doubles would +// then be in three bins. +// +// fill_entry() checks that each key holds doubles in at most two neighbouring +// bins. If the check fails, every value takes the slow path. +// +// For each key, the table stores the bin of its first double and where the +// next bin starts. It stores that start as the remaining 46 mantissa bits. +// Finding a bin is then one load and one compare. The table is filled with +// reference_bin_index(), so the table and reference_bin_index() always give +// the same bin. +// +// The table covers [2^-30, 2^65). Other values take the slow path. +class BinTable { + public: + static const BinTable& instance(); + + // Sets `bin` and returns true if the table covers the double `bits`. + bool find_bin(std::uint64_t bits, BinIndex& bin) const; + + // False if the table could not be built, and every value takes the slow + // path. + bool usable() const { return usable_keys_ == key_count; } + + private: + // A key is the exponent and the top 6 mantissa bits of a positive double. + static constexpr int key_shift = 52 - 6; + static constexpr std::uint64_t low_bits_mask = + (std::uint64_t{1} << key_shift) - 1; + static constexpr std::uint64_t first_key = std::uint64_t{1023 - 30} << 6; + static constexpr std::uint64_t key_count = std::uint64_t{30 + 65} << 6; + + static constexpr int edge_bits = key_shift + 1; + static constexpr int base_offset_bits = 64 - edge_bits; + // An edge value past every low bits, for keys whose doubles are all in one + // bin. + static constexpr std::uint64_t no_edge = low_bits_mask + 1; + + struct Entry { + // Low bits of the first double of the next bin, or `no_edge` if the next + // bin starts after the key. + std::uint64_t edge : edge_bits; + // Bin of the key's first double, minus `first_bin_`. + std::uint64_t base_offset : base_offset_bits; + }; + static_assert(sizeof(Entry) == sizeof(std::uint64_t)); + + BinTable(); + bool fill_entry(std::uint64_t key); + + BinIndex first_bin_; + // `key_count`, or 0 if the table could not be built. + std::uint64_t usable_keys_; + std::array entries_{}; +}; + +// Sets round-to-nearest while it lives, then restores the caller's mode. +class RoundToNearest { + public: + RoundToNearest() : saved_mode_(std::fegetround()) { + std::fesetround(FE_TONEAREST); + } + ~RoundToNearest() { std::fesetround(saved_mode_); } + RoundToNearest(const RoundToNearest&) = delete; + RoundToNearest& operator=(const RoundToNearest&) = delete; + + private: + int saved_mode_; +}; + +double log_multiplier(); +std::uint64_t find_edge(BinIndex bin, std::uint64_t below, + std::uint64_t at_or_above); +void narrow_around_guess(BinIndex bin, std::uint64_t& below, + std::uint64_t& at_or_above); +std::uint64_t to_bits(double value); +double from_bits(std::uint64_t bits); + +} // namespace + +BinIndex bin_index(double value) { + BinIndex bin; + if (BinTable::instance().find_bin(to_bits(value), bin)) return bin; + return reference_bin_index(value); +} + +bool fast_table_built() { return BinTable::instance().usable(); } + +BinIndex reference_bin_index(double value) { + // Checks the bits, because -ffast-math can remove std::isnan() and friends. + const std::uint64_t bits = to_bits(value); + const bool not_finite = ((bits >> 52) & 0x7ff) == 0x7ff; + const bool below_zero = (bits >> 63) != 0 && (bits << 1) != 0; + if (not_finite || below_zero) return rejected_value; + if (value < zero_threshold) return zero_bin; + + // One rounding for the multiplication and the addition. Separate roundings + // would depend on whether the compiler fuses them. + const double scaled_log = + std::fma(std::log(value), log_multiplier(), bin_index_shift); + return static_cast(std::floor(scaled_log)); +} + +namespace { + +// The table is built at run time, with the local `log`. C libraries do not +// all round `log` the same way, so a table built elsewhere could differ. +const BinTable& BinTable::instance() { + static const BinTable table; + return table; +} + +bool BinTable::find_bin(std::uint64_t bits, BinIndex& bin) const { + // Zero, negative values, NaN and infinities give keys out of range too. + const std::uint64_t key = (bits >> key_shift) - first_key; + if (key >= usable_keys_) return false; + + const Entry entry = entries_[key]; + const bool past_edge = (bits & low_bits_mask) >= entry.edge; + bin = first_bin_ + static_cast(entry.base_offset) + + static_cast(past_edge); + return true; +} + +// The first caller may have changed the rounding mode. The table must not +// depend on it. +BinTable::BinTable() : first_bin_(0), usable_keys_(key_count) { + const RoundToNearest rounding; + first_bin_ = reference_bin_index(from_bits(first_key << key_shift)); + for (std::uint64_t key = 0; key < key_count; ++key) { + if (!fill_entry(key)) { + usable_keys_ = 0; + return; + } + } +} + +bool BinTable::fill_entry(std::uint64_t key) { + const std::uint64_t first_bits = (first_key + key) << key_shift; + const std::uint64_t last_bits = first_bits | low_bits_mask; + const BinIndex base_bin = reference_bin_index(from_bits(first_bits)); + const BinIndex last_bin = reference_bin_index(from_bits(last_bits)); + const std::int64_t base_offset = std::int64_t{base_bin} - first_bin_; + if (base_offset < 0 || base_offset >> base_offset_bits != 0 || + last_bin < base_bin || last_bin > base_bin + 1) { + return false; + } + + Entry& entry = entries_[key]; + entry.base_offset = static_cast(base_offset); + entry.edge = no_edge; + if (last_bin > base_bin) { + entry.edge = find_edge(last_bin, first_bits, last_bits) - first_bits; + } + return true; +} + +// Same formula as libdatadog: 1 / ln(bin_ratio). +double log_multiplier() { + static const double multiplier = 1.0 / std::log(bin_ratio); + return multiplier; +} + +// Returns the bits of the smallest double whose bin is `bin`. Expects the bin +// of `below` to be lower than `bin`, and the bin of `at_or_above` not to be. +std::uint64_t find_edge(BinIndex bin, std::uint64_t below, + std::uint64_t at_or_above) { + narrow_around_guess(bin, below, at_or_above); + while (at_or_above - below > 1) { + const std::uint64_t middle = below + (at_or_above - below) / 2; + if (reference_bin_index(from_bits(middle)) >= bin) { + at_or_above = middle; + } else { + below = middle; + } + } + return at_or_above; +} + +// Moves the bounds close to the edge computed with `exp`, so that the search +// needs few steps. The bounds keep their meaning. +void narrow_around_guess(BinIndex bin, std::uint64_t& below, + std::uint64_t& at_or_above) { + const double guess_value = + std::exp((bin - bin_index_shift) / log_multiplier()); + const std::uint64_t guess = to_bits(guess_value); + if (guess <= below || guess >= at_or_above) return; + + for (std::uint64_t width = 64; width < at_or_above - below; width *= 64) { + const std::uint64_t low = guess > width ? guess - width : 0; + const std::uint64_t high = guess + width; + if (low > below && reference_bin_index(from_bits(low)) < bin) { + below = low; + } + if (high < at_or_above && reference_bin_index(from_bits(high)) >= bin) { + at_or_above = high; + } + if (below == low && at_or_above == high) return; + } +} + +std::uint64_t to_bits(double value) { + std::uint64_t bits; + std::memcpy(&bits, &value, sizeof bits); + return bits; +} + +double from_bits(std::uint64_t bits) { + double value; + std::memcpy(&value, &bits, sizeof value); + return value; +} + +} // namespace +} // namespace datadog::telemetry::log_bins diff --git a/src/datadog/telemetry/log_bin_index.h b/src/datadog/telemetry/log_bin_index.h new file mode 100644 index 00000000..cc8b0b74 --- /dev/null +++ b/src/datadog/telemetry/log_bin_index.h @@ -0,0 +1,39 @@ +#pragma once + +// Bin index of the log-binned distributions. See log_binned_distr.h for the +// mapping. + +#include +#include + +namespace datadog::telemetry::log_bins { + +// The number of a bin. Same type as LogBinnedDistr's private BinIndex. +using BinIndex = std::int32_t; + +// Each bin's upper edge is this many times its lower edge. +inline constexpr double bin_ratio = 65.0 / 64.0; +// Shift so that 1e-9 falls in bin 1. +inline constexpr double bin_index_shift = 1338.5; +// Values below this, zero included, are counted apart. +inline constexpr double zero_threshold = + std::numeric_limits::min() * bin_ratio; + +// Special results of bin_index(). +inline constexpr BinIndex zero_bin = std::numeric_limits::min(); +inline constexpr BinIndex rejected_value = zero_bin + 1; + +// Returns the bin of `value`. Returns `zero_bin` for values below +// `zero_threshold`, and `rejected_value` for negative values, NaN and +// infinities. Same result as reference_bin_index(), but faster. +BinIndex bin_index(double value); + +// Computes the bin as floor(ln(value) × m + bin_index_shift), with +// m = 1 / ln(bin_ratio). The multiplication and the addition are rounded once. +// Declared here for the tests. The library only uses bin_index(). +BinIndex reference_bin_index(double value); + +// Returns true if the fast table was built. Declared here for the tests. +bool fast_table_built(); + +} // namespace datadog::telemetry::log_bins diff --git a/src/datadog/telemetry/log_binned_distr.cpp b/src/datadog/telemetry/log_binned_distr.cpp new file mode 100644 index 00000000..454c49ab --- /dev/null +++ b/src/datadog/telemetry/log_binned_distr.cpp @@ -0,0 +1,218 @@ +#include "log_binned_distr.h" + +#include +#include +#include + +#include "log_bin_index.h" + +namespace datadog::telemetry { +namespace { + +using BinIndex = log_bins::BinIndex; + +constexpr std::int32_t max_bins = 2048; +constexpr BinIndex no_clamp = std::numeric_limits::min(); +constexpr std::uint32_t min_window_size = 64; +constexpr std::uint32_t max_window_size = 2 * max_bins; + +std::string encode_mapping(); +std::string encode_bin(BinIndex bin, std::uint64_t count); +void append_message(std::string& out, std::uint32_t field, + const std::string& message); +void append_double(std::string& out, std::uint32_t field, double value); +void append_varint(std::string& out, std::uint64_t value); +std::uint32_t zigzag(std::int32_t value); + +} // namespace + +bool LogBinnedDistr::record(double value) { + static_assert(std::is_same_v); + const BinIndex bin = log_bins::bin_index(value); + if (bin == log_bins::rejected_value) return false; + + std::lock_guard lock(mutex_); + if (bin == log_bins::zero_bin) { + ++zero_count_; + } else { + add_to_bin(bin); + } + return true; +} + +// DDSketch message: mapping = 1, positiveValues = 2, negativeValues = 3, +// zeroCount = 4. +std::string LogBinnedDistr::encode_protobuf() const { + std::lock_guard lock(mutex_); + std::string sketch; + append_message(sketch, 1, encode_mapping()); + append_message(sketch, 2, encode_bins()); + append_message(sketch, 3, ""); + if (zero_count_ != 0) { + append_double(sketch, 4, static_cast(zero_count_)); + } + return sketch; +} + +void LogBinnedDistr::add_to_bin(BinIndex bin) { + bin = std::max(bin, clamp_floor_); + const std::uint32_t position = + static_cast(bin) - static_cast(lowest_bin_); + if (position < bin_span_) { + ++count_at(bin); + return; + } + extend_range(bin); + const bool full = bin_span_ == static_cast(max_bins); + clamp_floor_ = full ? lowest_bin_ : no_clamp; +} + +// Same rules as libdatadog's LowCollapsingDenseStore. +void LogBinnedDistr::extend_range(BinIndex bin) { + if (bin_span_ == 0) { + start_range(bin); + return; + } + const BinIndex highest = + lowest_bin_ + static_cast(bin_span_) - 1; + if (bin < lowest_bin_) { + extend_down(bin, highest); + } else { + extend_up(bin, highest); + } +} + +void LogBinnedDistr::start_range(BinIndex bin) { + cover(bin, bin); + lowest_bin_ = bin; + bin_span_ = 1; + ++count_at(bin); +} + +// The range grows down while it has room. Values below it go to its lowest +// bin. +void LogBinnedDistr::extend_down(BinIndex bin, BinIndex highest) { + const BinIndex new_lowest = std::max(bin, highest - (max_bins - 1)); + cover(new_lowest, highest); + lowest_bin_ = new_lowest; + bin_span_ = static_cast(highest - new_lowest + 1); + ++count_at(new_lowest); +} + +// The range grows up. If it gets too wide, its lowest bins are merged into +// the new lowest bin. +void LogBinnedDistr::extend_up(BinIndex bin, BinIndex highest) { + const BinIndex new_lowest = std::max(lowest_bin_, bin - (max_bins - 1)); + const std::uint64_t merged = + take_counts(lowest_bin_, std::min(new_lowest - 1, highest)); + cover(new_lowest, bin); + lowest_bin_ = new_lowest; + bin_span_ = static_cast(bin - new_lowest + 1); + count_at(new_lowest) += merged; + ++count_at(bin); +} + +// Sets the counts of bins [lowest, highest] to zero and returns their sum. +std::uint64_t LogBinnedDistr::take_counts(BinIndex lowest, BinIndex highest) { + std::uint64_t sum = 0; + for (BinIndex bin = lowest; bin <= highest; ++bin) { + std::uint64_t& count = count_at(bin); + sum += count; + count = 0; + } + return sum; +} + +// Makes the window cover bins [lowest, highest]. The new window has room on +// both sides, so that the range can grow without moving it each time. +void LogBinnedDistr::cover(BinIndex lowest, BinIndex highest) { + const BinIndex window_end = + window_start_ + static_cast(counts_.size()); + if (!counts_.empty() && lowest >= window_start_ && highest < window_end) { + return; + } + + const std::uint32_t needed = static_cast(highest - lowest + 1); + const std::uint32_t size = + std::clamp(2 * needed, min_window_size, max_window_size); + const BinIndex start = + lowest - static_cast((size - needed) / 2); + std::vector counts(size); + const BinIndex copy_start = std::max(window_start_, start); + const BinIndex copy_end = + std::min(window_end, start + static_cast(size)); + for (BinIndex bin = copy_start; bin < copy_end; ++bin) { + counts[static_cast(bin - start)] = count_at(bin); + } + counts_.swap(counts); + window_start_ = start; +} + +std::uint64_t& LogBinnedDistr::count_at(BinIndex bin) { + return counts_[static_cast(bin - window_start_)]; +} + +// Store message: binCounts = 1 (map), with only the bins that +// are not empty. +std::string LogBinnedDistr::encode_bins() const { + std::string store; + for (std::uint32_t position = 0; position < bin_span_; ++position) { + const BinIndex bin = lowest_bin_ + static_cast(position); + const std::uint64_t count = + counts_[static_cast(bin - window_start_)]; + if (count != 0) append_message(store, 1, encode_bin(bin, count)); + } + return store; +} + +namespace { + +// IndexMapping message: gamma = 1, indexOffset = 2. The interpolation is +// NONE, the default, so it is left out. +std::string encode_mapping() { + std::string mapping; + append_double(mapping, 1, log_bins::bin_ratio); + append_double(mapping, 2, log_bins::bin_index_shift); + return mapping; +} + +// Map entry message: key = 1 (sint32), value = 2 (double). +std::string encode_bin(BinIndex bin, std::uint64_t count) { + std::string entry; + append_varint(entry, (1 << 3) | 0); + append_varint(entry, zigzag(bin)); + append_double(entry, 2, static_cast(count)); + return entry; +} + +void append_message(std::string& out, std::uint32_t field, + const std::string& message) { + append_varint(out, (field << 3) | 2); + append_varint(out, message.size()); + out += message; +} + +void append_double(std::string& out, std::uint32_t field, double value) { + append_varint(out, (field << 3) | 1); + std::uint64_t bits; + std::memcpy(&bits, &value, sizeof bits); + for (int byte = 0; byte < 8; ++byte) { + out.push_back(static_cast((bits >> (8 * byte)) & 0xff)); + } +} + +void append_varint(std::string& out, std::uint64_t value) { + while (value >= 0x80) { + out.push_back(static_cast((value & 0x7f) | 0x80)); + value >>= 7; + } + out.push_back(static_cast(value)); +} + +std::uint32_t zigzag(std::int32_t value) { + const std::uint32_t shifted = static_cast(value) << 1; + return value < 0 ? ~shifted : shifted; +} + +} // namespace +} // namespace datadog::telemetry diff --git a/src/datadog/telemetry/log_binned_distr.h b/src/datadog/telemetry/log_binned_distr.h new file mode 100644 index 00000000..144fd9c0 --- /dev/null +++ b/src/datadog/telemetry/log_binned_distr.h @@ -0,0 +1,81 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace datadog::telemetry { + +// A distribution whose bins form a geometric series, compatible with +// DDSketch. Bin i covers [low(i), γ × low(i)), so each bin's upper edge is γ +// times its lower edge. +// +// Every value in bin i is reported as the same bin value x̂(i). It is the +// harmonic mean of the bin's edges: +// +// x̂ = 2 × low × γ low / (low + γ low) = low × (1 + α) +// +// This puts x̂ at the same relative error from both edges. So for any value x +// in the bin, |x̂ - x| / x <= α. +// +// Design parameters: +// * The maximum relative error, α = 1/129. That is about 2.1 significant +// digits. The bin ratio follows from it: γ = (1 + α) / (1 - α) = 65/64. +// * Where the bins start. Bin 1 is the bin that holds 1e-9, the smallest value +// the backend's sketches use. So the bin number is +// +// i(x) = floor(log_γ(x) + s), with s = 1 - floor(log_γ(1e-9)) + 0.5 +// +// which gives s = 1338.5. Values between 0 and 1e-9 get bins below 1. +// +// Other properties: +// * Values below DBL_MIN × γ, zero included, are counted apart, in the zero +// count. Negative values, NaN and infinities are rejected. +// * At most 2048 bins are kept: i_max - i_min <= 2047. When a new value would +// go past that, the lowest bins are merged into the lowest bin kept. Values +// below the range go to that lowest bin too. The highest bins are never +// merged. +// * `log` rounds, so about one value in 10^12, right next to a bin edge, goes +// to the neighbouring bin. The worst relative error is then +// α + 4 × 10^-13. This also moves a few bin edges by a double or so between +// C libraries, and from libdatadog's. +// * All member functions are thread-safe. Each distribution has its own lock. +class LogBinnedDistr { + public: + // Returns false if the value is rejected. + bool record(double value); + + // Returns the distribution as a serialized DDSketch protobuf message. The + // bins are in the sparse form (`binCounts`). + std::string encode_protobuf() const; + + private: + // The number of a bin, i(x) above. Same type as log_bins::BinIndex. + using BinIndex = std::int32_t; + + void add_to_bin(BinIndex bin); + void extend_range(BinIndex bin); + void start_range(BinIndex bin); + void extend_down(BinIndex bin, BinIndex highest); + void extend_up(BinIndex bin, BinIndex highest); + std::uint64_t take_counts(BinIndex lowest, BinIndex highest); + void cover(BinIndex lowest, BinIndex highest); + std::uint64_t& count_at(BinIndex bin); + std::string encode_bins() const; + + mutable std::mutex mutex_; + // counts_[k] is the count of bin window_start_ + k. Bins outside the range + // [lowest_bin_, lowest_bin_ + bin_span_) are always zero. + std::vector counts_; + BinIndex window_start_ = 0; + BinIndex lowest_bin_ = 0; + std::uint32_t bin_span_ = 0; + // The lowest bin, once the range holds the maximum number of bins. Lower + // values are moved up to it without a branch. + BinIndex clamp_floor_ = std::numeric_limits::min(); + std::uint64_t zero_count_ = 0; +}; + +} // namespace datadog::telemetry diff --git a/src/datadog/telemetry/metric_handle.cpp b/src/datadog/telemetry/metric_handle.cpp new file mode 100644 index 00000000..f1e0574e --- /dev/null +++ b/src/datadog/telemetry/metric_handle.cpp @@ -0,0 +1,163 @@ +#include + +#include "log_binned_distr.h" + +namespace datadog::telemetry { +namespace { + +// Id of every new string once the table is full. +constexpr std::uint16_t overflow_id = 0xFFFF; + +// The strings of TagString values. Id 0 is the empty string. +class StringTable { + public: + static StringTable& instance() { + static StringTable table; + return table; + } + + std::uint16_t intern(tracing::StringView value); + std::string value(std::uint16_t id); + + private: + StringTable() { add(""); } + std::uint16_t add(const std::string& value); + + std::mutex mutex_; + std::vector strings_; + std::unordered_map ids_; +}; + +std::vector series_id_strides( + const std::vector& value_counts); + +} // namespace + +TagString::TagString(tracing::StringView value) + : id_(StringTable::instance().intern(value)) {} + +std::string TagString::value() const { return details::interned_string(id_); } + +namespace details { + +std::string interned_string(std::uint64_t id) { + return StringTable::instance().value(static_cast(id)); +} + +std::vector render_names( + const std::string& name, const std::vector& value_names) { + std::vector rendered; + for (const std::string& value_name : value_names) { + rendered.push_back(name + ":" + value_name); + } + return rendered; +} + +template +MetricBase::MetricBase( + Metric metric, std::vector fixed_tags, + std::vector value_counts, + std::vector> tags) + : metric_(std::move(metric)), + fixed_tags_(std::move(fixed_tags)), + value_counts_(std::move(value_counts)), + tags_(std::move(tags)), + strides_(series_id_strides(value_counts_)) {} + +template +tracing::Optional MetricBase::series_id( + const void* tags) const { + SeriesId id = 0; + for (std::size_t index = 0; index < tags_.size(); ++index) { + const std::uint64_t value = tags_[index]->read(tags); + if (value >= value_counts_[index]) return tracing::nullopt; + id += value * strides_[index]; + } + return id; +} + +template +std::vector MetricBase::series_tags(SeriesId id) const { + std::vector tags = fixed_tags_; + for (std::size_t index = 0; index < tags_.size(); ++index) { + const std::uint64_t value = id / strides_[index] % value_counts_[index]; + std::string rendered = tags_[index]->render(value); + if (!rendered.empty()) tags.push_back(std::move(rendered)); + } + return tags; +} + +template class MetricBase; +template class MetricBase; +template class MetricBase; + +struct SeriesSketches::Impl { + std::mutex mutex; + std::unordered_map sketches; +}; + +SeriesSketches::SeriesSketches() : impl_(std::make_unique()) {} + +SeriesSketches::~SeriesSketches() = default; + +void SeriesSketches::record(SeriesId series, std::uint64_t value) { + std::lock_guard lock(impl_->mutex); + impl_->sketches[series].record(static_cast(value)); +} + +std::vector> SeriesSketches::take() { + std::unordered_map taken; + { + std::lock_guard lock(impl_->mutex); + taken.swap(impl_->sketches); + } + std::vector> encoded; + for (const auto& [series, sketch] : taken) { + encoded.emplace_back(series, sketch.encode_protobuf()); + } + return encoded; +} + +} // namespace details + +namespace { + +std::uint16_t StringTable::intern(tracing::StringView value) { + const std::string key(value); + std::lock_guard lock(mutex_); + if (const auto found = ids_.find(key); found != ids_.end()) { + return found->second; + } + if (strings_.size() >= overflow_id) return overflow_id; + return add(key); +} + +std::string StringTable::value(std::uint16_t id) { + if (id == overflow_id) return "other"; + std::lock_guard lock(mutex_); + return id < strings_.size() ? strings_[id] : std::string(); +} + +// Expects the lock to be held, or the table to be under construction. +std::uint16_t StringTable::add(const std::string& value) { + const auto id = static_cast(strings_.size()); + strings_.push_back(value); + ids_.emplace(value, id); + return id; +} + +// The last tag has stride 1. Each other tag's stride is the number of +// combinations of the values of the tags after it. +std::vector series_id_strides( + const std::vector& value_counts) { + std::vector strides(value_counts.size()); + details::SeriesId stride = 1; + for (std::size_t index = value_counts.size(); index-- > 0;) { + strides[index] = stride; + stride *= value_counts[index]; + } + return strides; +} + +} // namespace +} // namespace datadog::telemetry diff --git a/src/datadog/telemetry/telemetry.cpp b/src/datadog/telemetry/telemetry.cpp index fbdb7099..d8379467 100644 --- a/src/datadog/telemetry/telemetry.cpp +++ b/src/datadog/telemetry/telemetry.cpp @@ -109,6 +109,17 @@ void capture_product_change(const Product& product) { instance()); } +details::MetricRegistry* details::metric_registry() { + return std::visit( + details::Overload{ + [](std::shared_ptr& telemetry) -> MetricRegistry* { + return &telemetry->metrics(); + }, + [](NoopTelemetry) -> MetricRegistry* { return nullptr; }, + }, + instance()); +} + namespace log { void warning(std::string message) { std::visit(details::Overload{ diff --git a/src/datadog/telemetry/telemetry_impl.cpp b/src/datadog/telemetry/telemetry_impl.cpp index 46583039..96870f23 100644 --- a/src/datadog/telemetry/telemetry_impl.cpp +++ b/src/datadog/telemetry/telemetry_impl.cpp @@ -10,6 +10,7 @@ #include +#include "base64.h" #include "datadog_agent.h" #include "platform_util.h" @@ -209,6 +210,30 @@ nlohmann::json encode_distributions( return j; } +// The `sketches` payload of the distribution handles' series, or nothing if +// there are none. +Optional sketches_payload( + const std::vector>& distributions) { + if (distributions.empty()) return nullopt; + auto series = nlohmann::json::array(); + for (const auto& distribution : distributions) { + auto encoded = nlohmann::json{ + {"metric", distribution.metric.name}, + {"common", distribution.metric.common}, + {"namespace", distribution.metric.scope}, + {"sketch_b64", base64_encode(distribution.value)}, + }; + if (!distribution.tags.empty()) { + encoded.emplace("tags", distribution.tags); + } + series.emplace_back(std::move(encoded)); + } + return nlohmann::json{ + {"request_type", "sketches"}, + {"payload", nlohmann::json{{"series", std::move(series)}}}, + }; +} + nlohmann::json encode_product(const Product& product) { auto encoded = nlohmann::json{ {"version", product.version}, @@ -534,6 +559,10 @@ std::string Telemetry::heartbeat_and_telemetry() { batch_payloads.emplace_back(std::move(distributions_json)); } + if (auto sketches = sketches_payload(metrics_.take())) { + batch_payloads.emplace_back(std::move(*sketches)); + } + std::vector old_logs; { std::lock_guard l{log_mutex_}; @@ -597,6 +626,10 @@ std::string Telemetry::app_closing_payload() { batch_payloads.emplace_back(std::move(distributions_json)); } + if (auto sketches = sketches_payload(metrics_.take())) { + batch_payloads.emplace_back(std::move(*sketches)); + } + if (!logs_.empty()) { auto encoded_logs = encode_logs(logs_); assert(!encoded_logs.empty()); @@ -851,6 +884,16 @@ void Telemetry::capture_metrics() { auto& rates_snapshots = rates_snapshot_[rate]; rates_snapshots.emplace_back(std::make_pair(timepoint, value)); } + + for (auto& series : metrics_.take()) { + counters_snapshot_[{series.metric, std::move(series.tags)}].emplace_back( + timepoint, series.value); + } + + for (auto& series : metrics_.take()) { + rates_snapshot_[{series.metric, std::move(series.tags)}].emplace_back( + timepoint, series.value); + } } void Telemetry::log(std::string message, telemetry::LogLevel level, diff --git a/src/datadog/telemetry/telemetry_impl.h b/src/datadog/telemetry/telemetry_impl.h index 2e432a32..c2facc85 100644 --- a/src/datadog/telemetry/telemetry_impl.h +++ b/src/datadog/telemetry/telemetry_impl.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -56,6 +57,9 @@ class Telemetry final : public std::enable_shared_from_this { std::unordered_map, std::vector> distributions_; + // The metric handles created with this Telemetry. + details::MetricRegistry metrics_; + // Configuration std::vector configuration_snapshot_; @@ -141,6 +145,9 @@ class Telemetry final : public std::enable_shared_from_this { void add_datapoint(const Distribution& distribution, const std::vector& tags, uint64_t value); + // Creates the metric handles that this Telemetry sends. + details::MetricRegistry& metrics() { return metrics_; } + private: void app_started(); void app_closing(); diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 86a47e77..85b9340a 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -20,6 +20,8 @@ add_executable(tests # telemetry test cases telemetry/test_configuration.cpp + telemetry/test_log_binned_distr.cpp + telemetry/test_metric_handle.cpp telemetry/test_telemetry.cpp # test cases diff --git a/test/telemetry/test_log_binned_distr.cpp b/test/telemetry/test_log_binned_distr.cpp new file mode 100644 index 00000000..a659b4ce --- /dev/null +++ b/test/telemetry/test_log_binned_distr.cpp @@ -0,0 +1,466 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "datadog/telemetry/log_bin_index.h" +#include "datadog/telemetry/log_binned_distr.h" +#include "test.h" + +using namespace datadog::telemetry; + +#define LOG_BINNED_TEST(x) TEST_CASE(x, "[telemetry][log_binned_distr]") + +namespace { + +using BinIndex = log_bins::BinIndex; +using Bins = std::map; + +struct DecodedSketch { + double gamma = 0; + double index_offset = 0; + std::uint64_t interpolation = 0; + Bins bins; + bool has_negative_store = false; + Bins negative_bins; + double zero_count = 0; +}; + +DecodedSketch decode_sketch(const std::string& data); +std::uint64_t to_bits(double value); +double from_bits(std::uint64_t bits); + +// The bins expected once `values` are recorded. Each value counts in its own +// bin, but only the 2048 highest bins are kept. Lower values count in the +// lowest bin kept. +Bins expected_bins(const std::vector& values) { + Bins exact; + for (const double value : values) { + const BinIndex bin = log_bins::bin_index(value); + if (bin != log_bins::zero_bin) exact[bin] += 1; + } + if (exact.empty()) return exact; + + const BinIndex lowest_kept = exact.rbegin()->first - 2047; + Bins expected; + for (const auto& [bin, count] : exact) { + expected[std::max(bin, lowest_kept)] += count; + } + return expected; +} + +// A value in the middle of `bin`, half a bin from both edges. Bin 1338 holds +// 1.0. +double value_in_bin(BinIndex bin) { + return std::pow(log_bins::bin_ratio, bin - 1338); +} + +Bins recorded_bins(const std::vector& bins) { + LogBinnedDistr distribution; + for (const BinIndex bin : bins) distribution.record(value_in_bin(bin)); + return decode_sketch(distribution.encode_protobuf()).bins; +} + +// Returns the bits of the smallest double whose reference bin is at least +// `bin`, searching in (below, at_or_above]. +std::uint64_t reference_edge(BinIndex bin, std::uint64_t below, + std::uint64_t at_or_above) { + while (at_or_above - below > 1) { + const std::uint64_t middle = below + (at_or_above - below) / 2; + if (log_bins::reference_bin_index(from_bits(middle)) >= bin) { + at_or_above = middle; + } else { + below = middle; + } + } + return at_or_above; +} + +void check_same_bin(double value) { + INFO("value " << value << ", bits " << to_bits(value)); + CHECK(log_bins::bin_index(value) == log_bins::reference_bin_index(value)); +} + +void check_bins(const std::vector& values) { + LogBinnedDistr distribution; + for (const double value : values) distribution.record(value); + const double zero_count = + static_cast(std::count(values.begin(), values.end(), 0.0)); + + const DecodedSketch decoded = decode_sketch(distribution.encode_protobuf()); + CHECK(decoded.bins == expected_bins(values)); + CHECK(decoded.zero_count == zero_count); +} + +std::vector log_uniform(std::size_t count, double lowest, + double highest, std::uint64_t seed) { + std::mt19937_64 generator(seed); + std::uniform_real_distribution exponent(std::log(lowest), + std::log(highest)); + std::vector values(count); + for (double& value : values) value = std::exp(exponent(generator)); + return values; +} + +} // namespace + +LOG_BINNED_TEST("mapping constants follow libdatadog's formulas") { + const double relative_accuracy = 0.007751937984496124; + CHECK((1 + relative_accuracy) / (1 - relative_accuracy) == + log_bins::bin_ratio); + + const double log_ratio = std::log(log_bins::bin_ratio); + CHECK((1 - std::floor(std::log(1e-9) / log_ratio)) + 0.5 == + log_bins::bin_index_shift); + + const double multiplier = 1 / log_ratio; + const double int32_limit = + std::exp((INT32_MIN - log_bins::bin_index_shift) / multiplier + 1.0); + CHECK(std::max(DBL_MIN * log_bins::bin_ratio, int32_limit) == + log_bins::zero_threshold); +} + +LOG_BINNED_TEST("bin index of special values") { + const double infinity = std::numeric_limits::infinity(); + const std::vector> cases{ + {std::nan(""), log_bins::rejected_value}, + {infinity, log_bins::rejected_value}, + {-infinity, log_bins::rejected_value}, + {-1.0, log_bins::rejected_value}, + {-DBL_MIN, log_bins::rejected_value}, + {0.0, log_bins::zero_bin}, + {-0.0, log_bins::zero_bin}, + {std::numeric_limits::denorm_min(), log_bins::zero_bin}, + {DBL_MIN, log_bins::zero_bin}, + {std::nextafter(log_bins::zero_threshold, 0.0), log_bins::zero_bin}, + {log_bins::zero_threshold, -44352}, + {1e-9, 1}, + {1.0, 1338}, + {1000.0, 1784}, + {DBL_MAX, 47118}, + }; + for (const auto& [value, expected_bin] : cases) { + INFO("value " << value); + CHECK(log_bins::bin_index(value) == expected_bin); + CHECK(log_bins::reference_bin_index(value) == expected_bin); + } +} + +LOG_BINNED_TEST("the fast table is built") { + CHECK(log_bins::fast_table_built()); +} + +LOG_BINNED_TEST("bin index of values far from an edge is exact") { + // Exact bins, computed with 300-bit arithmetic (mpmath): the floor of + // ln(x) / ln(65/64) + 1338.5. Each value is at least 0.04 bins from an edge. + const std::vector> cases{ + {1e-300, -43216}, {5e-300, -43112}, {1e-20, -1632}, {3.3e-15, -813}, + {1e-9, 1}, {0.001, 892}, {0.37, 1274}, {0.5, 1293}, + {1.0, 1338}, {2.5, 1397}, {3.0, 1409}, {123.456, 1649}, + {1000.0, 1784}, {65536.0, 2053}, {1e9, 2675}, {1e12, 3120}, + {1e18, 4011}, {1e25, 5051}, {1e100, 16189}, {1e300, 45892}, + }; + for (const auto& [value, expected_bin] : cases) { + INFO("value " << value); + CHECK(log_bins::bin_index(value) == expected_bin); + } +} + +LOG_BINNED_TEST("bin index rounds the multiplication and the addition once") { + // ln(x) / ln(65/64) + 1338.5 is 3253.99999999999995516 for this x, so the + // exact bin is 3253. Rounding the multiplication first would round the + // result up to 3254. + const double value = 7'903'045'517'381.0; + CHECK(log_bins::reference_bin_index(value) == 3253); + CHECK(log_bins::bin_index(value) == 3253); +} + +LOG_BINNED_TEST("bin index equals the reference around every bin edge") { + // Covers the fast table, [2^-30, 2^65), and some bins on each side. + const std::uint64_t lowest_bits = to_bits(std::ldexp(1.0, -32)); + const std::uint64_t highest_bits = to_bits(std::ldexp(1.0, 67)); + const BinIndex first_bin = + log_bins::reference_bin_index(from_bits(lowest_bits)); + const BinIndex last_bin = + log_bins::reference_bin_index(from_bits(highest_bits)); + + std::uint64_t previous_edge = lowest_bits; + for (BinIndex bin = first_bin + 1; bin <= last_bin; ++bin) { + const std::uint64_t edge = reference_edge(bin, previous_edge, highest_bits); + for (std::uint64_t step = 0; step <= 6; ++step) { + check_same_bin(from_bits(edge - 3 + step)); + } + previous_edge = edge; + } +} + +LOG_BINNED_TEST("bin index equals the reference on many values") { + SECTION("log-uniform values") { + for (const double value : log_uniform(1'000'000, 1e-15, 1e25, 1)) { + check_same_bin(value); + } + } + SECTION("random bit patterns") { + std::mt19937_64 generator(2); + for (int count = 0; count < 1'000'000; ++count) { + check_same_bin(from_bits(generator())); + } + } + SECTION("integers and decimal fractions") { + for (int number = 0; number < 200'000; ++number) { + check_same_bin(number); + check_same_bin(number / 1000.0); + } + } +} + +LOG_BINNED_TEST("record rejects invalid values") { + LogBinnedDistr distribution; + CHECK_FALSE(distribution.record(std::nan(""))); + CHECK_FALSE(distribution.record(-1.0)); + CHECK_FALSE(distribution.record(std::numeric_limits::infinity())); + CHECK(distribution.record(0.0)); + CHECK(distribution.record(-0.0)); + + const DecodedSketch decoded = decode_sketch(distribution.encode_protobuf()); + CHECK(decoded.bins.empty()); + CHECK(decoded.zero_count == 2); +} + +LOG_BINNED_TEST("encoding of an empty distribution") { + const LogBinnedDistr distribution; + const unsigned char expected[] = { + 0x0a, 0x12, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xf0, 0x3f, 0x11, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xea, 0x94, 0x40, 0x12, 0x00, 0x1a, 0x00}; + CHECK(distribution.encode_protobuf() == + std::string(reinterpret_cast(expected), sizeof expected)); +} + +LOG_BINNED_TEST("encoding of one value") { + LogBinnedDistr distribution; + distribution.record(1.0); + const unsigned char expected[] = { + 0x0a, 0x12, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xf0, + 0x3f, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0xea, 0x94, 0x40, + 0x12, 0x0e, 0x0a, 0x0c, 0x08, 0xf4, 0x14, 0x11, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f, 0x1a, 0x00}; + CHECK(distribution.encode_protobuf() == + std::string(reinterpret_cast(expected), sizeof expected)); + + const DecodedSketch decoded = decode_sketch(distribution.encode_protobuf()); + CHECK(decoded.gamma == 65.0 / 64.0); + CHECK(decoded.index_offset == 1338.5); + CHECK(decoded.interpolation == 0); + CHECK(decoded.bins == Bins{{1338, 1.0}}); + CHECK(decoded.has_negative_store); + CHECK(decoded.negative_bins.empty()); +} + +LOG_BINNED_TEST("the store keeps the 2048 highest bins") { + SECTION("a range of 2048 bins keeps every bin") { + CHECK(recorded_bins({1000, 3047}) == Bins{{1000, 1}, {3047, 1}}); + } + SECTION("a higher value merges the lowest bins into the lowest bin kept") { + CHECK(recorded_bins({1000, 1000, 1500, 3048}) == + Bins{{1001, 2}, {1500, 1}, {3048, 1}}); + CHECK(recorded_bins({1000, 1500, 9000}) == Bins{{6953, 2}, {9000, 1}}); + } + SECTION("a lower value goes to the lowest bin kept") { + CHECK(recorded_bins({3047, 1000, 999, 10}) == Bins{{1000, 3}, {3047, 1}}); + CHECK(recorded_bins({3047, 500}) == Bins{{1000, 1}, {3047, 1}}); + CHECK(recorded_bins({1000, 3048, 5}) == Bins{{1001, 2}, {3048, 1}}); + } +} + +LOG_BINNED_TEST("bins of many values") { + SECTION("narrow durations") { + check_bins(log_uniform(100'000, 100, 10'000, 3)); + } + SECTION("wide range, which collapses the lowest bins") { + check_bins(log_uniform(100'000, 1e-12, 1e22, 4)); + } + SECTION("values that only increase") { + std::vector values = log_uniform(20'000, 1e-9, 1e20, 5); + std::sort(values.begin(), values.end()); + check_bins(values); + } + SECTION("values that only decrease") { + std::vector values = log_uniform(20'000, 1e-9, 1e20, 6); + std::sort(values.begin(), values.end(), std::greater()); + check_bins(values); + } + SECTION("values alternating between both ends") { + std::vector values; + for (int step = 0; step < 5'000; ++step) { + values.push_back(1e-6 * (1 + step % 7)); + values.push_back(1e15 * (1 + step % 5)); + } + check_bins(values); + } + SECTION("low values, then high ones, then low ones again") { + std::vector values = log_uniform(5'000, 1, 100, 7); + const std::vector high = log_uniform(5'000, 1e14, 1e16, 8); + const std::vector low = log_uniform(5'000, 1e-3, 10, 9); + values.insert(values.end(), high.begin(), high.end()); + values.insert(values.end(), low.begin(), low.end()); + check_bins(values); + } + SECTION("zeros and fractions mixed") { + std::vector values = log_uniform(50'000, 1e-4, 1, 10); + for (std::size_t index = 0; index < values.size(); index += 10) { + values[index] = 0; + } + check_bins(values); + } +} + +LOG_BINNED_TEST("records from several threads are all counted") { + LogBinnedDistr distribution; + static constexpr int thread_count = 4; + static constexpr int values_per_thread = 50'000; + std::vector threads; + for (int thread_number = 0; thread_number < thread_count; ++thread_number) { + threads.emplace_back([&distribution, thread_number] { + for (int index = 0; index < values_per_thread; ++index) { + distribution.record(1.0 + thread_number + index % 100); + } + }); + } + for (std::thread& thread : threads) thread.join(); + + double total = 0; + for (const auto& [bin, count] : + decode_sketch(distribution.encode_protobuf()).bins) { + total += count; + } + CHECK(total == thread_count * values_per_thread); +} + +namespace { + +// A minimal protobuf reader, for the messages of a DDSketch. +class ProtobufReader { + public: + explicit ProtobufReader(const std::string& data) : data_(data) {} + + bool done() const { return position_ >= data_.size(); } + + std::uint64_t read_varint() { + std::uint64_t value = 0; + for (int shift = 0;; shift += 7) { + const auto byte = static_cast(data_.at(position_++)); + value |= std::uint64_t{byte & 0x7fu} << shift; + if ((byte & 0x80) == 0) return value; + } + } + + double read_double() { + std::uint64_t bits = 0; + for (int byte = 0; byte < 8; ++byte) { + const auto value = static_cast(data_.at(position_++)); + bits |= std::uint64_t{value} << (8 * byte); + } + return from_bits(bits); + } + + std::string read_bytes() { + const std::size_t length = read_varint(); + REQUIRE(position_ + length <= data_.size()); + std::string bytes = data_.substr(position_, length); + position_ += length; + return bytes; + } + + private: + const std::string& data_; + std::size_t position_ = 0; +}; + +std::int32_t unzigzag(std::uint64_t value) { + const auto low = static_cast(value); + return static_cast((low >> 1) ^ (0u - (low & 1))); +} + +void decode_bin(const std::string& data, Bins& bins) { + ProtobufReader reader(data); + BinIndex bin = 0; + double count = 0; + while (!reader.done()) { + const std::uint64_t tag = reader.read_varint(); + if (tag == ((1 << 3) | 0)) { + bin = unzigzag(reader.read_varint()); + } else if (tag == ((2 << 3) | 1)) { + count = reader.read_double(); + } else { + FAIL("unexpected field in a bin entry: " << tag); + } + } + bins[bin] += count; +} + +Bins decode_store(const std::string& data) { + ProtobufReader reader(data); + Bins bins; + while (!reader.done()) { + const std::uint64_t tag = reader.read_varint(); + REQUIRE(tag == ((1 << 3) | 2)); + decode_bin(reader.read_bytes(), bins); + } + return bins; +} + +void decode_mapping(const std::string& data, DecodedSketch& sketch) { + ProtobufReader reader(data); + while (!reader.done()) { + const std::uint64_t tag = reader.read_varint(); + if (tag == ((1 << 3) | 1)) { + sketch.gamma = reader.read_double(); + } else if (tag == ((2 << 3) | 1)) { + sketch.index_offset = reader.read_double(); + } else if (tag == ((3 << 3) | 0)) { + sketch.interpolation = reader.read_varint(); + } else { + FAIL("unexpected field in the mapping: " << tag); + } + } +} + +DecodedSketch decode_sketch(const std::string& data) { + ProtobufReader reader(data); + DecodedSketch sketch; + while (!reader.done()) { + const std::uint64_t tag = reader.read_varint(); + if (tag == ((1 << 3) | 2)) { + decode_mapping(reader.read_bytes(), sketch); + } else if (tag == ((2 << 3) | 2)) { + sketch.bins = decode_store(reader.read_bytes()); + } else if (tag == ((3 << 3) | 2)) { + sketch.has_negative_store = true; + sketch.negative_bins = decode_store(reader.read_bytes()); + } else if (tag == ((4 << 3) | 1)) { + sketch.zero_count = reader.read_double(); + } else { + FAIL("unexpected field in the sketch: " << tag); + } + } + return sketch; +} + +std::uint64_t to_bits(double value) { + std::uint64_t bits; + std::memcpy(&bits, &value, sizeof bits); + return bits; +} + +double from_bits(std::uint64_t bits) { + double value; + std::memcpy(&value, &bits, sizeof value); + return value; +} + +} // namespace diff --git a/test/telemetry/test_metric_handle.cpp b/test/telemetry/test_metric_handle.cpp new file mode 100644 index 00000000..df2daa3c --- /dev/null +++ b/test/telemetry/test_metric_handle.cpp @@ -0,0 +1,165 @@ +#include + +#include + +#include "datadog/telemetry/log_binned_distr.h" +#include "test.h" + +using namespace datadog::telemetry; +using datadog::tracing::Optional; + +#define METRIC_HANDLE_TEST(x) TEST_CASE(x, "[telemetry][metric_handle]") + +namespace { + +enum class Step { request_first, request_body }; + +std::array tag_value_names(Step) { + return {"req.first", "req.body"}; +} + +struct RequestTags { + TagString rules_version; + bool blocked = false; + Optional step; + + static auto tag_fields() { + using Self = RequestTags; + return std::tuple{tag("rules_version", &Self::rules_version), + tag("blocked", &Self::blocked), tag("step", &Self::step)}; + } +}; + +// Only the first two values have names. +enum class Size { small, large, unnamed }; + +std::array tag_value_names(Size) { return {"small", "large"}; } + +struct SizeTags { + Size size = Size::small; + + static auto tag_fields() { return std::tuple{tag("size", &SizeTags::size)}; } +}; + +struct TooManyTags { + TagString first, second, third, fourth, fifth; + + static auto tag_fields() { + using Self = TooManyTags; + return std::tuple{tag("first", &Self::first), tag("second", &Self::second), + tag("third", &Self::third), tag("fourth", &Self::fourth), + tag("fifth", &Self::fifth)}; + } +}; + +// A handle for TooManyTags would not compile: 65536^5 combinations do not fit +// in a 64-bit series id. +static_assert(!details::fits_in_series_id( + static_cast(nullptr))); +static_assert(details::fits_in_series_id( + static_cast(nullptr))); + +template +std::map, typename Metric::Value> by_tags( + const std::vector>& series) { + std::map, typename Metric::Value> result; + for (const auto& one_series : series) { + result[one_series.tags] = one_series.value; + } + return result; +} + +std::string sketch_of(std::initializer_list values) { + LogBinnedDistr sketch; + for (double value : values) sketch.record(value); + return sketch.encode_protobuf(); +} + +} // namespace + +METRIC_HANDLE_TEST("a counter without tags has one series") { + details::MetricRegistry registry; + const auto requests = registry.counter({"requests", "tracers", true}, + {"integration_name:datadog"}); + requests->record({}, 1); + requests->record({}, 1); + + const auto series = registry.take(); + REQUIRE(series.size() == 1); + CHECK(series[0].metric.name == "requests"); + CHECK(series[0].tags == std::vector{"integration_name:datadog"}); + CHECK(series[0].value == 2); + CHECK(registry.take().empty()); +} + +METRIC_HANDLE_TEST("each combination of tag values is a series") { + details::MetricRegistry registry; + const auto requests = registry.counter( + {"waf.requests", "appsec", true}, {"waf_version:1.30.1"}); + RequestTags tags; + tags.rules_version = TagString{"1.18.2"}; + requests->record(tags, 1); + tags.blocked = true; + tags.step = Step::request_body; + requests->record(tags, 1); + tags.rules_version = TagString{"1.18.2"}; // the same string, interned again + requests->record(tags, 1); + + using Counts = std::map, std::uint64_t>; + CHECK( + by_tags(registry.take()) == + Counts{ + {{"waf_version:1.30.1", "rules_version:1.18.2", "blocked:false"}, 1}, + {{"waf_version:1.30.1", "rules_version:1.18.2", "blocked:true", + "step:req.body"}, + 2}, + }); +} + +METRIC_HANDLE_TEST("a dropped handle is forgotten") { + details::MetricRegistry registry; + auto requests = + registry.counter({"requests", "tracers", true}, {"version:1"}); + requests->record({}, 1); + requests = registry.counter({"requests", "tracers", true}, {"version:2"}); + requests->record({}, 1); + + using Counts = std::map, std::uint64_t>; + CHECK(by_tags(registry.take()) == Counts{{{"version:2"}, 1}}); +} + +METRIC_HANDLE_TEST("a rate keeps its last value") { + details::MetricRegistry registry; + const auto rate = registry.rate({"spans", "tracers", true}); + rate->record({}, 5); + rate->record({}, 3); + CHECK(registry.take().at(0).value == 3); +} + +METRIC_HANDLE_TEST("a distribution has one sketch per series") { + details::MetricRegistry registry; + const auto duration = + registry.distribution({"waf.duration", "appsec", true}); + RequestTags tags; + duration->record(tags, 100); + duration->record(tags, 250); + tags.blocked = true; + duration->record(tags, 7); + + using Sketches = std::map, EncodedSketch>; + CHECK(by_tags(registry.take()) == + Sketches{ + {{"rules_version:", "blocked:false"}, sketch_of({100, 250})}, + {{"rules_version:", "blocked:true"}, sketch_of({7})}, + }); +} + +METRIC_HANDLE_TEST("an enum value without a name is dropped") { + details::MetricRegistry registry; + const auto bodies = registry.counter({"bodies", "appsec", true}); + bodies->record({Size::large}, 1); + bodies->record({Size::unnamed}, 1); + + using Counts = std::map, std::uint64_t>; + CHECK(by_tags(registry.take()) == Counts{{{"size:large"}, 1}}); +} diff --git a/test/telemetry/test_telemetry.cpp b/test/telemetry/test_telemetry.cpp index 9a0cfb41..fa772242 100644 --- a/test/telemetry/test_telemetry.cpp +++ b/test/telemetry/test_telemetry.cpp @@ -9,7 +9,9 @@ #include #include "../common/environment.h" +#include "datadog/base64.h" #include "datadog/runtime_id.h" +#include "datadog/telemetry/log_binned_distr.h" #include "datadog/telemetry/telemetry_impl.h" #include "mocks/http_clients.h" #include "mocks/loggers.h" @@ -42,6 +44,20 @@ std::optional find_payload(const nlohmann::json& messages, return std::nullopt; }; +struct StatusTags { + bool error = false; + + static auto tag_fields() { + return std::tuple{tag("error", &StatusTags::error)}; + } +}; + +std::string sketch_b64(std::initializer_list values) { + LogBinnedDistr sketch; + for (double value : values) sketch.record(value); + return base64_encode(sketch.encode_protobuf()); +} + struct FakeEventScheduler : public EventScheduler { size_t count_tasks = 0; std::function heartbeat_callback = nullptr; @@ -816,6 +832,79 @@ TELEMETRY_IMPLEMENTATION_TEST("Tracer telemetry API") { CHECK(find_payload(message_batch["payload"], "app-heartbeat")); } + SECTION("counter and rate handles are sent with the metrics") { + client->clear(); + auto requests = telemetry->metrics().counter( + {"handle_requests", "handle-test", true}, + {"integration_name:datadog"}); + auto rate = + telemetry->metrics().rate({"handle_rate", "handle-test", false}); + requests->record({true}, 1); + requests->record({true}, 2); + rate->record({}, 7); + + scheduler->trigger_metrics_capture(); + scheduler->trigger_heartbeat(); + + auto message_batch = nlohmann::json::parse(client->request_body); + auto generate_metrics = + find_payload(message_batch["payload"], "generate-metrics"); + REQUIRE(generate_metrics); + std::vector handle_series; + for (const auto& series : (*generate_metrics)["payload"]["series"]) { + if (series["namespace"] == "handle-test") { + handle_series.push_back(series); + } + } + + const auto expected = nlohmann::json::parse(R"([ + { + "common": true, + "metric": "handle_requests", + "namespace": "handle-test", + "points": [[1672484400, 3]], + "tags": ["integration_name:datadog", "error:true"], + "type": "count" + }, + { + "common": false, + "metric": "handle_rate", + "namespace": "handle-test", + "points": [[1672484400, 7]], + "type": "rate" + } + ])"); + REQUIRE(handle_series.size() == 2); + for (const auto& series : expected) { + CHECK(std::count(handle_series.begin(), handle_series.end(), series) == + 1); + } + } + + SECTION("distribution handles are sent as sketches") { + client->clear(); + auto duration = telemetry->metrics().distribution( + {"handle_duration", "handle-test", true}); + duration->record({false}, 100); + duration->record({false}, 250); + + scheduler->trigger_heartbeat(); + + auto message_batch = nlohmann::json::parse(client->request_body); + auto sketches = find_payload(message_batch["payload"], "sketches"); + REQUIRE(sketches); + auto expected = nlohmann::json::parse(R"([ + { + "common": true, + "metric": "handle_duration", + "namespace": "handle-test", + "tags": ["error:false"] + } + ])"); + expected[0]["sketch_b64"] = sketch_b64({100, 250}); + CHECK((*sketches)["payload"]["series"] == expected); + } + SECTION("distribution") { client->clear(); diff --git a/test/test_base64.cpp b/test/test_base64.cpp index 298b6577..33af765a 100644 --- a/test/test_base64.cpp +++ b/test/test_base64.cpp @@ -30,3 +30,18 @@ BASE64_TEST("padding") { CHECK(base64_decode("bGlnaHQgd28=") == "light wo"); CHECK(base64_decode("bGlnaHQgd29y") == "light wor"); } + +BASE64_TEST("encode") { + CHECK(base64_encode("") == ""); + CHECK(base64_encode("f") == "Zg=="); + CHECK(base64_encode("fo") == "Zm8="); + CHECK(base64_encode("foo") == "Zm9v"); + CHECK(base64_encode("foob") == "Zm9vYg=="); + CHECK(base64_encode("fooba") == "Zm9vYmE="); + CHECK(base64_encode("foobar") == "Zm9vYmFy"); +} + +BASE64_TEST("encode bytes above 0x7f") { + CHECK(base64_encode("\xff\xfe") == "//4="); + CHECK(base64_encode(std::string("\x00\x80\xfb", 3)) == "AID7"); +}