using OpenWaf.Domain.Engine; namespace OpenWaf.Edge.Observability; /// /// What this process has done to the traffic it has seen, one counter per /// verdict (OPEN-58). /// /// The guard already names every request it refuses in the log and every /// request it passes goes to the origin; what it did not have was a number /// anyone could scrape. This is that number, and it is deliberately the only /// new state the metrics endpoint needs: the rest of what /metrics reports is /// state the edge was already keeping. /// /// Two things are on purpose here. /// /// It counts the FINAL verdict, in the guard, at the one place that decides — /// counting in two places is how a request ends up counted twice and a counter /// whose total does not add up is worse than no counter. /// /// It is per process, like the rate counter (OPEN-56) and unlike the block /// list. A Prometheus counter is normally summed across instances by the query, /// which is exactly the right answer for "how many requests did this fleet /// refuse", and there is no shared version to choose because a shared counter /// would cost a round trip on a path whose measured p95 is ~3 ms. /// public sealed class EdgeCounterLedger { /// The verdicts are a contiguous enum from 0, so the counter store /// is an array indexed by the value rather than a dictionary keyed by a /// string: no allocation per request, and no way to count a name that is /// not a verdict. private const int VerdictCount = 9; private readonly long[] _counts = new long[VerdictCount]; /// The label the exposition gives this verdict. Lower-case, /// snake_case, and spelled the way the log spells it, so the same word /// appears in the alert and in the line an operator greps for. public static string LabelFor(EdgeVerdict verdict) => EdgeVerdictLabel.For(verdict); /// Every verdict the edge can answer with, in label form. The /// exposition emits all of them, including the zeros: a counter that is /// absent until it fires is a query that returns nothing rather than zero, /// and "nothing matched" and "this metric does not exist in this build" /// look the same in a graph. public static IReadOnlyList VerdictLabels { get; } = Enum.GetValues().Select(LabelFor).ToArray(); public void Record(EdgeVerdict verdict) { var index = (int)verdict; if (index < 0 || index >= VerdictCount) return; Interlocked.Increment(ref _counts[index]); } /// The counts as they stood at this instant. A scrape reads a /// snapshot rather than the live array, so a burst of traffic in the middle /// of a scrape cannot produce a body whose totals disagree with each other /// by more than the traffic that arrived while it was being written. public long[] Snapshot() { var copy = new long[VerdictCount]; for (var i = 0; i < VerdictCount; i++) copy[i] = Interlocked.Read(ref _counts[i]); return copy; } public long Total() => Snapshot().Sum(); }