Files
Pavlo Ratushnyi 7c5e1ef230
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 edge gains a schema step a compiled binary can run, and NativeAOT gets a measured verdict
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.
2026-10-06 05:20:28 +02:00

263 lines
12 KiB
C#

using System.Globalization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Holds the snapshot the decision point reads and refreshes it off the
/// request path.
///
/// The reference repo blocks the request thread on a stale cache
/// (<c>RefreshAsync().GetAwaiter().GetResult()</c>). This does not: a stale
/// snapshot is served while a single background refresh runs, because a
/// database hiccup should not add latency to every request, and a snapshot
/// that is 30 seconds old is a documented, accepted state. The very first load
/// is awaited at startup, so the edge never serves traffic with an empty
/// picture of the operator's list.
///
/// On refresh failure the previous snapshot is kept — fail closed for blocks.
/// A bot probing during a database restart must not skate past the gate.
/// </summary>
public sealed class EdgeStateStore
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly EdgePolicyProvider _policy;
private readonly ILogger<EdgeStateStore> _log;
private readonly SemaphoreSlim _refreshLock = new(1, 1);
private EdgeSnapshot _snapshot;
private int _refreshInFlight;
public EdgeStateStore(
IServiceScopeFactory scopeFactory,
EdgePolicyProvider policy,
ILogger<EdgeStateStore> log)
{
_scopeFactory = scopeFactory;
_policy = policy;
_log = log;
_snapshot = EdgeSnapshot.Empty(policy.Current);
}
public EdgeSnapshot Current => _snapshot;
public TimeSpan RefreshTtl { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>
/// Older than the TTL. The TTL is documented as the bound on how stale the
/// block list may be, and the process refuses to start with an unparseable
/// one — "rather than run with a block list of unknown staleness". Until now
/// nothing checked that bound after startup, so a snapshot could sit at ten
/// times the bound and every surface still looked normal.
/// </summary>
public bool IsStale => DateTimeOffset.UtcNow - _snapshot.GeneratedAt > RefreshTtl;
/// <summary>Consecutive refresh failures; zero means the last one worked.</summary>
public int RefreshFailures => Volatile.Read(ref _refreshFailures);
/// <summary>The last refresh error, or null when the last refresh succeeded.</summary>
public string? LastRefreshError => Volatile.Read(ref _lastRefreshError);
private int _refreshFailures;
private string? _lastRefreshError;
/// <summary>Whether the last refresh could read the request-rule table.
/// False means the edge is enforcing everything except the rules, and says
/// so — see <see cref="RefreshAsync"/>.</summary>
public bool RulesAvailable { get; private set; } = true;
/// <summary>Whether the operator's range bans (OPEN-66) could be read on the
/// last refresh. Same rule as the rules flag: a database that predates the
/// table enforces everything it has and says what it cannot see.</summary>
public bool RangesAvailable { get; private set; } = true;
public string? RangesError => Volatile.Read(ref _rangesError);
/// <summary>Whether the per-path budgets (OPEN-68) could be read on the last
/// refresh. False means the edge is enforcing everything except the path
/// budgets, and the surface says which.</summary>
public bool RateRulesAvailable { get; private set; } = true;
public string? RateRulesError => Volatile.Read(ref _rateRulesError);
private string? _rateRulesError;
private string? _rangesError;
/// <summary>Why the rules could not be read, for the operator surface.</summary>
public string? RulesError => Volatile.Read(ref _rulesError);
private string? _rulesError;
/// <summary>
/// Reads the configured TTL. The TTL is the bound on how stale the block
/// list may be, which makes it a security setting: an unparseable or
/// out-of-range value stops the process at startup instead of quietly
/// falling back to the default behind the operator's back. Unset means 30 s.
/// </summary>
public static TimeSpan ParseRefreshTtl(string? configured)
{
if (string.IsNullOrWhiteSpace(configured)) return TimeSpan.FromSeconds(30);
if (!int.TryParse(configured.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var seconds)
|| seconds < 1 || seconds > 300)
{
throw new InvalidOperationException(
"OpenWaf:State:RefreshTtlSeconds must be a whole number of seconds between 1 and 300; "
+ $"got \"{configured}\". Refusing to start rather than run with a block list of unknown staleness.");
}
return TimeSpan.FromSeconds(seconds);
}
/// <summary>Blocking load, used once at startup.</summary>
public Task WarmUpAsync(CancellationToken ct = default) => RefreshAsync(ct);
/// <summary>Serve now, refresh in the background if the TTL has expired.</summary>
public EdgeSnapshot GetOrRefresh()
{
var snapshot = _snapshot;
if (DateTimeOffset.UtcNow - snapshot.GeneratedAt > RefreshTtl && Interlocked.CompareExchange(ref _refreshInFlight, 1, 0) == 0)
{
_ = Task.Run(async () =>
{
try { await RefreshAsync(CancellationToken.None); }
finally { Interlocked.Exchange(ref _refreshInFlight, 0); }
});
}
return snapshot;
}
/// <summary>Admin mutations call this so the operator's change lands on the
/// next request rather than after the TTL.</summary>
public Task InvalidateAsync(CancellationToken ct = default) => RefreshAsync(ct);
private async Task RefreshAsync(CancellationToken ct)
{
if (!await _refreshLock.WaitAsync(TimeSpan.FromSeconds(10), ct)) return;
try
{
var policy = await _policy.ReloadAsync(ct);
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var blocks = await db.Blocks.AsNoTracking().ToListAsync(token);
var allow = await db.AllowEntries.AsNoTracking().ToListAsync(token);
var countries = await db.CountryRules.AsNoTracking().ToListAsync(token);
// The rules read stands alone, on purpose. `request_rules` is the
// newest table in the schema, and a database created before the
// feature has every other table — so reading it in the same block
// as the rest would let one missing table stop a ban written a
// minute ago from ever being enforced, which is exactly the failure
// this file warns about two paragraphs down. When it fails, the
// snapshot is still the operator's list and the surface says the
// rules pillar is reading nothing.
IReadOnlyList<RequestRule> rules;
try
{
// Ordered by id: the listing an operator reads and the order the
// engine evaluates are the same thing, so "which rule wins" has
// one answer that is visible on the page.
rules = await db.RequestRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(token);
RulesAvailable = true;
Volatile.Write(ref _rulesError, null);
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
rules = [];
RulesAvailable = false;
Volatile.Write(ref _rulesError, ex.Message);
_log.LogWarning(ex,
"EdgeStateStore: the request-rule table could not be read; enforcing the rest of the list without it.");
}
// The per-path budgets (OPEN-68) read alone, for the same reason the
// rule and range reads do: rate_rules is the newest table in the
// schema, and a database that predates it must keep enforcing
// everything else. A pillar that cannot read its table says so on the
// surface rather than answering "no budgets".
IReadOnlyList<RateRule> rateRules;
try
{
rateRules = await db.RateRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(token);
RateRulesAvailable = true;
Volatile.Write(ref _rateRulesError, null);
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
rateRules = [];
RateRulesAvailable = false;
Volatile.Write(ref _rateRulesError, ex.Message);
_log.LogWarning(ex,
"EdgeStateStore: the rate-rule table could not be read; enforcing the rest of the config without it.");
}
var operatorBlocks = new Dictionary<string, BlockEntry>(StringComparer.Ordinal);
var engineBans = new Dictionary<string, BlockEntry>(StringComparer.Ordinal);
foreach (var b in blocks)
{
if (b.Source == BlockSource.Operator) operatorBlocks[b.SourceKey] = b;
else engineBans[b.SourceKey] = b;
}
// The range read stands alone for the same reason the rule read does:
// `network_bans` is the newest table in the schema, and a database
// created before it has every other table. Failing this read must not
// take a ban written a minute ago down with it.
NetworkBanIndex ranges;
try
{
ranges = new NetworkBanIndex(await db.NetworkBans.AsNoTracking().ToListAsync(token));
RangesAvailable = true;
Volatile.Write(ref _rangesError, null);
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
ranges = NetworkBanIndex.Empty;
RangesAvailable = false;
Volatile.Write(ref _rangesError, ex.Message);
_log.LogWarning(ex,
"EdgeStateStore: the range-ban table could not be read; enforcing the rest of the list without it.");
}
var countryMap = new Dictionary<string, CountryRule>(StringComparer.OrdinalIgnoreCase);
foreach (var c in countries) countryMap[c.Code] = c;
Interlocked.Exchange(ref _refreshFailures, 0);
Volatile.Write(ref _lastRefreshError, null);
_snapshot = new EdgeSnapshot
{
GeneratedAt = DateTimeOffset.UtcNow,
Policy = policy,
OperatorBlocks = operatorBlocks,
EngineBans = engineBans,
AllowEntries = allow,
Countries = countryMap,
RequestRules = rules,
OperatorRanges = ranges,
RateRules = rateRules
};
}
catch (Exception ex)
{
// Fail closed for the decision, and say so where an operator looks.
// Keeping the previous snapshot is right; keeping it silently is not:
// the snapshot is the operator's list, and a refresh that has been
// failing for an hour means a ban written since then is not being
// enforced — while /readyz, /state and the page all looked normal.
Interlocked.Increment(ref _refreshFailures);
Volatile.Write(ref _lastRefreshError, ex.Message);
_log.LogWarning(ex, "EdgeStateStore: refresh failed; keeping the previous snapshot.");
}
finally
{
_refreshLock.Release();
}
}
}