Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/AlertWriter.cs
T
Pavlo Ratushnyi 5c7b0bef3b an alert can be pushed to an endpoint, so a 03:00 outage reaches something that acts
The alerting pillar ended at a table. The rows are right — the server-error
streak fires, the dry-run candidate is recorded — and then they wait for an
operator to open a page. That is the posture this project already removed for
blocking ("blocking is usually manual: a human notices abuse and adds an IP.
That never fires at 3am"), applied one level up: an alert nobody is told about
never fires at 3am either.

OpenWaf:Alerts:WebhookUrl (env fallback OPENWAF_ALERT_WEBHOOK_URL) POSTs each
raised alert as JSON — kind, sourceKey, count, lastStatusCode, lastPath,
createdAt, detail — off the request path, from a bounded queue of 1000, and only
after the row is durably written. Three attempts with a short backoff;
OpenWaf:Alerts:WebhookTimeoutSeconds (1-60, default 5) refuses startup outside
that range rather than falling back, as the other startup-parsed bounds do. The
default is empty, which is no push at all: the shipped stack behaves exactly as
it did before.

The endpoint is counted like every other write side pillar, because a webhook
that has been down for a week is otherwise indistinguishable from a quiet night:
alertWebhookFailures, alertWebhookLost, alertWebhookDelivered,
alertWebhookLastError, alertWebhookLastSuccessAt, plus alertWebhookConfigured and
alertWebhookHost — host, never the URL, since a webhook URL carries its secret
in the path and this is rendered on the operator page. The console's alert line
now ends in "pushed to <host>, N delivered" or "not pushed anywhere: each row
waits for someone to open this page", so "no alerts" and "alerts go nowhere" stay
two different sentences.

Two things the tests caught instead of the design assuming:
 * the queue was BoundedChannelFullMode.DropWrite, where TryWrite returns true
   and the overflow vanishes with no trace — the counter it was written to feed
   stayed at zero. The mode is Wait now, chosen for what TryWrite reports when
   the queue is full; nothing here awaits a write, so the response path still
   cannot block.
 * a refused push counted as an entry lost, which conflated a lost delivery with
   a lost record. The alert row is in the table either way, so EntriesLost on
   this pillar is reserved for the one case where the push is gone for good.

Measured on this tree: build 0 warnings / 0 errors, unit 151/151 (19 new),
integration 194/194 in 28 s (3 new: the push arrives with the alert in it, an
unconfigured edge sends nothing and keeps every row, an endpoint answering 500 is
counted and does not undo the alert), smoke 29/0, console 79 assertions 0 failed,
compose 209/0 against the built image at 261 MB.
2026-10-04 18:18:25 +02:00

76 lines
2.9 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;
private readonly AlertNotifier _notifier;
public AlertWriter(
IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger<AlertWriter> log,
AlertNotifier notifier)
{
_scopeFactory = scopeFactory;
_health = health;
_log = log;
_notifier = notifier;
}
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>();
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);
}
}
}