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; public AlertWriter(IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger log) { _scopeFactory = scopeFactory; _health = health; _log = log; } public async Task RaiseAsync( string kind, string sourceKey, int count, int? statusCode, string? path, string detail, CancellationToken ct = default) { try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.Alerts.Add(new EdgeAlert { Kind = kind, SourceKey = sourceKey, Count = count, LastStatusCode = statusCode, LastPath = path, Detail = detail.Length > 1024 ? detail[..1024] : detail, CreatedAt = DateTimeOffset.UtcNow }); await db.SaveChangesAsync(ct); _health.RecordSuccess(DurabilityHealth.Alerts, 1); } 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); } } }