Files
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

142 lines
7.3 KiB
C#

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace OpenWaf.Data.Generator;
/// <summary>
/// Emits the ORM plumbing for a class marked <c>[Table]</c>: the column map, the
/// row materializer, and the metadata registration — all as ordinary C#, at
/// build time.
///
/// Why generated rather than reflected: the whole NativeAOT wall on this tree is
/// that a compiled binary cannot answer "what are this type's properties" at run
/// time. EF's answer to that question is the sentence the probe counts — 32
/// refusals in the 2026-10-07 window. Here the answer is a switch the compiler
/// wrote, so the question is never asked.
///
/// The column name is the property name unless a <c>[Column]</c> says otherwise,
/// because that is what this schema of record uses: <c>schema.sqlite.sql</c>
/// creates <c>"policy_settings"("Key","Value","UpdatedAt")</c>.
/// </summary>
[Generator]
public sealed class EntityOrmGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var entities = context.SyntaxProvider
.ForAttributeWithMetadataName(
"OpenWaf.Data.TableAttribute",
static (node, _) => node is ClassDeclarationSyntax,
static (ctx, _) => Read((INamedTypeSymbol)ctx.TargetSymbol))
.Collect();
context.RegisterSourceOutput(entities, static (spc, entities) =>
{
foreach (var entity in entities)
spc.AddSource("OpenWaf.Data." + entity.ShortName + "Orm.g.cs", Emit(entity));
});
}
private static Entity Read(INamedTypeSymbol type)
{
var table = AttributeArgument(type, "OpenWaf.Data.TableAttribute") ?? type.Name;
var columns = new List<ColumnMapping>();
foreach (var member in type.GetMembers().OfType<IPropertySymbol>())
{
if (member.IsStatic || member.IsIndexer) continue;
if (member.GetMethod is null) continue;
if (member.DeclaredAccessibility != Accessibility.Public) continue;
var name = AttributeArgument(member, "OpenWaf.Data.ColumnAttribute") ?? member.Name;
// "global::" is stripped so the switch below can name a type the way a
// reader writes it; the generated code uses the same string.
columns.Add(new ColumnMapping(
member.Name,
name,
member.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat).Replace("global::", string.Empty)));
}
return new Entity(
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
type.Name,
table,
columns.ToImmutableArray());
}
private static string? AttributeArgument(ISymbol symbol, string attributeName)
{
var attribute = symbol.GetAttributes()
.FirstOrDefault(a => a.AttributeClass?.ToDisplayString() == attributeName);
return attribute?.ConstructorArguments.Length > 0 ? attribute.ConstructorArguments[0].Value as string : null;
}
private static string Emit(Entity entity)
{
var sb = new StringBuilder();
sb.AppendLine("// <auto-generated/>");
sb.AppendLine("// Generated from " + entity.TypeName + " by OpenWaf.Data.Generator. Do not edit.");
sb.AppendLine("#nullable enable");
sb.AppendLine("using System.Collections.Immutable;");
sb.AppendLine("using System.Data.Common;");
sb.AppendLine("using System.Runtime.CompilerServices;");
sb.AppendLine("using OpenWaf.Data;");
sb.AppendLine();
if (entity.Namespace.Length > 0) sb.AppendLine("namespace " + entity.Namespace + ";");
sb.AppendLine();
sb.AppendLine("/// <summary>The generated data access for <c>" + entity.ShortName + "</c>: the table's");
sb.AppendLine("/// metadata, its column map and its row materializer. Nothing here is discovered at");
sb.AppendLine("/// run time, which is the point.</summary>");
sb.AppendLine("public static class " + entity.ShortName + "Orm");
sb.AppendLine("{");
sb.AppendLine(" [ModuleInitializer]");
sb.AppendLine(" internal static void RegisterOpenWafData() =>");
sb.AppendLine(" OrmMeta.Register<" + entity.TypeName + ">(");
sb.AppendLine(" " + Literal(entity.Table) + ",");
sb.AppendLine(" ColumnOf,");
sb.AppendLine(" ImmutableArray.Create(" + string.Join(", ", entity.Columns.Select(c => Literal(c.Column))) + "));");
sb.AppendLine();
sb.AppendLine(" /// <summary>CLR member name to column name. Empty means the member is not a");
sb.AppendLine(" /// column of this table, and the query layer says so rather than guessing.</summary>");
sb.AppendLine(" public static string ColumnOf(string member) => member switch");
sb.AppendLine(" {");
foreach (var column in entity.Columns)
sb.AppendLine(" " + Literal(column.Member) + " => " + Literal(column.Column) + ",");
sb.AppendLine(" _ => string.Empty,");
sb.AppendLine(" };");
sb.AppendLine();
sb.AppendLine(" public static Query<" + entity.TypeName + "> Query(OrmContext db) =>");
sb.AppendLine(" new(db, OrmMeta.Get(typeof(" + entity.TypeName + ")), Map);");
sb.AppendLine();
sb.AppendLine(" /// <summary>Reads one row of " + Literal(entity.Table) + " into a new object. The");
sb.AppendLine(" /// ordinals are the order " + "RenderSelect" + " emits, which is the order the");
sb.AppendLine(" /// column list was registered in — one list, one order, no name lookups per row.</summary>");
sb.AppendLine(" public static " + entity.TypeName + " Map(DbDataReader reader, ISqlDialect dialect) => new " + entity.TypeName);
sb.AppendLine(" {");
for (var i = 0; i < entity.Columns.Length; i++)
sb.AppendLine(" " + entity.Columns[i].Member + " = " + Read(entity.Columns[i], i) + ",");
sb.AppendLine(" };");
sb.AppendLine("}");
return sb.ToString();
}
private static string Read(ColumnMapping column, int ordinal) => column.Type switch
{
"string" => "RowReader.String(reader, " + ordinal + ")",
"bool" => "RowReader.Boolean(reader, " + ordinal + ")",
"int" => "RowReader.Int32(reader, " + ordinal + ")",
"long" => "RowReader.Int64(reader, " + ordinal + ")",
"System.DateTimeOffset" => "RowReader.DateTimeOffset(reader, " + ordinal + ", dialect)",
"System.Guid" => "RowReader.Guid(reader, " + ordinal + ")",
_ => "RowReader.Required<" + column.Type + ">(reader, " + ordinal + ")",
};
private static string Literal(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
private sealed record Entity(string Namespace, string TypeName, string ShortName, string Table, ImmutableArray<ColumnMapping> Columns);
private sealed record ColumnMapping(string Member, string Column, string Type);
}