using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenWaf.Domain.Security; namespace OpenWaf.Infrastructure.Persistence; /// /// Raises operator-visible alerts. Two kinds exist and they mean different /// things: server_error_streak is "your upstream is failing" (Q3: never /// a reason to ban, always a reason to look), and candidate_ban is "the /// engine would have banned this source" — which is what makes Observe mode /// worth having, because without it a dry run is invisible. /// public sealed class AlertWriter { private readonly IServiceScopeFactory _scopeFactory; private readonly DurabilityHealth _health; private readonly ILogger _log; private readonly AlertNotifier _notifier; public AlertWriter( IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger log, AlertNotifier notifier) { _scopeFactory = scopeFactory; _health = health; _log = log; _notifier = notifier; } /// Alerts this process decided to raise, per kind (OPEN-58). The /// kinds are a fixed set written in this codebase — server_error_streak, /// candidate_ban, rule_match, rate_breach — 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". /// private readonly ConcurrentDictionary _raised = new(StringComparer.Ordinal); /// A snapshot for the scrape, not the live map. public IReadOnlyDictionary RaisedByKind() => new Dictionary(_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(); 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. // Queuing is awaited now because the queue is a row: a delivery that // was never written down is a delivery that will not happen, and the // caller has to know that rather than assume it (OPEN-60). await _notifier.EnqueueAsync(alert, ct); } 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); } } }