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.
95 lines
4.1 KiB
C#
95 lines
4.1 KiB
C#
using System.Collections.Concurrent;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using OpenWaf.Domain.Security;
|
|
|
|
namespace OpenWaf.Infrastructure.Persistence;
|
|
|
|
/// <summary>
|
|
/// Raises operator-visible alerts. Two kinds exist and they mean different
|
|
/// things: <c>server_error_streak</c> is "your upstream is failing" (Q3: never
|
|
/// a reason to ban, always a reason to look), and <c>candidate_ban</c> is "the
|
|
/// engine would have banned this source" — which is what makes Observe mode
|
|
/// worth having, because without it a dry run is invisible.
|
|
/// </summary>
|
|
public sealed class AlertWriter
|
|
{
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
private readonly DurabilityHealth _health;
|
|
private readonly ILogger<AlertWriter> _log;
|
|
private readonly AlertNotifier _notifier;
|
|
|
|
public AlertWriter(
|
|
IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger<AlertWriter> log,
|
|
AlertNotifier notifier)
|
|
{
|
|
_scopeFactory = scopeFactory;
|
|
_health = health;
|
|
_log = log;
|
|
_notifier = notifier;
|
|
}
|
|
|
|
/// <summary>Alerts this process decided to raise, per kind (OPEN-58). The
|
|
/// kinds are a fixed set written in this codebase — <c>server_error_streak</c>,
|
|
/// <c>candidate_ban</c>, <c>rule_match</c>, <c>rate_breach</c> — never a value
|
|
/// a visitor types, which is what makes it safe to expose as a label: the
|
|
/// cardinality is the number of things this edge can alert about, not the
|
|
/// number of things that have happened.
|
|
///
|
|
/// It counts the decision, not the write. The durability counters next to it
|
|
/// say whether the row landed, and the two answers are different questions:
|
|
/// "the edge saw a storm" and "the operator can find the storm in the table".
|
|
/// </summary>
|
|
private readonly ConcurrentDictionary<string, long> _raised = new(StringComparer.Ordinal);
|
|
|
|
/// <summary>A snapshot for the scrape, not the live map.</summary>
|
|
public IReadOnlyDictionary<string, long> RaisedByKind()
|
|
=> new Dictionary<string, long>(_raised, StringComparer.Ordinal);
|
|
|
|
public async Task RaiseAsync(
|
|
string kind,
|
|
string sourceKey,
|
|
int count,
|
|
int? statusCode,
|
|
string? path,
|
|
string detail,
|
|
CancellationToken ct = default)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(kind)) _raised.AddOrUpdate(kind, 1, static (_, v) => v + 1);
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var alert = new EdgeAlert
|
|
{
|
|
Kind = kind,
|
|
SourceKey = sourceKey,
|
|
Count = count,
|
|
LastStatusCode = statusCode,
|
|
LastPath = path,
|
|
Detail = detail.Length > 1024 ? detail[..1024] : detail,
|
|
CreatedAt = DateTimeOffset.UtcNow
|
|
};
|
|
db.Alerts.Add(alert);
|
|
await db.SaveChangesAsync(ct);
|
|
_health.RecordSuccess(DurabilityHealth.Alerts, 1);
|
|
// Push only what is durably there, and only after the write: the
|
|
// table is the record of truth, and a push that arrives before the
|
|
// row exists would report an alert the operator then cannot find.
|
|
_notifier.Enqueue(alert);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// Counted, not just logged. The alert table is the whole point of
|
|
// this pillar — "an alert nobody reads is a log line" — and an
|
|
// alert that never reached the table is worse: measured on the
|
|
// shipped image with writes to edge_alerts aborted, a six-request
|
|
// 5xx storm left the alert listing at the one row it already had,
|
|
// /readyz answered "ready", and the storm was invisible to the
|
|
// operator while the upstream was failing.
|
|
_health.RecordFailure(DurabilityHealth.Alerts, ex, 1);
|
|
_log.LogWarning(ex, "AlertWriter: could not persist a {Kind} alert for {Key}.", kind, sourceKey);
|
|
}
|
|
}
|
|
}
|