Skip to content

Commit

Permalink
[metric] static summary serialize won't empty when it has observerd a… (
Browse files Browse the repository at this point in the history
#898)

[metric] static summary serialize won't empty when it has observerd and refreshed
  • Loading branch information
poor-circle authored Feb 7, 2025
1 parent b41a1d6 commit 416e89d
Show file tree
Hide file tree
Showing 2 changed files with 27 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
21 changes: 20 additions & 1 deletion src/metric/tests/test_metric.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -978,9 +978,24 @@ 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);
}

double sum;
uint64_t cnt;
summary.get_rates(sum, cnt);
Expand All @@ -1002,7 +1017,11 @@ TEST_CASE("test summary refresh") {
CHECK(cnt == 10);
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

0 comments on commit 416e89d

Please sign in to comment.