Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/AlertWriter.cs
T
Pavlo Ratushnyi 2b0163aa80 A pillar that could not write kept answering with the count it had before the break
The read side got its counters last cycle; the write side was still catching
everything, logging one line and keeping the process alive. A failed write is
worse than a failed read - the row never existed and no later request brings it
back - and the surface hid it better. Measured on the shipped image with SQLite
triggers aborting every INSERT/UPDATE on source_observations and edge_alerts
while reads kept working: three new sources refused and a six-request 5xx storm
later, GET /admin-api/observations answered 200 with the same X-Total-Count it
had before the break (46), GET /admin-api/alerts still showed its one row,
/healthz and /readyz were 200, /admin-api/state had no write-side field at all,
and the log carried "flush failed, 4 entries dropped" plus two "could not
persist".

DurabilityHealth counts each writer separately; /state reports
observationWriteFailures/observationsLost/observationLastWriteError,
alertWriteFailures/alertsLost and retentionPruneFailures; /readyz answers 503
naming the pillar, the rows lost and the innermost error rather than EF's
wrapper. A counter clears only on a successful write of its own pillar, and
retention is reported without being a readiness failure - stated in code, with
the reason.

Teeth: WriteFailureVisibilityTests (5) - 5 failed / 0 passed before the fix.
Gates: compose-smoke 53 -> 63 (blocks writes with triggers, asserts the
unchanged X-Total-Count as the lie, and heals per pillar), smoke.sh 25 -> 28,
console-check 53 -> 57.
2026-10-02 08:26:45 +02:00

67 lines
2.5 KiB
C#

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;
public AlertWriter(IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger<AlertWriter> 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<OpenWafDbContext>();
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);
}
}
}