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

112 lines
4.7 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Unit;
/// <summary>
/// The push timeout is the bound on how long one dead endpoint may hold a queue
/// worker, so it is parsed the way the other startup-parsed bounds are: a typo
/// stops the process and names the key. A 0-second timeout drops every push and
/// a 600-second one parks the worker on an endpoint that is not answering —
/// neither is what the operator typed, and both look like a quiet night.
/// </summary>
public sealed class AlertWebhookBoundsTests
{
[Theory]
[InlineData(null, 5)]
[InlineData("", 5)]
[InlineData(" ", 5)]
[InlineData("1", 1)]
[InlineData(" 7 ", 7)]
[InlineData("60", 60)]
public void Unset_means_five_and_a_whole_number_means_what_it_says(string? configured, int expected)
=> Assert.Equal(expected, AlertNotifier.ParseTimeoutSeconds(configured));
[Theory]
[InlineData("0")]
[InlineData("-5")]
[InlineData("61")]
[InlineData("600")]
[InlineData("abc")]
[InlineData("5.5")]
[InlineData("5s")]
public void Anything_else_names_the_key_and_refuses_to_start(string configured)
{
var ex = Assert.Throws<InvalidOperationException>(() => AlertNotifier.ParseTimeoutSeconds(configured));
Assert.Contains("OpenWaf:Alerts:WebhookTimeoutSeconds", ex.Message);
Assert.Contains(configured, ex.Message);
}
[Theory]
[InlineData(null, false)]
[InlineData("", false)]
[InlineData(" ", false)]
[InlineData("https://hooks.example.test/abc", true)]
public void An_empty_endpoint_is_no_endpoint(string? url, bool configured)
{
var notifier = Build(url);
Assert.Equal(configured, notifier.IsConfigured);
}
[Fact]
public void The_endpoint_is_reported_as_a_host_never_as_a_url()
{
// A webhook URL carries its secret in the path — that is how the common
// providers work — and this value is echoed to the operator page.
var notifier = Build("https://hooks.example.test/notify/secret-token-123");
Assert.Equal("hooks.example.test", notifier.WebhookHost);
}
[Fact]
public async Task A_delivery_that_could_not_be_queued_is_counted_as_lost_rather_than_assumed_sent()
{
// The queue used to be a bounded channel in this process, and its
// overflow was the counted loss. The queue is a table now, so the
// equivalent failure is the write that never happened: the alert row is
// in the database, the operator can read it, and nobody was ever going to
// be told. Assuming the delivery in that moment is the silence this
// whole pillar exists to remove.
var health = new DurabilityHealth();
var notifier = new AlertNotifier(
new Microsoft.Extensions.DependencyInjection.ServiceCollection().BuildServiceProvider()
.GetRequiredService<Microsoft.Extensions.DependencyInjection.IServiceScopeFactory>(),
health,
Microsoft.Extensions.Logging.Abstractions.NullLogger<AlertNotifier>.Instance,
"https://hooks.example.test/notify", 5, 6, 30);
var queued = await notifier.EnqueueAsync(new EdgeAlert
{
Kind = "server_error_streak", SourceKey = "203.0.113.9", Count = 3,
LastStatusCode = 502, LastPath = "/checkout", Detail = "d",
CreatedAt = DateTimeOffset.UtcNow
});
Assert.False(queued);
var pillar = health.Get(AlertNotifier.Pillar);
Assert.True(pillar.Failing, pillar.ToString());
Assert.Equal(1, pillar.EntriesLost);
Assert.Contains("could not be queued", pillar.LastError);
}
[Fact]
public async Task An_unconfigured_endpoint_queues_nothing_and_reports_nothing()
{
// "No webhook" is a configuration, not a failure: no row is written, no
// counter moves, and the surface says the push is off rather than that it
// is failing.
var health = new DurabilityHealth();
var notifier = Build(null);
var queued = await notifier.EnqueueAsync(new EdgeAlert { Kind = "candidate_ban", SourceKey = "203.0.113.9" });
Assert.False(queued);
Assert.False(health.Get(AlertNotifier.Pillar).Failing);
}
private static AlertNotifier Build(string? url) => new(
new Microsoft.Extensions.DependencyInjection.ServiceCollection().BuildServiceProvider()
.GetRequiredService<Microsoft.Extensions.DependencyInjection.IServiceScopeFactory>(),
new DurabilityHealth(),
Microsoft.Extensions.Logging.Abstractions.NullLogger<AlertNotifier>.Instance,
url, 5, 6, 30);
}