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

174 lines
8.8 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Engine;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Edge.Startup;
/// <summary>
/// Brings the durable state up before the first request is served: schema,
/// then the guard's first snapshot.
///
/// The order matters. If the edge starts serving with an empty snapshot
/// because the database was still coming up, every operator block is
/// momentarily invisible — which is the one moment an abusive source is
/// guaranteed to be probing.
/// </summary>
internal sealed class EdgeStateWarmer(
IServiceScopeFactory scopeFactory,
EdgeStateStore state,
IStreakTracker streaks,
RateTracker rates,
RateRuleTracker rateRules,
SchemaUpgradeReport schema,
IConfiguration configuration,
ILogger<EdgeStateWarmer> log) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
// Migrations are the schema of record for the provider that actually
// runs in production — PostgreSQL. A migration set is provider-shaped
// SQL, so it is not applied to the SQLite default; there the schema is
// created from the model instead. OPENWAF_SCHEMA=none leaves both alone
// when an operator manages the schema themselves.
// Read through configuration rather than the environment directly: an
// environment variable still sets it (ASP.NET Core puts the environment
// in the configuration), and a test can now ask for a strategy instead of
// mutating process-wide state that parallel tests share.
var isSqlite = string.Equals(
configuration["Database:Provider"] ?? "sqlite", "sqlite", StringComparison.OrdinalIgnoreCase);
var strategy = configuration["OPENWAF_SCHEMA"]
?? (isSqlite ? "ensurecreated" : "migrate");
schema.Strategy = strategy;
switch (strategy.ToLowerInvariant())
{
case "ensurecreated":
await CreateSchemaAsync(db, migrate: false, cancellationToken);
// EnsureCreated is the step that creates a missing database, and
// the step that changes nothing about an existing one. The second
// half is what an upgrade needs: the tables this build expects
// and this database predates, created in place.
schema.TablesAdded = (await SchemaUpgrader.AddMissingTablesAsync(db, log, cancellationToken)).Count;
break;
case "migrate":
// A database that has tables but no history table cannot be
// migrated: the migration set would start by creating tables that
// are already there. Claim the ones that demonstrably ran, then
// run the rest.
schema.MigrationsBaselined = await SchemaUpgrader.BaselineIfUntrackedAsync(db, log, cancellationToken);
schema.MigrationsApplied = await SchemaUpgrader.PendingMigrationsAsync(db, cancellationToken);
await CreateSchemaAsync(db, migrate: true, cancellationToken);
break;
case "script":
// The ensurecreated step for a binary that cannot run it. EF
// refuses to build a model at run time in a NativeAOT build, and
// both EnsureCreated and GenerateCreateScript go through the
// design-time model — so the DDL is generated from the model at
// build time, committed, and read out of the binary. Same
// provider-shaped statements, one of them checked by the
// schema-script gate rather than re-derived at start-up.
await CreateSchemaFromScriptAsync(db, cancellationToken);
schema.TablesAdded = (await SchemaUpgrader.AddMissingTablesAsync(
db, log, SchemaUpgrader.EmbeddedScriptFor(db) ?? string.Empty, cancellationToken)).Count;
break;
default:
log.LogInformation("edge: schema management left to the operator (OPENWAF_SCHEMA={Strategy})", strategy);
break;
}
// Asked after the step rather than instead of it, because the operator
// who manages the schema themselves needs the same answer: a pillar this
// build can run either has its table or it does not.
schema.MissingTables = await SchemaUpgrader.MissingTablesAsync(db, cancellationToken);
if (schema.MissingTables.Count > 0)
log.LogError(
"edge: the database is still missing {Tables} — the pillars that need them report themselves "
+ "unavailable on /admin-api/state instead of answering with nothing.",
string.Join(", ", schema.MissingTables));
await state.WarmUpAsync(cancellationToken);
// The map bounds come from the policy, and both trackers read them once
// rather than dereferencing the policy record per request. The streak
// tracker's cap used to be set by nobody outside its own tests, so
// maxTrackedSources bounded nothing in a running edge — the map grew to
// the built-in 10 000 whatever the operator had asked for.
streaks.Configure(state.Current.Policy);
rates.Configure(state.Current.Policy);
rateRules.Configure(state.Current.Policy);
log.LogInformation(
"edge: warmed up — {Operator} operator blocks, {Engine} engine bans, {Allow} allow entries",
state.Current.OperatorBlocks.Count, state.Current.EngineBans.Count, state.Current.AllowEntries.Count);
}
/// <summary>
/// Bring the schema up, and survive losing the race for it.
///
/// Two edges on one database start at the same moment in every deployment
/// that shares the block list — and in the shared-streak store (OPEN-52)
/// that is the configuration, not an accident. Measured with two processes
/// against one SQLite file: the first created the tables, the second died in
/// <c>StartAsync</c> with <c>SQLite Error 1: 'table "allow_entries" already
/// exists'</c>, hosting reported "Hosting failed to start", and the process
/// never listened on its port. What has to be true is that the schema exists,
/// not that this process was the one that made it, so the loser re-checks and
/// carries on.
/// </summary>
private async Task CreateSchemaAsync(OpenWafDbContext db, bool migrate, CancellationToken ct)
{
try
{
if (migrate) await db.Database.MigrateAsync(ct);
else await db.Database.EnsureCreatedAsync(ct);
}
catch (Exception ex)
{
// Give the winner a moment to finish, then ask the question that
// matters. If the tables are there, this edge serves against them;
// if they are not, the failure was something else and the process
// must still refuse to start.
await Task.Delay(TimeSpan.FromMilliseconds(500), ct);
var creator = ((IInfrastructure<IServiceProvider>)db.Database).Instance
.GetRequiredService<IRelationalDatabaseCreator>();
if (!await creator.ExistsAsync(ct)) throw;
log.LogWarning(
"edge: the schema was being created by another instance ({Error}); continuing against it.",
ex.Message);
}
}
/// <summary>
/// The script strategy's share of the race for the schema.
///
/// Same rule as <see cref="CreateSchemaAsync"/>: what has to be true is that
/// the tables exist, not that this process was the one that made them. Two
/// edges on one database both find the same tables missing and both start
/// creating them, and the loser's CREATE TABLE fails on the winner's table —
/// which is a start-up failure only if the tables are still missing after.
/// </summary>
private async Task CreateSchemaFromScriptAsync(OpenWafDbContext db, CancellationToken ct)
{
try
{
await SchemaUpgrader.ApplyScriptAsync(db, log, ct);
}
catch (Exception ex)
{
await Task.Delay(TimeSpan.FromMilliseconds(500), ct);
var stillMissing = await SchemaUpgrader.MissingTablesAsync(db, ct);
if (stillMissing.Count > 0) throw;
log.LogWarning(
"edge: the schema was being created by another instance ({Error}); continuing against it.",
ex.Message);
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}