OPEN-58. The edge had one push surface — the alert webhook, at-most-once, for the four things it can alert about — and every other number it keeps was readable by a human on /admin-api/state and by nothing else. 'The ban writes have been failing for forty minutes' is a pull question with a threshold on it, so it belongs in Prometheus, where the operator already keeps their alerting. The exposition is a pure type in the domain project (PrometheusText) rather than a metrics library: the numbers already exist in one place, and the parts that break a scrape — label escaping, HELP on one line, the name alphabet, NaN, sample ordering — are testable as a string without a running edge. EdgeCounterLedger adds the one piece of new state, counted at the single place that may refuse a request, so the verdict totals add up to the requests answered. Three rules, each a decision: aggregate only (no source key, address, path, user agent or operator note anywhere in the body, and the only labels are bounded sets written in the code — a label per source is a cardinality explosion and an IP leak); no query per scrape (every number is already in memory, so a scrape cannot be what makes an unhealthy database unhealthy for the request path); and behind the same token as the admin API, on an always-pass prefix, so an edge that has blocked the operator's own address is still watchable. The token check moved out of the admin group into AdminAuth rather than being copied. Three things the run caught. The 'closed surface' assertion passed alone and failed under the gate: Program falls back to OPENWAF_ADMIN_TOKEN when the configured token is blank and the gate scripts export a throwaway value into the test process, so a blank token there is an OPEN surface — 401, not 404. The smoke and compose sample helpers grepped for the metric name and matched the '# HELP' line first, answering with the help text's last word; they now match the line prefix. And EndpointFilterDelegate is not what AddEndpointFilter accepts — the two have different arities, which only shows when the filter is a method rather than a lambda at the call site. Gates on this tree: build 0 warnings / 0 errors, unit 250/250, integration 236/236, smoke 60/0, compose 223/0 against the built image (261 MB), console 90/0.
200 lines
8.5 KiB
C#
200 lines
8.5 KiB
C#
using System.Globalization;
|
|
using System.Text;
|
|
|
|
namespace OpenWaf.Domain.Observability;
|
|
|
|
/// <summary>What a metric family is, in the one word the exposition format
|
|
/// spells after <c># TYPE</c>. Counter and gauge are the two that mean
|
|
/// something to a scraper: a counter is expected to only ever go up, and a
|
|
/// PromQL <c>rate()</c> over it assumes exactly that, so labelling a level as a
|
|
/// counter is how a restart starts looking like a drop in traffic.</summary>
|
|
public enum MetricKind
|
|
{
|
|
Counter,
|
|
Gauge
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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; }
|
|
|
|
/// <summary>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.</summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>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.</summary>
|
|
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);
|
|
|
|
/// <summary>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.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>Label names may not start with a digit, and <c>__</c> is
|
|
/// reserved for the scraper's own internal use.</summary>
|
|
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] == '_';
|
|
}
|
|
|
|
/// <summary>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.</summary>
|
|
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();
|
|
}
|
|
|
|
}
|
|
|
|
/// <summary>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.</summary>
|
|
public static class PrometheusText
|
|
{
|
|
/// <summary>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.</summary>
|
|
public const string ContentType = "text/plain; version=0.0.4; charset=utf-8";
|
|
|
|
public static string Render(IEnumerable<MetricFamily> 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();
|
|
}
|
|
|
|
/// <summary>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.</summary>
|
|
private static string EscapeHelp(string help)
|
|
=> help.Replace("\\", "\\\\").Replace("\n", " ").Replace("\r", " ");
|
|
|
|
/// <summary>Whole numbers stay whole — a counter written as <c>3.0</c> 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.</summary>
|
|
private static string Format(double value)
|
|
=> value == Math.Truncate(value) && !double.IsInfinity(value)
|
|
? value.ToString("0.###", CultureInfo.InvariantCulture)
|
|
: value.ToString("0.##########", CultureInfo.InvariantCulture);
|
|
}
|