ci / lint the workflow and the shell (push) Successful in 10s
geo-freshness / the pinned geo database vs the vendor (push) Successful in 5s
ci / the operator page in a real browser (push) Successful in 3m42s
ci / build, test, smoke (push) Failing after 2m6s
ci / build the image and smoke it (push) Successful in 5m7s
The Dockerfile said "why not NativeAOT" on the authority of another repo's
Dockerfile. That claim is now this repo's own, and it is a measurement.
What was built to find out:
* Persistence/Schema/schema.sqlite.sql — the model's DDL, generated by
`dotnet ef dbcontext script`, embedded in the binary and read by
Persistence/EmbeddedSchema.cs. A NativeAOT build cannot ask EF to build a
model at run time, and EnsureCreated and GenerateCreateScript both go through
the design-time model, so the schema step has nowhere to get its SQL from.
OPENWAF_SCHEMA=script is the fourth strategy: same provider-shaped
statements, produced at build time instead of at start-up. The schema-script
CI step regenerates the file and fails the run when the committed copy is not
what the current model produces (5652 bytes today).
* SchemaUpgrader.ModelTables asks the runtime model, per entity type. The
design-time one is refused outright under NativeAOT, and GetRelationalModel()
on the runtime model of a compiled model throws
"The annotation 'Relational:DefaultMappings' cannot be added because an
annotation with the same name already exists on the object EntityType:
CountryRule" — building a compiled model's relational model a second time
collides with itself.
* The persistence layer's queries were rewritten into the shape EF's query
precompiler accepts: captured parameters copied to locals, conditional
IQueryable composition written as literal chains, aggregates that take a
predicate given their own Where. 40 of them were refused before that.
* dotnet-ef and EF Core moved 10.0.0 -> 10.0.12, because 10.0.0's design package
ships no build host and `--precompile-queries` cannot load a project without it.
What the measurement says, from scripts/aot-probe.sh on osx-arm64: the AOT build
compiles (48,797,072-byte native binary, 10 IL warnings, 0 errors), starts, and
creates all 12 tables from the DDL it carries. Then it never serves. EF refuses
every query at run time ("Query wasn't precompiled and dynamic code isn't
supported with NativeAOT"), and the precompiler that would fix that is not
usable on this model: after all 40 refusals were cleared it emitted 14
declarations with dots in the identifier
(`var openWaf.Domain.Security.BlockEntryPrimaryKeyProperties = …`) — 28 CS1002
and CS1003 errors, one per entity materialisation — with or without --nativeaot.
The refusals themselves trace to dotnet/efcore#35887, #38030 and #35494; the fix
landed in the 12.0-preview1 milestone, not in any 10.0.x.
Two things were not kept, and why:
* The atomic alert-queue claim and the claim release were rewritten as raw SQL
to dodge the precompiler's ExecuteUpdate failures. Reverted: 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. A correctness risk here buys nothing when the
AOT build is blocked further along anyway.
* --nativeaot on the compiled model: its unsafe accessors do not compile
(CS1503 in BlockEntryEntityType.cs). The plain compiled model is what is
committed.
The compose gate's two escalation-count scenes also stopped being a coin toss.
They slept a fixed 2 s and then counted; on a loaded host the same tree read 3
rows once and 1 the next, and the assertion is about a settled number either
way. They now wait for three equal reads, bounded. The scene count is unchanged
at 368.
Gates at this commit: build 0 warnings / 0 errors, unit 378/378, integration
405/405, schema-script ok, smoke 256/0, compose-smoke 368/0, README counts
match (256, 368), lint clean (actionlint 1.7.12, shellcheck 0.11.0).
Not verified: the AOT image on linux-x64 — the probe ran on osx-arm64, and the
ILC failure mode that ends the attempt is a codegen bug in EF, not a
platform-specific one, but that is an inference rather than a measurement.
452 lines
22 KiB
C#
452 lines
22 KiB
C#
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;
|
|
|
|
/// <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, 0);
|
|
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".
|
|
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();
|
|
}
|
|
}
|
|
|
|
/// <summary>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.</summary>
|
|
private async Task ReleaseOwnClaimsAsync()
|
|
{
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
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.");
|
|
}
|
|
}
|
|
|
|
/// <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 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);
|
|
}
|
|
|
|
/// <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!, 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;
|
|
}
|
|
|
|
/// <summary>For the surfaces and the tests: the queue as the database holds
|
|
/// it, not as this process last cached it.</summary>
|
|
public Task<PushQueueCounts> ReadCountsAsync(CancellationToken ct = default)
|
|
=> _url is null
|
|
? Task.FromResult(new PushQueueCounts(0, 0, 0, null, null, 0))
|
|
: QueryCountsAsync(ct);
|
|
|
|
/// <summary>The queue's numbers, each one a literal chain from the DbSet.</summary>
|
|
/// <remarks>
|
|
/// 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.
|
|
/// </remarks>
|
|
private async Task<PushQueueCounts> QueryCountsAsync(CancellationToken ct)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
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));
|
|
}
|
|
|
|
/// <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,
|
|
int Attempts);
|
|
|
|
/// <summary>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.</summary>
|
|
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;
|