Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.cs
T
Pavlo Ratushnyi d635a00078 an alert that could not be pushed is pushed later, and says so while it waits
The push queue was a channel in one process: three attempts inside one request of work, then the row was simply no longer owed to anybody. An endpoint down for ten minutes swallowed every alert raised in that window, and a restart swallowed everything still waiting. The alert table stayed correct the whole time, which is exactly what made the hole invisible from the surface.

What is owed is now a row in alert_pushes: denormalised payload (retention prunes edge_alerts, and a delivery still owed must not go with the row it was copied from), attempts, next-attempt time, last error, and a claim so two edges over one database send each row once. Attempts are configuration (OpenWaf:Alerts:MaxPushAttempts, PushRetrySeconds), validated at startup like the other bounds; when they run out the row records that and the surface says how many were given up, because a counter that cannot tell 'still retrying' from 'stopped retrying' is the blindness this item removes.

Surfaces: /admin-api/state answers alertPushPending/Delivered/GivenUp/OldestPendingAt/LastError from the table, /metrics publishes the same as gauges from a cache no older than 5s (the metrics endpoint's rule is that it never leans on the database per scrape). Retention prunes only rows that are finished.

What the run caught, in order: (1) SchemaUpgradeTests hardcoded the migration count as a literal, so the new migration turned a working upgrade into a red test - the count is now read from the migrations assembly. (2) Two of the new queue tests asserted 'pending == 0' after waiting only for 'delivered >= 1'; one scene raises more than one alert, so the read landed between two rows and failed on a correct product - the wait now requires the queue to have emptied. (3) The whole integration suite answered 9 failures of 251, every one 'Timed out waiting for the entry point to build the IHost after 00:05:00', while the identical build minutes later answered 251/251 in 34s: a test host that cannot bind a loopback socket fails as a timeout, and the README now says so next to the scheduling note that used to be the only explanation on file.

Gates on this tree: build 0 warnings / 0 errors, unit 277/277, integration 251/251 in 34s, smoke 68 passed / 0 failed (3 new), image 261 MB, compose-smoke 232 passed / 0 failed with 0 containers left behind (2 new, including the push-queue table being added by the edge to a volume that predates it), console 90 assertions / 0 failed.

Refs OPEN-60.
2026-10-05 03:21:39 +02:00

356 lines
16 KiB
C#

using System.Net.Http.Json;
using System.Threading.Channels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Tells somebody about the alerts the edge raised (OPEN-53), and keeps trying
/// until it can (OPEN-60).
///
/// The alerting pillar used to end at a table. That is the same posture this
/// project removed for blocking — "blocking is usually manual: a human notices
/// abuse and adds an IP. That never fires at 3am" — applied to alerts: the row
/// exists, is correct, and is read by nobody until the morning.
///
/// The first version of the push fixed that and introduced a quieter hole: the
/// queue of "not pushed yet" was a channel in one process, so a delivery got
/// three attempts inside one attempt, and then it was gone for good. An endpoint
/// down for ten minutes swallowed every alert raised in that window, and a
/// restart swallowed everything still waiting. Measured here rather than assumed:
/// with the endpoint refusing, the alert row was there, the counter said the push
/// failed, and nothing ever asked again.
///
/// So the queue is a table now. Three properties follow from that and each is a
/// decision:
///
/// * <b>Eventually, across a restart.</b> A row that is still owed is picked up
/// by the next process that starts, which is the difference between "the
/// endpoint was down during the outage" and "the operator was never told".
/// * <b>Bounded, and honest about the bound.</b> Attempts are configuration,
/// validated at startup; when they run out the row records that, and the
/// surface says how many were given up. A counter that cannot tell "still
/// retrying" from "stopped retrying" is the blindness this item removes.
/// * <b>Claimed before it is sent.</b> Two edges sharing one database would
/// otherwise push the same alert twice, and a duplicate page at 03:00 is not a
/// harmless bug. A claim left by a process that died is taken over after a
/// bounded window, so a crash delays a delivery rather than losing it.
///
/// The database row of the alert stays the record of truth: a refused push does
/// not undo an alert, and the request path never waits on the webhook.
/// </summary>
public sealed class AlertNotifier : BackgroundService
{
public const string Pillar = "alertWebhook";
/// <summary>How long one HTTP attempt may take. Out of range refuses startup
/// rather than falling back: a 0-second timeout drops every push, and a
/// 600-second one parks the worker on a dead endpoint — the same reasoning as
/// <c>OpenWaf:State:RefreshTtlSeconds</c>.</summary>
public const int TimeoutSecondsFloor = 1, TimeoutSecondsCeiling = 60;
/// <summary>How often the worker looks for owed deliveries. Not on any
/// request path, and a fresh enqueue wakes it immediately, so this is only
/// the ceiling on how long a delivery waits when nothing else is happening.</summary>
private const int PollSeconds = 2;
private const int BatchSize = 20;
/// <summary>How often the cached queue counts are refreshed. <c>/metrics</c>
/// reads the cache rather than issuing a query per scrape — the metrics
/// endpoint's rule is that it never leans on the database — so the gauge is
/// labelled with that bound. <c>/admin-api/state</c> reads the table, because
/// an operator asking directly should get the current answer.</summary>
private static readonly TimeSpan CountsRefresh = TimeSpan.FromSeconds(5);
public static int ParseTimeoutSeconds(string? configured)
{
if (string.IsNullOrWhiteSpace(configured)) return 5;
if (!int.TryParse(configured, out var seconds)
|| seconds < TimeoutSecondsFloor || seconds > TimeoutSecondsCeiling)
throw new InvalidOperationException(
$"OpenWaf:Alerts:WebhookTimeoutSeconds must be a whole number of seconds between "
+ $"{TimeoutSecondsFloor} and {TimeoutSecondsCeiling}; got {configured}");
return seconds;
}
private readonly IServiceScopeFactory _scopeFactory;
private readonly DurabilityHealth _health;
private readonly ILogger<AlertNotifier> _log;
private readonly string? _url;
private readonly HttpClient _http;
private readonly int _maxAttempts;
private readonly int _retryBaseSeconds;
/// <summary>Identifies this process in a claim. Machine plus pid plus a
/// random suffix, because two edges on one host share a pid namespace in a
/// container and a stale claim has to name who left it.</summary>
private readonly string _processId =
$"{Environment.MachineName}-{Environment.ProcessId}-{Guid.NewGuid().ToString("N")[..8]}";
private readonly Channel<byte> _wake = Channel.CreateBounded<byte>(
new BoundedChannelOptions(16) { FullMode = BoundedChannelFullMode.DropWrite, SingleReader = true });
private volatile PushQueueCounts _counts = new(0, 0, 0, null, null);
private DateTimeOffset _countsAt = DateTimeOffset.MinValue;
/// <summary>Host only, never the URL: webhook URLs routinely carry the
/// secret in the path, and this is echoed to the operator page and the log.</summary>
public string? WebhookHost { get; }
public bool IsConfigured => _url is not null;
/// <summary>The queue as this process last measured it. Cached on purpose:
/// <c>/metrics</c> and <c>/admin-api/state</c> read it without touching the
/// database, so a scrape cannot become a query per poll.</summary>
public PushQueueCounts Counts => _counts;
public AlertNotifier(
IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger<AlertNotifier> log,
string? webhookUrl, int timeoutSeconds, int maxPushAttempts, int retryBaseSeconds)
{
_scopeFactory = scopeFactory;
_health = health;
_log = log;
_url = string.IsNullOrWhiteSpace(webhookUrl) ? null : webhookUrl.Trim();
WebhookHost = _url is null ? null : new Uri(_url).Host;
_maxAttempts = maxPushAttempts;
_retryBaseSeconds = retryBaseSeconds;
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(timeoutSeconds) };
}
/// <summary>Queue one delivery, durably. Returns false when the queue itself
/// could not be written, which is a lost delivery and is counted as one —
/// the alert row still exists, so what is lost is the telling.</summary>
public async Task<bool> EnqueueAsync(EdgeAlert alert, CancellationToken ct = default)
{
if (_url is null) return false;
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
db.AlertPushes.Add(new AlertPush
{
AlertId = alert.Id,
Kind = alert.Kind,
SourceKey = alert.SourceKey,
Count = alert.Count,
LastStatusCode = alert.LastStatusCode,
LastPath = alert.LastPath,
Detail = alert.Detail,
AlertCreatedAt = alert.CreatedAt,
CreatedAt = DateTimeOffset.UtcNow,
NextAttemptAt = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync(ct);
_wake.Writer.TryWrite(0);
return true;
}
catch (Exception ex)
{
_health.RecordFailure(Pillar, $"the delivery could not be queued: {ex.Message}", 1);
_log.LogWarning(ex, "AlertNotifier: could not queue a {Kind} delivery for {Key}.", alert.Kind, alert.SourceKey);
return false;
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (_url is null) return;
// Nothing is replayed from memory on purpose: whatever this process was
// holding is in the table, and whatever a previous process left is picked
// up here. That is the whole of "eventually".
while (!stoppingToken.IsCancellationRequested)
{
try
{
await DrainAsync(stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
// The queue itself is unreachable. Counted, because a worker that
// cannot read its own queue is the same blindness as an endpoint
// that is down, and quieter.
_health.RecordFailure(Pillar, ex);
_log.LogWarning(ex, "AlertNotifier: the delivery queue could not be read.");
}
using var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
wait.CancelAfter(TimeSpan.FromSeconds(PollSeconds));
try { _ = await _wake.Reader.ReadAsync(wait.Token); }
catch (OperationCanceledException) { }
}
}
/// <summary>One pass over the owed deliveries: claim a batch atomically, then
/// send each one.</summary>
private async Task DrainAsync(CancellationToken ct)
{
var now = DateTimeOffset.UtcNow;
var staleClaim = now - PushRetryPolicy.ClaimReclaimWindow;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var due = await db.AlertPushes
.Where(p => p.PushedAt == null && p.GivenUpAt == null
&& (p.NextAttemptAt == null || p.NextAttemptAt <= now)
&& (p.ClaimedBy == null || p.ClaimedAt == null || p.ClaimedAt <= staleClaim))
.OrderBy(p => p.Id)
.Select(p => p.Id)
.Take(BatchSize)
.ToListAsync(ct);
if (due.Count > 0)
{
// The guard is in the UPDATE, not in the code around it: two edges
// reading the same due list at the same moment must end up with the
// row claimed by exactly one of them, and the loser simply finds
// nothing of its own to send.
await db.AlertPushes
.Where(p => due.Contains(p.Id) && p.PushedAt == null && p.GivenUpAt == null
&& (p.ClaimedBy == null || p.ClaimedAt == null || p.ClaimedAt <= staleClaim))
.ExecuteUpdateAsync(s => s
.SetProperty(p => p.ClaimedBy, _processId)
.SetProperty(p => p.ClaimedAt, now), ct);
var rows = await db.AlertPushes
.Where(p => due.Contains(p.Id) && p.ClaimedBy == _processId)
.OrderBy(p => p.Id)
.ToListAsync(ct);
// Saved per row rather than once per batch: a process killed between
// two deliveries must not lose the record of the one it already made,
// because that record is what decides whether the next process retries
// it or gives up on it.
foreach (var row in rows)
{
await DeliverAsync(db, row, now, ct);
await db.SaveChangesAsync(ct);
}
}
await RefreshCountsAsync(db, now, ct);
}
private async Task DeliverAsync(OpenWafDbContext db, AlertPush row, DateTimeOffset now, CancellationToken ct)
{
var (ok, error) = await TryPushAsync(row, ct);
row.Attempts++;
row.ClaimedBy = null;
row.ClaimedAt = null;
row.LastError = error;
if (ok)
{
row.PushedAt = now;
row.NextAttemptAt = null;
_health.RecordSuccess(Pillar, 1);
return;
}
if (PushRetryPolicy.HasGivenUp(row.Attempts, _maxAttempts))
{
// The one case where a delivery is gone for good, so it is the one
// case counted as lost. The alert row is still there; what is lost is
// that nobody was told, and the surface has to be able to say so.
row.GivenUpAt = now;
row.NextAttemptAt = null;
// The row says why it stopped, not only what the last attempt said,
// because the row is what an operator reads an hour later.
row.LastError = $"gave up after {row.Attempts} attempts: {error}";
_health.RecordFailure(Pillar, $"gave up after {row.Attempts} attempts: {error}", 1);
_log.LogWarning(
"AlertNotifier: gave up pushing a {Kind} alert to {Host} after {Attempts} attempts ({Error}).",
row.Kind, WebhookHost, row.Attempts, error);
return;
}
row.NextAttemptAt = now + PushRetryPolicy.NextDelay(row.Attempts, _retryBaseSeconds);
_health.RecordFailure(Pillar, error ?? "the push failed");
_log.LogDebug("AlertNotifier: attempt {Attempt} for a {Kind} alert failed ({Error}); next try at {Next}.",
row.Attempts, row.Kind, error, row.NextAttemptAt);
}
/// <summary>One HTTP attempt. The retry policy lives in the queue now, so the
/// old three-tries-in-a-row loop is gone: a durable backoff and an in-line
/// backoff are the same decision made twice, and the one that survives a
/// restart is the one worth keeping.</summary>
private async Task<(bool Ok, string? Error)> TryPushAsync(AlertPush row, CancellationToken ct)
{
try
{
using var response = await _http.PostAsJsonAsync(_url!, new
{
kind = row.Kind,
sourceKey = row.SourceKey,
count = row.Count,
lastStatusCode = row.LastStatusCode,
lastPath = row.LastPath,
createdAt = row.AlertCreatedAt,
detail = row.Detail,
attempts = row.Attempts + 1
}, ct);
if (response.IsSuccessStatusCode) return (true, null);
// Named with the status, because "the push failed" is not actionable
// and "the endpoint answered 404" is.
return (false, $"the endpoint answered {(int)response.StatusCode}");
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
return (false, ex.Message);
}
}
private async Task RefreshCountsAsync(OpenWafDbContext db, DateTimeOffset now, CancellationToken ct)
{
if (now - _countsAt < CountsRefresh) return;
_counts = await PushQueueCounts.QueryAsync(db, ct);
_countsAt = now;
}
/// <summary>For the surfaces and the tests: the queue as the database holds
/// it, not as this process last cached it.</summary>
public async Task<PushQueueCounts> ReadCountsAsync(CancellationToken ct = default)
{
if (_url is null) return new PushQueueCounts(0, 0, 0, null, null);
using var scope = _scopeFactory.CreateScope();
return await PushQueueCounts.QueryAsync(scope.ServiceProvider.GetRequiredService<OpenWafDbContext>(), ct);
}
/// <summary>Force one pass, for tests and for an operator who wants the queue
/// drained now rather than on the next poll.</summary>
public Task PumpAsync(CancellationToken ct = default) => DrainAsync(ct);
}
/// <summary>The push queue in four numbers and one error. Every one of them is a
/// count of rows rather than an in-process counter, so the answer survives a
/// restart and agrees between edges sharing the database.</summary>
public sealed record PushQueueCounts(
int Pending, int Delivered, int GivenUp, string? LastError, DateTimeOffset? OldestPendingAt)
{
public static async Task<PushQueueCounts> QueryAsync(OpenWafDbContext db, CancellationToken ct)
{
var pending = db.AlertPushes.Where(p => p.PushedAt == null && p.GivenUpAt == null);
return new PushQueueCounts(
await pending.CountAsync(ct),
await db.AlertPushes.CountAsync(p => p.PushedAt != null, ct),
await db.AlertPushes.CountAsync(p => p.GivenUpAt != null, ct),
await db.AlertPushes.Where(p => p.LastError != null)
.OrderByDescending(p => p.Attempts).Select(p => p.LastError).FirstOrDefaultAsync(ct),
await pending.OrderBy(p => p.CreatedAt).Select(p => p.CreatedAt).FirstOrDefaultAsync(ct));
}
}