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.
289 lines
14 KiB
C#
289 lines
14 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// The delivery, not the alert (OPEN-60).
|
|
///
|
|
/// The alert table already had these tests. What is under test here is the
|
|
/// separate promise the webhook added — that somebody is told — and the way that
|
|
/// promise used to fail quietly: the queue of "not pushed yet" lived in one
|
|
/// process's memory, so an endpoint down for ten minutes swallowed every alert
|
|
/// raised in that window, and a restart swallowed everything still waiting. The
|
|
/// alert row was correct the whole time, which is what made it invisible.
|
|
///
|
|
/// So every test here asks the same question in a different way: an alert was
|
|
/// raised, the endpoint could not take it, and does the operator still hear about
|
|
/// it later?
|
|
/// </summary>
|
|
public sealed class AlertPushQueueTests
|
|
{
|
|
private const string Failing = "203.0.113.81";
|
|
|
|
private static async Task<JsonElement> StateAsync(EdgeFixture f)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/state");
|
|
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
|
using var response = await f.Client.SendAsync(request);
|
|
response.EnsureSuccessStatusCode();
|
|
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone();
|
|
}
|
|
|
|
private static async Task<JsonElement> WaitForStateAsync(EdgeFixture f, Func<JsonElement, bool> ready)
|
|
{
|
|
var deadline = DateTime.UtcNow.AddSeconds(25);
|
|
while (true)
|
|
{
|
|
var state = await StateAsync(f);
|
|
if (ready(state) || DateTime.UtcNow > deadline) return state;
|
|
await Task.Delay(150);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The queue has emptied and at least one delivery landed. Waiting on
|
|
/// "delivered >= 1" alone reads the queue between two rows: one scene can
|
|
/// raise more than one alert, and the second row is still owed the moment the
|
|
/// first lands — which is how this suite first failed, on a correct product.
|
|
/// </summary>
|
|
private static bool Settled(JsonElement s) =>
|
|
s.GetProperty("alertPushPending").GetInt32() == 0
|
|
&& s.GetProperty("alertPushDelivered").GetInt32() >= 1;
|
|
|
|
private static int PushesTo(FakeUpstream upstream, string marker)
|
|
{
|
|
lock (upstream.Bodies) return upstream.Bodies.Count(b => b.Contains(marker));
|
|
}
|
|
|
|
/// <summary>Six 502s from one source: the 5xx streak alert fires.</summary>
|
|
private static async Task BreakTheUpstreamAsync(EdgeFixture f)
|
|
{
|
|
for (var i = 0; i < 6; i++)
|
|
{
|
|
using var probe = new HttpRequestMessage(HttpMethod.Get, "/checkout");
|
|
probe.Headers.TryAddWithoutValidation("X-Forwarded-For", Failing);
|
|
using var r = await f.Client.SendAsync(probe);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_endpoint_that_refused_is_asked_again_once_it_heals()
|
|
{
|
|
await using var f = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
await BreakTheUpstreamAsync(f);
|
|
|
|
// Wait for an attempt to have happened, not merely for a row to exist: a
|
|
// row that has not been tried yet has no error to name, and an assertion
|
|
// written against it passes for the wrong reason.
|
|
var failing = await WaitForStateAsync(f,
|
|
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
|
|
Assert.True(failing.GetProperty("alertWebhookFailures").GetInt32() >= 1, failing.ToString());
|
|
Assert.Equal(0, failing.GetProperty("alertPushDelivered").GetInt32());
|
|
Assert.Equal(0, failing.GetProperty("alertPushGivenUp").GetInt32());
|
|
// The queue says what it is waiting on, in words an operator can act on.
|
|
Assert.Contains("500", failing.GetProperty("alertPushLastError").GetString());
|
|
|
|
// The endpoint heals. Nothing new happens at the edge — no new alert, no
|
|
// operator action — and the delivery still goes out.
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status200OK
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
var healed = await WaitForStateAsync(f, Settled);
|
|
Assert.True(PushesTo(f.Upstream, "server_error_streak") >= 1, "the healed endpoint never got the alert");
|
|
Assert.Equal(0, healed.GetProperty("alertPushPending").GetInt32());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_delivery_owed_by_a_process_that_stopped_is_owed_by_the_next_one()
|
|
{
|
|
var dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
|
|
|
|
// First process: the endpoint refuses, so the delivery is owed and stays
|
|
// owed after this process is gone.
|
|
string? owed = null;
|
|
await using (var first = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath,
|
|
maxPushAttempts: 20, pushRetrySeconds: 1))
|
|
{
|
|
first.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
await BreakTheUpstreamAsync(first);
|
|
var state = await WaitForStateAsync(first,
|
|
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
|
|
Assert.True(state.GetProperty("alertPushPending").GetInt32() >= 1, state.ToString());
|
|
owed = state.GetProperty("alertPushOldestPendingAt").GetString();
|
|
}
|
|
|
|
Assert.NotNull(owed);
|
|
|
|
// Second process, same database, working endpoint. It raised nothing and
|
|
// nobody asked it to remember anything: the queue is rows, so the promise
|
|
// outlives the process that made it.
|
|
await using var second = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
second.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
|
|
|
var state2 = await WaitForStateAsync(second, Settled);
|
|
Assert.Equal(0, state2.GetProperty("alertPushPending").GetInt32());
|
|
var pushed = PushesTo(second.Upstream, "server_error_streak");
|
|
Assert.True(pushed >= 1, "the new process never delivered what the old one owed");
|
|
// The payload came with the row, not out of the old process's memory.
|
|
lock (second.Upstream.Bodies)
|
|
Assert.Contains(second.Upstream.Bodies, b => b.Contains(Failing));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Attempts_run_out_and_the_surface_says_who_was_never_told()
|
|
{
|
|
await using var f = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 2, pushRetrySeconds: 1);
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
await BreakTheUpstreamAsync(f);
|
|
|
|
var state = await WaitForStateAsync(f, s => s.GetProperty("alertPushGivenUp").GetInt32() >= 1);
|
|
Assert.Equal(0, state.GetProperty("alertPushPending").GetInt32());
|
|
Assert.True(state.GetProperty("alertPushGivenUp").GetInt32() >= 1, state.ToString());
|
|
|
|
// The distinction this item exists for: a failing counter alone cannot
|
|
// tell "still asking" from "stopped asking".
|
|
Assert.Contains("gave up after 2 attempts", state.GetProperty("alertPushLastError").GetString());
|
|
|
|
// And giving up on the delivery does not undo the alert.
|
|
using var scope = f.Factory.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
Assert.NotEmpty(await db.Alerts.AsNoTracking()
|
|
.Where(a => a.Kind == "server_error_streak" && a.SourceKey == Failing).ToListAsync());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_delivery_owed_outlives_the_alert_row_it_was_copied_from()
|
|
{
|
|
await using var f = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
await BreakTheUpstreamAsync(f);
|
|
await WaitForStateAsync(f,
|
|
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
|
|
|
|
// Retention prunes edge_alerts on the ban-retention window. A delivery
|
|
// still owed must not go with them, which is why the payload is copied
|
|
// onto the queue row rather than read back from the alert.
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
{
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
Assert.True(await db.Alerts.ExecuteDeleteAsync() >= 1);
|
|
}
|
|
|
|
f.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
|
|
|
var state = await WaitForStateAsync(f, Settled);
|
|
Assert.Equal(0, state.GetProperty("alertPushPending").GetInt32());
|
|
lock (f.Upstream.Bodies)
|
|
Assert.Contains(f.Upstream.Bodies, b => b.Contains("server_error_streak") && b.Contains(Failing));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Two_edges_on_one_database_do_not_tell_the_same_person_twice()
|
|
{
|
|
var dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
|
|
await using (var first = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath,
|
|
maxPushAttempts: 20, pushRetrySeconds: 1))
|
|
{
|
|
first.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
await BreakTheUpstreamAsync(first);
|
|
await WaitForStateAsync(first,
|
|
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
|
|
}
|
|
|
|
// Two processes, one database, one owed delivery each, two working
|
|
// endpoints. A duplicate page at 03:00 is not a harmless bug, so the row
|
|
// is claimed before it is sent and exactly one process sends it.
|
|
await using var a = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
await using var b = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
a.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
|
b.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
|
|
|
// Wait on the queue, not on the bodies: a body arrives a moment before the
|
|
// row that produced it is marked delivered, and an assertion written
|
|
// against the wire would read the database mid-write.
|
|
PushQueueCounts queueA = new(0, 0, 0, null, null), queueB = new(0, 0, 0, null, null);
|
|
var deadline = DateTime.UtcNow.AddSeconds(25);
|
|
while (DateTime.UtcNow < deadline)
|
|
{
|
|
queueA = await a.Service<AlertNotifier>().ReadCountsAsync();
|
|
queueB = await b.Service<AlertNotifier>().ReadCountsAsync();
|
|
if (queueA.Pending == 0 && queueA.Delivered >= 1) break;
|
|
await Task.Delay(250);
|
|
}
|
|
|
|
Assert.Equal(0, queueA.Pending);
|
|
Assert.True(queueA.Delivered >= 1, $"nothing was delivered — A: {queueA}, B: {queueB}");
|
|
Assert.Equal(0, queueA.GivenUp);
|
|
|
|
// The count that proves the claim works: every owed row was sent, and no
|
|
// row was sent twice. Two processes polling the same table on the same
|
|
// interval is exactly where a duplicate would appear.
|
|
var total = PushesTo(a.Upstream, Failing) + PushesTo(b.Upstream, Failing);
|
|
Assert.Equal(queueA.Delivered, total);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_queue_is_a_number_a_scraper_can_put_an_alert_rule_on()
|
|
{
|
|
await using var f = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
await BreakTheUpstreamAsync(f);
|
|
await WaitForStateAsync(f, s => s.GetProperty("alertPushPending").GetInt32() >= 1);
|
|
|
|
// The gauge is cached, so it is at most five seconds behind the rows and
|
|
// the test has to wait for the cache rather than assume it.
|
|
string body = "";
|
|
var scrapeDeadline = DateTime.UtcNow.AddSeconds(15);
|
|
while (DateTime.UtcNow < scrapeDeadline)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/metrics");
|
|
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
|
using var response = await f.Client.SendAsync(request);
|
|
body = await response.Content.ReadAsStringAsync();
|
|
if (System.Text.RegularExpressions.Regex.IsMatch(body, "openwaf_alert_push_pending [1-9]")) break;
|
|
await Task.Delay(250);
|
|
}
|
|
|
|
// A count of rows, not of one alert: a storm can owe more than one
|
|
// delivery, so the assertion is that the gauge is non-zero and the other
|
|
// two are still zero.
|
|
Assert.Matches(@"openwaf_alert_push_pending [1-9]", body);
|
|
Assert.Contains("openwaf_alert_push_delivered_total 0", body);
|
|
Assert.Contains("openwaf_alert_push_given_up_total 0", body);
|
|
Assert.Contains("openwaf_alert_push_oldest_pending_age_seconds", body);
|
|
}
|
|
}
|