using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; 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; /// /// 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: /// /// * Eventually, across a restart. 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". /// * Bounded, and honest about the bound. 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. /// * Claimed before it is sent. 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. /// public sealed class AlertNotifier : BackgroundService { public const string Pillar = "alertWebhook"; /// 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 /// OpenWaf:State:RefreshTtlSeconds. public const int TimeoutSecondsFloor = 1, TimeoutSecondsCeiling = 60; /// 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. private const int PollSeconds = 2; private const int BatchSize = 20; /// How often the cached queue counts are refreshed. /metrics /// 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. /admin-api/state reads the table, because /// an operator asking directly should get the current answer. 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 _log; private readonly string? _url; private readonly HttpClient _http; private readonly int _maxAttempts; private readonly int _retryBaseSeconds; /// 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. private readonly string _processId = $"{Environment.MachineName}-{Environment.ProcessId}-{Guid.NewGuid().ToString("N")[..8]}"; private readonly Channel _wake = Channel.CreateBounded( new BoundedChannelOptions(16) { FullMode = BoundedChannelFullMode.DropWrite, SingleReader = true }); private volatile PushQueueCounts _counts = new(0, 0, 0, null, null, 0); private DateTimeOffset _countsAt = DateTimeOffset.MinValue; /// 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. public string? WebhookHost { get; } public bool IsConfigured => _url is not null; /// The queue as this process last measured it. Cached on purpose: /// /metrics and /admin-api/state read it without touching the /// database, so a scrape cannot become a query per poll. public PushQueueCounts Counts => _counts; public AlertNotifier( IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger 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) }; } /// 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. public async Task EnqueueAsync(EdgeAlert alert, CancellationToken ct = default) { if (_url is null) return false; try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); 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". try { 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) { } } } finally { // A row this process claimed but never finished must not sit behind its // own claim until the reclaim window expires. The window exists for a // process that was killed and cannot say anything; a process that is // being stopped can, and saying it is the difference between "the next // process picks up what is owed" and "it picks it up five minutes // later". Measured: with no release here, the restart test below stalled // on the claim its own predecessor left. await ReleaseOwnClaimsAsync(); } } /// Give back the owed rows this process holds a claim on. Runs after /// the stopping token has fired, so it uses its own bounded one: a database /// that is already gone must not hold the process open on shutdown, and the /// reclaim window is the backstop for exactly that case. private async Task ReleaseOwnClaimsAsync() { try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); // A local, not the field: the query precompiler reads the lambda out // of the source text and does not resolve an instance field from there // ("Encountered unknown identifier name '_processId'"). var owner = _processId; var released = await db.AlertPushes .Where(p => p.ClaimedBy == owner && p.PushedAt == null && p.GivenUpAt == null) .ExecuteUpdateAsync(s => s .SetProperty(p => p.ClaimedBy, (string?)null) .SetProperty(p => p.ClaimedAt, (DateTimeOffset?)null), timeout.Token); if (released > 0) _log.LogInformation("AlertNotifier: released {Rows} owed deliveries this process had claimed.", released); } catch (Exception ex) { _log.LogWarning(ex, "AlertNotifier: could not release this process's claims; the reclaim window will do it."); } } /// One pass over the owed deliveries: claim a batch atomically, then /// send each one. 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(); var token = ct; var owner = _processId; // A local for the batch size: the source-level translator resolves only // lambda parameters and captured variables, so a const by name is "unknown // identifier" to it. var take = BatchSize; 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(take) .ToListAsync(token); 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. // // This is the one query in the persistence layer that EF's query // precompiler cannot translate at all — ClaimedAt is DateTimeOffset?, // and no shape of a non-nullable value in an ExecuteUpdate set-list // precompiles — and it is deliberately left as LINQ rather than // rewritten as hand-written SQL. Measured: with the statement written // as SQL, DateTimeOffset reaches sqlite as a provider parameter instead // of through the property's own mapping, the reclaim comparison stops // matching, and // AlertPushQueueTests.A_delivery_owed_by_a_process_that_stopped_is_owed_by_the_next_one // fails with the row still owed. The AOT build is blocked further along // anyway (see docs/ARCHITECTURE.md), so a correctness risk here buys // nothing. 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, owner) .SetProperty(p => p.ClaimedAt, now), token); var rows = await db.AlertPushes .Where(p => due.Contains(p.Id) && p.ClaimedBy == owner) .OrderBy(p => p.Id) .ToListAsync(token); // 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(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); } /// 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. private async Task<(bool Ok, string? Error)> TryPushAsync(AlertPush row, CancellationToken ct) { try { using var response = await _http.PostAsJsonAsync( _url!, AlertPushPayload.From(row), AlertPushPayloadJsonContext.Default.AlertPushPayload, 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(DateTimeOffset now, CancellationToken ct) { if (now - _countsAt < CountsRefresh) return; _counts = await QueryCountsAsync(ct); _countsAt = now; } /// For the surfaces and the tests: the queue as the database holds /// it, not as this process last cached it. public Task ReadCountsAsync(CancellationToken ct = default) => _url is null ? Task.FromResult(new PushQueueCounts(0, 0, 0, null, null, 0)) : QueryCountsAsync(ct); /// The queue's numbers, each one a literal chain from the DbSet. /// /// The context is resolved here rather than passed in, and that is not style: /// a method whose query root is a parameter cannot be precompiled at all /// (dotnet/efcore#38030), and a NativeAOT build cannot compile a query at run /// time, so this is the difference between the compiled image answering these /// numbers and not answering them. The aggregate overloads that take the /// predicate — CountAsync(p => …), SumAsync(p => …) — build their query at run /// time and are "dynamic LINQ" for the same reason, which is why each number /// spells its own Where. /// private async Task QueryCountsAsync(CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var token = ct; return new PushQueueCounts( await db.AlertPushes.Where(p => p.PushedAt == null && p.GivenUpAt == null).CountAsync(token), await db.AlertPushes.Where(p => p.PushedAt != null).CountAsync(token), await db.AlertPushes.Where(p => p.GivenUpAt != null).CountAsync(token), await db.AlertPushes.Where(p => p.LastError != null) .OrderByDescending(p => p.Attempts).Select(p => p.LastError).FirstOrDefaultAsync(token), await db.AlertPushes.Where(p => p.PushedAt == null && p.GivenUpAt == null) .OrderBy(p => p.CreatedAt).Select(p => p.CreatedAt).FirstOrDefaultAsync(token), // Every attempt every row has made, including rows that have since landed. It is // the one number that says how hard the edge has been trying: pending and given-up // say what the queue holds, this says what it cost. (int) await db.AlertPushes.Select(p => p.Attempts).SumAsync(token)); } /// Force one pass, for tests and for an operator who wants the queue /// drained now rather than on the next poll. public Task PumpAsync(CancellationToken ct = default) => DrainAsync(ct); } /// 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. public sealed record PushQueueCounts( int Pending, int Delivered, int GivenUp, string? LastError, DateTimeOffset? OldestPendingAt, int Attempts); /// The push body, as a named shape with a source-generated JSON context. /// It used to be an anonymous type handed to PostAsJsonAsync, which is reflection /// JSON: the NativeAOT analyzer refuses it (IL2026/IL3050), and the body an /// operator's webhook receives would then depend on what the trimmer kept. The /// property names below are the wire contract the queue has always sent — /// camelCase, `createdAt` being the alert's timestamp and not the row's. internal sealed record AlertPushPayload( string Kind, string SourceKey, int Count, int? LastStatusCode, string? LastPath, DateTimeOffset CreatedAt, string Detail, int Attempts) { public static AlertPushPayload From(AlertPush row) => new( row.Kind, row.SourceKey, row.Count, row.LastStatusCode, row.LastPath, row.AlertCreatedAt, row.Detail, row.Attempts + 1); } [JsonSerializable(typeof(AlertPushPayload))] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] internal sealed partial class AlertPushPayloadJsonContext : JsonSerializerContext;