Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs
T
Pavlo Ratushnyi 1e0d11df1c
ci / build, test, smoke (push) Failing after 3m33s
ci / the same smoke on an image with no base (push) Successful in 8m10s
ci / lint the workflow and the shell (push) Failing after 19s
ci / the operator page in a real browser (push) Successful in 4m41s
ci / build the image and smoke it (push) Failing after 8m11s
the first query moves off ef, and the aot edge reads its own policy from the database
Wall 3 starts. Two projects, one query path, measured.

dotnet/OpenWaf.Data is the runtime: OrmContext (a DbDataSource plus an
ISqlDialect), Query<T>, RowReader, OrmMeta. It is typed over System.Data.Common
and carries no provider package; the driver is supplied at composition, which is
how the neighbouring deployment ships it too. Query<T> renders SQL by walking the
expression tree rather than compiling it — that is the exact difference from EF's
pipeline, and the reason it survives a NativeAOT link where EF does not. The
supported grammar is a closed set that refuses by name: joins, subqueries,
aggregates other than COUNT, updates, deletes, JSON columns and method calls each
raise UnsupportedQueryNodeException naming the node, because a renderer that
guesses is a renderer that ships wrong SQL.

dotnet/OpenWaf.Data.Generator is a Roslyn incremental generator attached to
OpenWaf.Infrastructure as an analyzer. For a [Table] class it emits the column
map, the row materializer and an OrmMeta.Register call inside a
[ModuleInitializer], so the question a NativeAOT binary cannot answer — what are
this type's properties — is never asked. The generated file is ordinary C#,
readable in obj/ and asserted against.

PolicySetting is the entity moved and EdgePolicyProvider.ReloadAsync the call
site, which was the first refusal in the probe log. Program.cs composes the
driver and dialect on the same Database:Provider switch EF uses, so one generated
query serves sqlite (the shipped image) and PostgreSQL (the migrations'
provider). EF still owns every write and every other read; the two layers
coexist on one composition root, which is what makes this incremental rather than
a rewrite.

Measured on the AOT binary, same probe, same window, before and after:
queries refused at run time 32 -> 18; EdgePolicyProvider reload failures 1 -> 0;
native binary 49,609,680 -> 49,676,016 bytes. The 18 that remain are named by
their own frames: 14 EdgeStateStore.RefreshAsync, 2 BlockStore.WriteBanAsync,
1 BlockStore.AddOperatorAsync, 1 admin endpoint.

The sqlite timestamp column turned out to be a contract, not a detail. The model
puts EF's DateTimeOffsetToBinaryConverter on every timestamp column, so every row
already written says (localTicks / 1000) * 2048 + (offsetMinutes & 2047); the
formula was derived by probing EF's converter and is now pinned by
SqliteTimestampEncodingTests against that converter over five instants including
+05:30, -05:00 and DateTimeOffset.MinValue — including the microsecond
truncation the /1000 imposes, which is EF's behaviour and is now a test rather
than a future surprise.

Two build traps, both paid for and both recorded where the next person will hit
them. -p:PublishAot on the command line is a global property, so it reaches every
project in the graph including a netstandard2.0 Roslyn analyzer, and the publish
dies with NETSDK1207; AOT is now switched by OpenWafAot=true, which only
OpenWaf.Edge.csproj turns into PublishAot — the same shape as the existing
OpenWafCompiledModel switch. And a raw Microsoft.Data.Sqlite data source needs
SQLitePCL.Batteries.Init() before its first open, because the order in which
EF's provider and this data source are first used is not guaranteed.

Gates on this tree: build 0 warnings, unit 391/391 (13 new: rendered SQL for both
dialects, null tests, the captured-null case, the refusals, the timestamp
encoding), integration 408/408, smoke 256/256, and the AOT probe above. One
earlier run of the 408 carried a single failure in AdminConsoleTests at a host
load average near 30 and the next run was clean; recorded rather than hidden, in
the same family as the load-sensitive compose gates this README already
documents.
2026-10-07 21:48:01 +02:00

246 lines
11 KiB
C#

using Microsoft.EntityFrameworkCore;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Twelve tables, all small. The edge never queries them on the request path —
/// <see cref="EdgeStateStore"/> holds the snapshot it reads — so the schema is
/// sized for operator inspection and for explaining a ban after the fact, not
/// for throughput.
/// </summary>
public sealed class OpenWafDbContext(DbContextOptions<OpenWafDbContext> options) : DbContext(options)
{
public DbSet<BlockEntry> Blocks => Set<BlockEntry>();
public DbSet<AllowEntry> AllowEntries => Set<AllowEntry>();
public DbSet<SourceObservation> Observations => Set<SourceObservation>();
public DbSet<CountryRule> CountryRules => Set<CountryRule>();
public DbSet<EdgeAlert> Alerts => Set<EdgeAlert>();
public DbSet<PolicySetting> PolicySettings => Set<PolicySetting>();
public DbSet<SourceStreak> Streaks => Set<SourceStreak>();
public DbSet<RequestRule> RequestRules => Set<RequestRule>();
public DbSet<AlertPush> AlertPushes => Set<AlertPush>();
public DbSet<ConfigChange> ConfigChanges => Set<ConfigChange>();
public DbSet<NetworkBan> NetworkBans => Set<NetworkBan>();
public DbSet<RateRule> RateRules => Set<RateRule>();
protected override void OnModelCreating(ModelBuilder mb)
{
StoreTimestampsAsIntegersOnSqlite(mb);
mb.Entity<BlockEntry>(e =>
{
e.ToTable("block_entries");
e.HasKey(b => b.Id);
// One row per (source key, provenance): an operator block and an
// engine ban on the same address coexist on purpose — the operator
// entry outlives the ban and must not be overwritten by it.
e.HasIndex(b => new { b.SourceKey, b.Source }).IsUnique();
e.HasIndex(b => b.ExpiresAt);
e.Property(b => b.SourceKey).HasMaxLength(128).IsRequired();
e.Property(b => b.Reason).HasMaxLength(1024);
e.Property(b => b.RedirectTo).HasMaxLength(512);
e.Property(b => b.LastPath).HasMaxLength(512);
e.Property(b => b.LastUserAgent).HasMaxLength(256);
e.Property(b => b.LastCountryCode).HasMaxLength(2);
e.Property(b => b.LastCity).HasMaxLength(128);
e.Property(b => b.LastRegion).HasMaxLength(128);
e.Property(b => b.Source).HasConversion<int>();
});
mb.Entity<NetworkBan>(e =>
{
// A ban on a network rather than an address (OPEN-66). Its own table
// rather than a flag on block_entries: block_entries is keyed on the
// source key, and a range is not a key — the exact-key lookup that
// enforces an address block would answer "is this address exactly
// this network address", which is not the question.
e.ToTable("network_bans");
e.HasKey(b => b.Id);
// One row per normalised network: 198.51.100.37/24 and
// 198.51.100.0/24 are one claim, and two rows for it is two rows an
// operator has to notice and remove.
e.HasIndex(b => b.Match).IsUnique();
e.HasIndex(b => b.ExpiresAt);
e.Property(b => b.Match).HasMaxLength(64).IsRequired();
e.Property(b => b.Reason).HasMaxLength(1024);
e.Property(b => b.RedirectTo).HasMaxLength(512);
});
mb.Entity<ConfigChange>(e =>
{
// The change log (OPEN-64): one row per deliberate change to the
// operator's config. Indexed on the instant because the surface
// reads newest first, and on the section because "what happened to
// the rules" is the question an operator actually asks.
e.ToTable("config_changes");
e.HasKey(c => c.Id);
e.HasIndex(c => c.At);
e.HasIndex(c => c.Section);
e.Property(c => c.Section).HasMaxLength(16).IsRequired();
e.Property(c => c.Action).HasMaxLength(16).IsRequired();
e.Property(c => c.Target).HasMaxLength(ConfigChangeLog.MaxTargetLength).IsRequired();
e.Property(c => c.Detail).HasMaxLength(ConfigChangeLog.MaxDetailLength);
e.Property(c => c.Actor).HasMaxLength(16).IsRequired();
});
mb.Entity<AllowEntry>(e =>
{
e.ToTable("allow_entries");
e.HasKey(a => a.Id);
e.HasIndex(a => a.Match).IsUnique();
e.Property(a => a.Match).HasMaxLength(128).IsRequired();
e.Property(a => a.Note).HasMaxLength(512);
});
mb.Entity<SourceObservation>(e =>
{
e.ToTable("source_observations");
e.HasKey(o => o.SourceKey);
e.Property(o => o.SourceKey).HasMaxLength(128);
e.HasIndex(o => o.LastSeenAt);
e.Property(o => o.LastPath).HasMaxLength(512);
e.Property(o => o.LastUserAgent).HasMaxLength(256);
e.Property(o => o.LastCountryCode).HasMaxLength(2);
e.Property(o => o.LastCity).HasMaxLength(128);
e.Property(o => o.LastRegion).HasMaxLength(128);
});
mb.Entity<SourceStreak>(e =>
{
e.ToTable("source_streaks");
e.HasKey(t => t.SourceKey);
e.Property(t => t.SourceKey).HasMaxLength(128);
e.HasIndex(t => t.LastSeenAt);
e.Property(t => t.LastPath).HasMaxLength(512);
e.Property(t => t.LastUserAgent).HasMaxLength(256);
e.Property(t => t.LastCountryCode).HasMaxLength(2);
e.Property(t => t.LastCity).HasMaxLength(128);
e.Property(t => t.LastRegion).HasMaxLength(128);
// The streak row is written by every edge that sees the source, so
// it is the one table in this schema where two writers routinely
// collide. The token is what turns that collision into a retry
// instead of a lost refusal.
e.Property(t => t.Version).IsConcurrencyToken();
});
mb.Entity<CountryRule>(e =>
{
e.ToTable("country_rules");
e.HasKey(c => c.Code);
e.Property(c => c.Code).HasMaxLength(2);
e.Property(c => c.Name).HasMaxLength(128);
});
mb.Entity<EdgeAlert>(e =>
{
e.ToTable("edge_alerts");
e.HasKey(a => a.Id);
e.HasIndex(a => a.CreatedAt);
e.Property(a => a.SourceKey).HasMaxLength(128).IsRequired();
e.Property(a => a.Kind).HasMaxLength(64).IsRequired();
e.Property(a => a.Detail).HasMaxLength(1024).IsRequired();
});
mb.Entity<RequestRule>(e =>
{
e.ToTable("request_rules");
e.HasKey(r => r.Id);
// Not unique: an expired rule keeps its row, and a unique index
// would let a rule that stopped being true last month refuse the
// same pattern forever. "Two live rules for one pattern" is the
// real mistake, and the API refuses that one by name.
e.HasIndex(r => r.Pattern);
e.HasIndex(r => r.ExpiresAt);
e.Property(r => r.Pattern).HasMaxLength(PathPattern.MaxLength).IsRequired();
e.Property(r => r.Note).HasMaxLength(512);
e.Property(r => r.Action).HasConversion<int>();
});
mb.Entity<RateRule>(e =>
{
// A request budget written for one path (OPEN-68). Its own table
// rather than a kind of request_rules: a path rule refuses a request
// for what it asked for, a rate rule refuses it for how often that
// source asked, and the two have different parameters, different
// counters and different reasons to expire.
e.ToTable("rate_rules");
e.HasKey(r => r.Id);
// Not unique, for the same reason request_rules is not: an expired
// budget keeps its row, and a unique index would let a rule that
// stopped being true last month refuse the same pattern forever. Two
// live rules for one pattern is the real mistake, and the API refuses
// that one by name.
e.HasIndex(r => r.Pattern);
e.HasIndex(r => r.ExpiresAt);
e.Property(r => r.Pattern).HasMaxLength(PathPattern.MaxLength).IsRequired();
e.Property(r => r.Note).HasMaxLength(512);
});
mb.Entity<AlertPush>(e =>
{
e.ToTable("alert_pushes");
e.HasKey(a => a.Id);
// The worker's query is "not delivered, not given up, due now, not
// claimed", and it runs every couple of seconds against a table that
// retention keeps short. Without this index that query is a scan of
// every delivery this edge has ever owed.
e.HasIndex(a => new { a.PushedAt, a.GivenUpAt, a.NextAttemptAt });
e.HasIndex(a => a.AlertId);
e.Property(a => a.Kind).HasMaxLength(64).IsRequired();
e.Property(a => a.SourceKey).HasMaxLength(128).IsRequired();
e.Property(a => a.Detail).HasMaxLength(1024).IsRequired();
e.Property(a => a.LastError).HasMaxLength(512);
e.Property(a => a.ClaimedBy).HasMaxLength(128);
});
mb.Entity<PolicySetting>(e =>
{
e.ToTable("policy_settings");
e.HasKey(p => p.Key);
e.Property(p => p.Key).HasMaxLength(64);
e.Property(p => p.Value).HasMaxLength(256).IsRequired();
});
}
/// <summary>
/// SQLite has no timestamp type: the provider stores a DateTimeOffset as
/// text and then refuses to compare it, so every "is this ban still live"
/// and "has this observation aged out" query dies at translation time.
/// Storing the instant as an integer makes those comparisons ordinary
/// integer comparisons and keeps the retention rules working on the default
/// provider. PostgreSQL keeps its native timestamptz, where an operator can
/// read the column.
/// </summary>
private void StoreTimestampsAsIntegersOnSqlite(ModelBuilder mb)
{
if (Database.ProviderName?.Contains("Sqlite") != true) return;
var converter = new Microsoft.EntityFrameworkCore.Storage.ValueConversion.DateTimeOffsetToBinaryConverter();
foreach (var entityType in mb.Model.GetEntityTypes())
{
foreach (var property in entityType.GetProperties())
{
var clr = property.ClrType;
if (clr == typeof(DateTimeOffset) || clr == typeof(DateTimeOffset?))
{
property.SetValueConverter(converter);
}
}
}
}
}
/// <summary>
/// Operator-set policy overrides, one row per key, layered over what comes
/// from configuration. Stored as text on purpose: the set of knobs is small and
/// a column per knob would need a migration every time one is added.
/// </summary>
[OpenWaf.Data.Table("policy_settings")]
public sealed class PolicySetting
{
public string Key { get; init; } = string.Empty;
public string Value { get; set; } = string.Empty;
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
}