Skip to content

Commit

Permalink
serialize for summary
Browse files Browse the repository at this point in the history
  • Loading branch information
qicosmos committed Feb 7, 2025
1 parent edbf301 commit 0571c9e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
10 changes: 7 additions & 3 deletions include/ylt/metric/summary.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ class summary_t : public static_metric {
std::sort(quantiles_.begin(), quantiles_.end());
}

void observe(float value) { impl_.insert(value); }
void observe(float value) {
has_refreshed_.store(true, std::memory_order_relaxed);
impl_.insert(value);
}

std::vector<float> get_rates() {
uint64_t count;
Expand All @@ -85,7 +88,7 @@ class summary_t : public static_metric {
double sum = 0;
uint64_t count = 0;
auto rates = get_rates(sum, count);
if (count == 0) {
if (count == 0 && !has_refreshed_.load(std::memory_order_relaxed)) {
return;
}
serialize_head(str);
Expand Down Expand Up @@ -121,7 +124,7 @@ class summary_t : public static_metric {
json_summary_metric_t metric;

metric.quantiles_value = get_rates(metric.sum, metric.count);
if (metric.count == 0) {
if (metric.count == 0 && !has_refreshed_.load(std::memory_order_relaxed)) {
return;
}
metric.labels.reserve(labels_value_.size());
Expand All @@ -132,6 +135,7 @@ class summary_t : public static_metric {
#endif

private:
std::atomic<bool> has_refreshed_;
std::vector<double> quantiles_;
ylt::metric::detail::summary_impl<uint64_t> impl_;
};
Expand Down
20 changes: 19 additions & 1 deletion src/metric/tests/test_metric.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,19 @@ TEST_CASE("test summary refresh") {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distr(1, 100);
std::string str;
summary.serialize_to_json(str);
CHECK(str.size() == 0);
str = "";
summary.serialize(str);
CHECK(str.size() == 0);

std::this_thread::sleep_for(1001ms);
summary.serialize_to_json(str);
CHECK(str.size() == 0);
str = "";
summary.serialize(str);
CHECK(str.size() == 0);
for (int i = 0; i < 50; i++) {
summary.observe(i);
}
Expand All @@ -1050,6 +1063,11 @@ TEST_CASE("test summary refresh") {
std::this_thread::sleep_for(500ms);
summary.get_rates(sum, cnt);
CHECK(cnt == 0);
summary.serialize_to_json(str);
CHECK(str.size() > 0);
str = "";
summary.serialize(str);
CHECK(str.size() > 0);
}

TEST_CASE("test register metric") {
Expand Down Expand Up @@ -2011,7 +2029,7 @@ TEST_CASE("test metric manager clean expired label") {
CHECK(c->label_value_count() == 2);
CHECK(summary->label_value_count() == 1);
CHECK(h->label_value_count() == 1);
std::this_thread::sleep_for(std::chrono::seconds(2));
std::this_thread::sleep_for(std::chrono::seconds(3));
c->inc({"/index"});
size_t count = c->label_value_count();
CHECK(count == 1);
Expand Down

0 comments on commit 0571c9e

Please sign in to comment.