Files
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

98 lines
4.3 KiB
C#

using System.Collections.Concurrent;
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;
}
/// <summary>Alerts this process decided to raise, per kind (OPEN-58). The
/// kinds are a fixed set written in this codebase — <c>server_error_streak</c>,
/// <c>candidate_ban</c>, <c>rule_match</c>, <c>rate_breach</c> — 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".
/// </summary>
private readonly ConcurrentDictionary<string, long> _raised = new(StringComparer.Ordinal);
/// <summary>A snapshot for the scrape, not the live map.</summary>
public IReadOnlyDictionary<string, long> RaisedByKind()
=> new Dictionary<string, long>(_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<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.
// 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);
}
}
}