using System.Globalization;
using System.Text;
namespace OpenWaf.Domain.Observability;
/// What a metric family is, in the one word the exposition format
/// spells after # TYPE. Counter and gauge are the two that mean
/// something to a scraper: a counter is expected to only ever go up, and a
/// PromQL rate() over it assumes exactly that, so labelling a level as a
/// counter is how a restart starts looking like a drop in traffic.
public enum MetricKind
{
Counter,
Gauge
}
///
/// One metric family: a name, a type, a help line, and the samples under it.
///
/// This is the whole Prometheus surface of the edge, so it is deliberately a
/// tiny pure type in the domain project rather than a dependency on a
/// metrics library. The reference repo pulls in a client library and hands it
/// counters scattered across the pipeline; here the numbers already exist in
/// one place (OPEN-58) and the only job left is to write them out in the
/// spelling a scraper accepts. A pure type is also what makes the format
/// testable: escaping, ordering and the empty case are the parts that break a
/// scrape, and none of them need a running edge to check.
///
public sealed class MetricFamily
{
private readonly List<(string Labels, double Value)> _samples = [];
private MetricFamily(string name, MetricKind kind, string help)
{
Name = name;
Kind = kind;
Help = help;
}
public string Name { get; }
public MetricKind Kind { get; }
public string Help { get; }
/// A family with no sample renders nothing. A gauge that has no
/// meaning yet — "the geo database's build date" before a database is
/// loaded — is better absent than a zero that reads as an answer.
public bool HasSamples => _samples.Count > 0;
public IReadOnlyList<(string Labels, double Value)> Samples => _samples;
public static MetricFamily Counter(string name, string help) => New(name, MetricKind.Counter, help);
public static MetricFamily Gauge(string name, string help) => New(name, MetricKind.Gauge, help);
private static MetricFamily New(string name, MetricKind kind, string help)
{
if (!IsValidMetricName(name))
throw new ArgumentException($"'{name}' is not a valid Prometheus metric name.", nameof(name));
return new MetricFamily(name, kind, help);
}
/// Add one sample. Label values are escaped here rather than at
/// render time so a value can never reach the body unescaped by way of a
/// caller that forgot to think about it.
public MetricFamily With(double value, params (string Name, string Value)[] labels)
{
var sb = new StringBuilder();
if (labels.Length > 0)
{
sb.Append('{');
for (var i = 0; i < labels.Length; i++)
{
if (i > 0) sb.Append(',');
if (!IsValidLabelName(labels[i].Name))
throw new ArgumentException(
$"'{labels[i].Name}' is not a valid Prometheus label name.", nameof(labels));
sb.Append(labels[i].Name).Append("=\"").Append(EscapeLabelValue(labels[i].Value)).Append('"');
}
sb.Append('}');
}
_samples.Add((sb.ToString(), value));
return this;
}
public MetricFamily With(long value, params (string Name, string Value)[] labels)
=> With((double)value, labels);
/// Metric names are a small alphabet. A name outside it is not
/// "unusual", it is a line a scraper rejects, and the failure lands in the
/// operator's alerting rather than in this process — so the throw is here,
/// where the mistake is made, and the tests can pin it.
private static bool IsValidMetricName(string name)
{
if (string.IsNullOrEmpty(name)) return false;
for (var i = 0; i < name.Length; i++)
{
var c = name[i];
var ok = c is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or '_' or ':' || (i > 0 && c is >= '0' and <= '9');
if (!ok) return false;
}
return true;
}
/// Label names may not start with a digit, and __ is
/// reserved for the scraper's own internal use.
private static bool IsValidLabelName(string name)
{
if (string.IsNullOrEmpty(name) || name.StartsWith("__", StringComparison.Ordinal)) return false;
for (var i = 0; i < name.Length; i++)
{
var c = name[i];
if (c is not (>= 'a' and <= 'z' or >= 'A' and <= 'Z' or '_' or >= '0' and <= '9')) return false;
}
return char.IsAsciiLetter(name[0]) || name[0] == '_';
}
/// The three escapes the format defines for a quoted label value.
/// A backslash or a quote left raw ends the quoted string early and the
/// rest of the line is a parse error; a raw newline splits one sample into
/// two lines, and the second one reads as a malformed sample.
internal static string EscapeLabelValue(string value)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
var needs = false;
for (var i = 0; i < value.Length && !needs; i++)
needs = value[i] is '"' or '\\' or '\n' or '\r';
if (!needs) return value;
var sb = new StringBuilder(value.Length + 8);
foreach (var c in value)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
default: sb.Append(c); break;
}
}
return sb.ToString();
}
}
/// Renders families as a Prometheus exposition. Pure: no I/O, no
/// clock, no state between calls, so the same families always render the same
/// bytes and the tests can compare the body itself.
public static class PrometheusText
{
/// The format version is part of the content type, and a scraper
/// that is asked for a version it does not know behaves differently from one
/// that is asked for nothing.
public const string ContentType = "text/plain; version=0.0.4; charset=utf-8";
public static string Render(IEnumerable families)
{
var sb = new StringBuilder();
foreach (var family in families)
{
if (family is null || !family.HasSamples) continue;
sb.Append("# HELP ").Append(family.Name).Append(' ').Append(EscapeHelp(family.Help)).Append('\n');
sb.Append("# TYPE ").Append(family.Name).Append(' ')
.Append(family.Kind == MetricKind.Counter ? "counter" : "gauge").Append('\n');
// Ordered, because the body is read by a human during an incident
// and diffed by the tests. An unordered body makes "this line
// changed" impossible to see.
foreach (var sample in family.Samples.OrderBy(s => s.Labels, StringComparer.Ordinal))
{
// NaN and +Inf are legal in the format and useless here: a
// gauge that is NaN is a number this edge does not have, and
// exporting it as one is how an alert on "value dropped" fires.
if (double.IsNaN(sample.Value) || double.IsInfinity(sample.Value)) continue;
sb.Append(family.Name).Append(sample.Labels).Append(' ')
.Append(Format(sample.Value)).Append('\n');
}
}
return sb.ToString();
}
/// HELP is free text, but it is free text on one line: a newline
/// in it would put an unparseable line into the body, and a backslash would
/// start an escape nothing is going to close.
private static string EscapeHelp(string help)
=> help.Replace("\\", "\\\\").Replace("\n", " ").Replace("\r", " ");
/// Whole numbers stay whole — a counter written as 3.0 is
/// legal but reads as a measurement rather than a count — and everything is
/// invariant-culture, because a comma as a decimal separator is a parse
/// error in a Prometheus file.
private static string Format(double value)
=> value == Math.Truncate(value) && !double.IsInfinity(value)
? value.ToString("0.###", CultureInfo.InvariantCulture)
: value.ToString("0.##########", CultureInfo.InvariantCulture);
}