Copilot commented on code in PR #13754:
URL: https://github.com/apache/trafficserver/pull/13754#discussion_r4189331821


##########
plugins/stats_over_http/prometheus_render.cc:
##########
@@ -0,0 +1,761 @@
+/** @file
+
+  Render records in the Prometheus text format from a cache of translated 
names.
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+ */
+
+#include "prometheus_render.h"
+
+#include <algorithm>
+#include <cerrno>
+#include <charconv>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <functional>
+#include <limits>
+#include <numeric>
+
+#include "prometheus_rules.h"
+#include "tsutil/DbgCtl.h"
+#include "tsutil/StringCompare.h"
+
+namespace
+{
+DbgCtl dbg_ctl{"stats_over_http"};
+
+bool
+is_numeric(TSRecordDataType data_type)
+{
+  return data_type == TS_RECORDDATATYPE_COUNTER || data_type == 
TS_RECORDDATATYPE_INT || data_type == TS_RECORDDATATYPE_FLOAT;
+}
+
+bool
+is_digit(char c)
+{
+  return c >= '0' && c <= '9';
+}
+
+// Accepts a decimal number with an optional sign and exponent, Inf or 
Infinity with an optional sign, or NaN.  The case of
+// the letters does not matter.  Rejects a number too large for a double.
+bool
+parse_number(const std::string &text, double &value)
+{
+  std::string_view body{text};
+
+  if (ts::iequals(body, "nan")) {
+    value = NAN;
+    return true;
+  }
+  if (!body.empty() && (body[0] == '+' || body[0] == '-')) {
+    body.remove_prefix(1);
+  }
+  if (!ts::iequals(body, "inf") && !ts::iequals(body, "infinity")) {
+    size_t i      = 0;
+    size_t digits = 0;
+
+    for (; i < body.size() && is_digit(body[i]); ++i) {
+      ++digits;
+    }
+    if (i < body.size() && body[i] == '.') {
+      for (++i; i < body.size() && is_digit(body[i]); ++i) {
+        ++digits;
+      }
+    }
+    if (digits == 0) {
+      return false;
+    }
+    if (i < body.size() && (body[i] == 'e' || body[i] == 'E')) {
+      size_t exponent = 0;
+
+      if (++i < body.size() && (body[i] == '+' || body[i] == '-')) {
+        ++i;
+      }
+      for (; i < body.size() && is_digit(body[i]); ++i) {
+        ++exponent;
+      }
+      if (exponent == 0) {
+        return false;
+      }
+    }
+    if (i != body.size()) {
+      return false;
+    }
+  }
+  errno = 0;
+  value = std::strtod(text.c_str(), nullptr);
+  return !(errno == ERANGE && std::isinf(value));
+}
+
+// Appends @a value with the fewest significant digits, from @a min to @a max, 
that parse back to the same value.  With
+// @a single, the digits must parse back to the same float.  NaN and the 
infinities get their Prometheus spellings.
+void
+append_number(std::string &out, double value, int min, int max, bool single)
+{
+  if (std::isnan(value)) {
+    out += "NaN";
+    return;
+  }
+  if (std::isinf(value)) {
+    out += value > 0 ? "+Inf" : "-Inf";
+    return;
+  }
+
+  char buffer[32];
+  int  length = 0;
+
+  for (int precision = min; precision <= max; ++precision) {
+    length = snprintf(buffer, sizeof(buffer), "%.*g", precision, value);
+    if (single ? std::strtof(buffer, nullptr) == static_cast<float>(value) : 
std::strtod(buffer, nullptr) == value) {
+      break;
+    }
+  }
+  out.append(buffer, length);
+}
+
+std::string
+join(const std::vector<std::string> &names)
+{
+  std::string result;
+
+  for (const std::string &name : names) {
+    if (!result.empty()) {
+      result += ", ";
+    }
+    result += name;
+  }
+  return result;
+}
+} // namespace
+
+std::string_view
+prometheus_type_name(PrometheusType type)
+{
+  switch (type) {
+  case PrometheusType::COUNTER:
+    return "counter";
+  case PrometheusType::GAUGE:
+    return "gauge";
+  case PrometheusType::UNTYPED:
+    break;
+  }
+  return "untyped";
+}
+
+void
+prometheus_escape_label_value(std::string &out, std::string_view value)
+{
+  for (char c : value) {
+    switch (c) {
+    case '\\':
+      out += "\\\\";
+      break;
+    case '"':
+      out += "\\\"";
+      break;
+    case '\n':
+      out += "\\n";
+      break;
+    default:
+      out += c;
+      break;
+    }
+  }
+}
+
+void
+prometheus_escape_help_text(std::string &out, std::string_view text)
+{
+  for (char c : text) {
+    switch (c) {
+    case '\\':
+      out += "\\\\";
+      break;
+    case '\n':
+      out += "\\n";
+      break;
+    default:
+      out += c;
+      break;
+    }
+  }
+}
+
+void
+PrometheusRenderer::begin()
+{
+  ++_renders;
+  _position = 0;
+  _stats    = {};
+}
+
+void
+PrometheusRenderer::add(const char *name, TSRecordDataType data_type, const 
TSRecordData &datum)
+{
+  uint32_t const position = _position++;
+  uint32_t       index;
+
+  if (position < _slots.size() && _slots[position].name == name && 
_records[_slots[position].record].data_type == data_type) {
+    index = _slots[position].record;
+  } else {
+    index = find(name, data_type);
+    if (position < _slots.size()) {
+      _slots[position] = {name, index};
+    } else {
+      _slots.push_back({name, index});
+    }
+  }
+
+  Record &record     = _records[index];
+  record.last_render = _renders;
+  record.datum       = datum;
+  if (record.value == Value::TEXT_LABEL || record.value == Value::TEXT_NUMBER) 
{
+    // The string is valid only while TSRecordDump calls back.
+    _info[index].text.assign(datum.rec_string != nullptr ? datum.rec_string : 
"");
+  } else if (record.value == Value::NONE && _info[index].invalid) {
+    ++_stats.dropped;
+  }
+}
+
+uint32_t
+PrometheusRenderer::find(const char *name, TSRecordDataType data_type)
+{
+  if (auto it = _by_pointer.find(name); it != _by_pointer.end() && 
_records[it->second].data_type == data_type) {
+    return it->second;
+  }
+
+  auto [it, added] = _by_name.try_emplace(name, 0);
+
+  if (added || _records[it->second].data_type != data_type) {
+    it->second = translate(it->first, data_type);
+  }
+  _by_pointer[name] = it->second;
+  return it->second;
+}
+
+uint32_t
+PrometheusRenderer::add_record(std::string_view name, TSRecordDataType 
data_type)
+{
+  auto const index = static_cast<uint32_t>(_records.size());
+
+  _records.emplace_back().data_type = data_type;
+  _info.emplace_back().name         = name;
+  _writers.push_back({index, 0});
+  return index;
+}
+
+uint32_t
+PrometheusRenderer::add_family(const std::string &name, std::string_view 
record_name, PrometheusType type, uint32_t record)
+{
+  auto [it, added] = _family_index.try_emplace(name, 
static_cast<uint32_t>(_families.size()));
+
+  if (added) {
+    Family &family = _families.emplace_back();
+
+    _family_info.push_back({name, record});
+    _reorder    = true;
+    family.type = type;
+    if (_options.help) {
+      family.header.append("# HELP ").append(name).append(" ");
+      prometheus_escape_help_text(family.header, record_name);
+      family.header.append("\n");
+    }
+    if (type != PrometheusType::UNTYPED) {
+      family.header.append("# TYPE ").append(name).append(" 
").append(prometheus_type_name(type)).append("\n");
+    }
+  }
+  return it->second;
+}
+
+uint32_t
+PrometheusRenderer::translate(std::string_view name, TSRecordDataType 
data_type)
+{
+  if (_options.rules != nullptr) {
+    return translate_rules(name, data_type);
+  }
+
+  uint32_t const index = add_record(name, data_type);
+
+  if (!is_numeric(data_type)) {
+    Dbg(dbg_ctl, "Prometheus supports only numeric values, skipping: %.*s", 
static_cast<int>(name.size()), name.data());
+  } else if (PrometheusName translated = _options.namer(name, data_type); 
!translated.family.empty()) {
+    Record &record = _records[index];
+
+    record.value        = Value::NUMBER;
+    record.type         = translated.type;
+    _info[index].family = add_family(translated.family, name, translated.type, 
index);
+
+    Family &family = _families[_info[index].family];
+
+    if (family.type != translated.type) {
+      Dbg(dbg_ctl, "Inconsistent types for metric family %s: %.*s is %s, the 
family is %s", translated.family.c_str(),
+          static_cast<int>(name.size()), name.data(), 
prometheus_type_name(translated.type).data(),
+          prometheus_type_name(family.type).data());
+    }
+    record.prefix = std::move(translated.family);
+    if (!translated.labels.empty()) {
+      record.prefix.append("{").append(translated.labels).append("}");
+    }
+    record.prefix += ' ';
+    family.members.push_back(index);

Review Comment:
   The no-rules renderer does not deduplicate series. The production v1 namer 
sanitizes metric names many-to-one (for example, both `a.b` and `a_b` become 
the unlabeled series `a_b`), so adding both records here makes one scrape emit 
`a_b` twice. Prometheus requires each label set to be unique within a scrape 
and may reject the scrape as containing duplicate samples. Track the generated 
prefix in this path and suppress later records with the same family and labels, 
as the rules path already does.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to