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.
150 lines
6.7 KiB
C#
150 lines
6.7 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using OpenWaf.Domain.Engine;
|
|
using OpenWaf.Domain.Security;
|
|
|
|
namespace OpenWaf.Infrastructure.Persistence;
|
|
|
|
/// <summary>
|
|
/// Persists the in-memory streak state on a timer. This is the write
|
|
/// amplification protection the reference repo already paid for: a scanner
|
|
/// hammering thousands of paths a second must not generate matching writes a
|
|
/// second, so the tracker stays in memory and at most one durable upsert per
|
|
/// source per <c>ObservationWriteInterval</c> leaves this loop.
|
|
/// </summary>
|
|
public sealed class ObservationWriter : BackgroundService
|
|
{
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
private readonly IStreakTracker _tracker;
|
|
private readonly EdgePolicyProvider _policy;
|
|
private readonly DurabilityHealth _health;
|
|
private readonly ILogger<ObservationWriter> _log;
|
|
private readonly TimeSpan _flushInterval = TimeSpan.FromSeconds(15);
|
|
private readonly Dictionary<string, DateTimeOffset> _lastWrittenAt = new(StringComparer.Ordinal);
|
|
|
|
public ObservationWriter(
|
|
IServiceScopeFactory scopeFactory,
|
|
IStreakTracker tracker,
|
|
EdgePolicyProvider policy,
|
|
DurabilityHealth health,
|
|
ILogger<ObservationWriter> log)
|
|
{
|
|
_scopeFactory = scopeFactory;
|
|
_tracker = tracker;
|
|
_policy = policy;
|
|
_health = health;
|
|
_log = log;
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
try { await Task.Delay(_flushInterval, stoppingToken); }
|
|
catch (TaskCanceledException) { return; }
|
|
await FlushAsync(stoppingToken);
|
|
}
|
|
await FlushAsync(CancellationToken.None);
|
|
}
|
|
|
|
internal async Task<int> FlushAsync(CancellationToken ct)
|
|
{
|
|
var policy = _policy.Current;
|
|
var now = DateTimeOffset.UtcNow;
|
|
var snapshots = _tracker.Snapshot(now, policy);
|
|
if (snapshots.Count == 0) return 0;
|
|
|
|
// The write-amplification bound protects against load, not against
|
|
// retries. While this pillar has an outstanding failure, every flush
|
|
// re-attempts every tracked source: the rows the failed flush was
|
|
// carrying would otherwise be lost until each source happened to be due
|
|
// again a full interval later, and the counter would stop being a live
|
|
// signal. The flush rate is unchanged (one per 15 s) and the source count
|
|
// is already capped by the LRU bound on the map, so retrying cannot turn
|
|
// into write amplification.
|
|
var retrying = _health.Get(DurabilityHealth.Observations).Failures > 0;
|
|
var due = new List<StreakSnapshot>();
|
|
foreach (var s in snapshots)
|
|
{
|
|
if (!retrying
|
|
&& _lastWrittenAt.TryGetValue(s.SourceKey, out var last) && now - last < policy.ObservationWriteInterval)
|
|
continue;
|
|
due.Add(s);
|
|
_lastWrittenAt[s.SourceKey] = now;
|
|
}
|
|
|
|
if (_lastWrittenAt.Count > policy.MaxTrackedSources)
|
|
{
|
|
foreach (var key in _lastWrittenAt.Where(kv => now - kv.Value > policy.StateIdleTtl).Select(kv => kv.Key).ToList())
|
|
_lastWrittenAt.Remove(key);
|
|
}
|
|
|
|
if (due.Count == 0) return 0;
|
|
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var token = ct;
|
|
var keys = due.Select(d => d.SourceKey).ToList();
|
|
var existing = await db.Observations.Where(o => keys.Contains(o.SourceKey)).ToListAsync(token);
|
|
var byKey = existing.ToDictionary(o => o.SourceKey, StringComparer.Ordinal);
|
|
|
|
foreach (var s in due)
|
|
{
|
|
if (byKey.TryGetValue(s.SourceKey, out var row))
|
|
{
|
|
row.LastSeenAt = s.LastSeenAt;
|
|
row.MaxConsecutiveRefusals = Math.Max(row.MaxConsecutiveRefusals, s.MaxConsecutiveRefusals);
|
|
row.TotalRefusals = Math.Max(row.TotalRefusals, s.TotalRefusals);
|
|
row.TotalServerErrorStreak = Math.Max(row.TotalServerErrorStreak, s.MaxConsecutiveServerErrors);
|
|
row.LastStatusCode = s.LastStatusCode ?? row.LastStatusCode;
|
|
row.LastPath = s.LastPath ?? row.LastPath;
|
|
row.LastUserAgent = s.LastUserAgent ?? row.LastUserAgent;
|
|
row.LastCountryCode = s.LastCountryCode ?? row.LastCountryCode;
|
|
row.LastCity = s.LastCity ?? row.LastCity;
|
|
row.LastRegion = s.LastRegion ?? row.LastRegion;
|
|
}
|
|
else
|
|
{
|
|
db.Observations.Add(new SourceObservation
|
|
{
|
|
SourceKey = s.SourceKey,
|
|
FirstSeenAt = s.LastSeenAt,
|
|
LastSeenAt = s.LastSeenAt,
|
|
MaxConsecutiveRefusals = s.MaxConsecutiveRefusals,
|
|
TotalRefusals = s.TotalRefusals,
|
|
TotalServerErrorStreak = s.MaxConsecutiveServerErrors,
|
|
LastStatusCode = s.LastStatusCode,
|
|
LastPath = s.LastPath,
|
|
LastUserAgent = s.LastUserAgent,
|
|
LastCountryCode = s.LastCountryCode,
|
|
LastCity = s.LastCity,
|
|
LastRegion = s.LastRegion
|
|
});
|
|
}
|
|
}
|
|
await db.SaveChangesAsync(ct);
|
|
_health.RecordSuccess(DurabilityHealth.Observations, due.Count);
|
|
return due.Count;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// The writer must survive: losing observations is better than
|
|
// taking the host down over a transient database error. What it may
|
|
// not do is survive quietly. Measured on the shipped image with the
|
|
// write path aborted by SQLite triggers: three new sources never
|
|
// reached source_observations, /admin-api/observations kept
|
|
// answering 200 with the same X-Total-Count as before the break,
|
|
// /readyz said "ready", and the only trace was this log line. The
|
|
// rows are not recoverable later — the streak history the operator
|
|
// reasons about is simply missing them.
|
|
_health.RecordFailure(DurabilityHealth.Observations, ex, due.Count);
|
|
_log.LogWarning(ex, "ObservationWriter: flush failed, {Count} entries dropped.", due.Count);
|
|
return 0;
|
|
}
|
|
}
|
|
}
|