diff --git a/Dockerfile.aot-probe b/Dockerfile.aot-probe index 2fc3235..51e7faa 100644 --- a/Dockerfile.aot-probe +++ b/Dockerfile.aot-probe @@ -58,9 +58,7 @@ RUN . /rid && dotnet publish OpenWaf.Edge/OpenWaf.Edge.csproj \ -c Release \ -r "$RID" \ --self-contained true \ - -p:PublishAot=true \ - -p:InvariantGlobalization=true \ - -p:DebugType=none \ + -p:OpenWafAot=true \ -p:OpenWafCompiledModel=true \ -p:NoWarn=IL2026%3BIL3050 \ -p:IlcTreatWarningsAsErrors=false \ diff --git a/README.md b/README.md index d126321..15e5f34 100644 --- a/README.md +++ b/README.md @@ -416,9 +416,9 @@ bought; as of 2026-10-07 **the first of those two is down on this tree**: never missing code generation, only a registered contract for the shapes that cross the wire. See the next section. - every query is still refused — `Query wasn't precompiled and dynamic code isn't - supported with NativeAOT`, **32 refusals in the 2026-10-07 probe window** - (30 in the run before it — it counts a window, not a total, because the - background refresh loop retries on its own clock) — + supported with NativeAOT`, **18 refusals in the 2026-10-07 probe window** — + 32 before the first query moved off EF, and the count is a window rather than a + total because the background refresh loop retries on its own clock — which is EF's precompiler (the NativeAOT entry in `docs/ARCHITECTURE.md` carries its four untranslatable query shapes and its codegen bug). This is the one wall left, and it is the generator slice. @@ -534,6 +534,74 @@ a `$"…{x}…"` was counted as code. The numbers above are the same tree re-mea with a scanner that skips strings, char literals and comments; the 111 that became `ErrorDto` is the one figure both scanners agree on. +### The first query that does not go through EF + +The query wall is where the generator slice starts, and the first path is moved +and measured. Two new projects: + +* **`dotnet/OpenWaf.Data`** — the runtime, typed over `System.Data.Common` with + no provider package in it. `OrmContext` carries a `DbDataSource` and an + `ISqlDialect`; `Query` renders SQL by **walking** the expression tree, which + is the whole point: EF's pipeline compiles trees into IL at run time, and that + is the sentence the probe counts. The supported grammar is a closed set and it + says so — joins, subqueries, aggregates other than `COUNT`, updates, deletes, + JSON columns and method calls each throw `UnsupportedQueryNodeException` naming + the node, rather than rendering SQL that is quietly wrong. +* **`dotnet/OpenWaf.Data.Generator`** — 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 in a + `[ModuleInitializer]`. Nothing at run time asks a type what its properties are, + because the answer is a switch the compiler wrote. + +`PolicySetting` is the first entity moved, `EdgePolicyProvider.ReloadAsync` the +first call site, and `Program.cs` composes the driver and dialect on the same +`Database:Provider` switch EF uses — sqlite for the shipped image, PostgreSQL for +the migrations' provider, one generated query serving both. + +Measured on the AOT binary, same probe, same window, before and after: + +``` +queries refused at run time: 32 -> 18 +policy reload failures: 1 -> 0 +native binary bytes: 49,609,680 -> 49,676,016 (+66,336) +``` + +The 18 that remain are named by their own stack frames: **14** in +`EdgeStateStore.RefreshAsync`, **2** in `BlockStore.WriteBanAsync`, **1** in +`BlockStore.AddOperatorAsync`, **1** in an admin endpoint. The policy read — the +first refusal in the log before this change — is gone from that list. + +Two facts about the storage contract came out of it. The model puts EF's +`DateTimeOffsetToBinaryConverter` on every timestamp column of sqlite, so that +encoding — `(localTicks / 1000) * 2048 + (offsetMinutes & 2047)` — is what every +row this application has written already says, and the dialect reproduces it. +`SqliteTimestampEncodingTests` asserts the reproduction equals EF's own converter +over five instants (a `+03:00`, a `-05:00`, the half-hour `+05:30`, a sub-second +value and `DateTimeOffset.MinValue`), and asserts the resolution too: the `/1000` +means a round trip through the column drops the sub-microsecond digits, which is +EF's behaviour and is now a test rather than a surprise. + +Two build facts, both paid for: + +* **`-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: Ahead-of-time compilation is not supported + for the target framework`. AOT is now switched on by `OpenWafAot=true`, which + only `OpenWaf.Edge.csproj` acts on; the same pattern this tree already used for + `OpenWafCompiledModel`. +* **A raw `Microsoft.Data.Sqlite` data source needs the native bundle + registered**: `SQLitePCL.Batteries.Init()` before the first open, because the + order in which EF's provider and this data source are first used is not + guaranteed. (`SqliteConnectionFactory` is not public API; the factory is + `SqliteFactory.Instance.CreateDataSource(…)`.) + +Gates on this tree: build **0 warnings**, unit **391/391** (13 new: the rendered +SQL for both dialects, the null tests, the captured-null case, the refusals, and +the timestamp encoding), integration **408/408**, smoke **256/256**. One run of +the 408 carried a single failure in `AdminConsoleTests` at a host load average of +about 30 and the next run was clean; recorded rather than hidden, and it is the +load-sensitive shape this README already documents for the compose gates. + ## Schema Migrations are the schema of record for PostgreSQL, which is the provider a diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4a040e1..49fb99d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -47,10 +47,10 @@ classifies the status, and is the only thing that can create an engine ban. starts, creates its own schema from the DDL the binary carries **and serves**: `Now listening on:`, `/healthz` 200, a proxied request 200, its own `--healthcheck` mode exit 0. What it still cannot do is run a query. EF refuses - to compile a LINQ query at run time in a NativeAOT binary — **32 refusals in - the 2026-10-07 probe window**, 30 in the run before it: a window count, not a - total, because the background refresh loop retries on its own clock — and the - only alternative, `dotnet ef dbcontext optimize + to compile a LINQ query at run time in a NativeAOT binary — **18 refusals in + the 2026-10-07 probe window, 32 before the first query moved off EF** (a window + count, not a total: the background refresh loop retries on its own clock) — and + the only alternative, `dotnet ef dbcontext optimize --precompile-queries`, first refused 40 of this tree's queries (parameter-symbol roots and captures, dotnet/efcore#35887 / #38030 / #35494, fixed only in the 12.0-preview1 line). Four refusals remain, and they are not a style to rewrite @@ -169,6 +169,42 @@ classifies the status, and is the only thing that can create an engine ban. supplied at composition. That is the slice this entry points at (OPEN-79), and the reason it is the *correct* step rather than the cheap one: it removes the walls instead of routing around them. + + **The first query moved (2026-10-07).** `dotnet/OpenWaf.Data` (a runtime typed + over `System.Data.Common`, no provider package in it) and + `dotnet/OpenWaf.Data.Generator` (a Roslyn incremental generator attached to + `OpenWaf.Infrastructure` as an analyzer) are that mechanism, first slice. The + generator emits, for a `[Table]` class, 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. `Query` renders SQL by **walking** the expression tree rather than + compiling it, which is the exact difference from EF's pipeline. The supported + grammar is a closed set that refuses by name — joins, subqueries, aggregates + other than `COUNT`, updates, deletes, JSON columns, method calls — because a + renderer that guesses is a renderer that ships wrong SQL. + Measured on the AOT binary with the same probe and the same window: query + refusals **32 → 18**, `EdgePolicyProvider: reload failed` **1 → 0**, binary + **49,609,680 → 49,676,016 bytes**. The 18 are named by their own frames: 14 + `EdgeStateStore.RefreshAsync`, 2 `BlockStore.WriteBanAsync`, 1 + `BlockStore.AddOperatorAsync`, 1 admin endpoint. EF still owns every write and + every other read; the two layers coexist on one composition root, which is what + makes the move incremental rather than a rewrite. + + Two contracts this had to respect, both now asserted rather than assumed. The + sqlite timestamp column is EF's `DateTimeOffsetToBinaryConverter` — every row + already written says `(localTicks / 1000) * 2048 + (offsetMinutes & 2047)` — and + `SqliteTimestampEncodingTests` pins the dialect's read and write to EF's own + converter across five instants including a `+05:30` and `DateTimeOffset.MinValue`, + including the microsecond truncation that encoding imposes. And the dialect, not + the generated code, owns the provider differences: quoting, the paging tail + (`LIMIT -1 OFFSET n` on sqlite, `LIMIT 2147483647 OFFSET n` on PostgreSQL), bool + as INTEGER versus boolean, timestamp as integer versus `timestamptz`. + + One build trap worth recording: **`-p:PublishAot` on the command line is a + global property**, so it reaches every project in the graph — including a + `netstandard2.0` analyzer — and the publish fails 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. * **Keying the ban on ip+UA** (as the analytics `SessionHash` does): a bot that varies its UA multiplies into many sources and never reaches the threshold. * **Banning on 5xx because the original wording said `> 400`**: turns an outage diff --git a/dotnet/OpenWaf.Data.Generator/EntityOrmGenerator.cs b/dotnet/OpenWaf.Data.Generator/EntityOrmGenerator.cs new file mode 100644 index 0000000..12b2bca --- /dev/null +++ b/dotnet/OpenWaf.Data.Generator/EntityOrmGenerator.cs @@ -0,0 +1,141 @@ +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; + +/// +/// Emits the ORM plumbing for a class marked [Table]: 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 [Column] says otherwise, +/// because that is what this schema of record uses: schema.sqlite.sql +/// creates "policy_settings"("Key","Value","UpdatedAt"). +/// +[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(); + foreach (var member in type.GetMembers().OfType()) + { + 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("// "); + 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("/// The generated data access for " + entity.ShortName + ": 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."); + 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(" /// 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."); + 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(" /// 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."); + 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 Columns); + + private sealed record ColumnMapping(string Member, string Column, string Type); +} diff --git a/dotnet/OpenWaf.Data.Generator/IsExternalInit.cs b/dotnet/OpenWaf.Data.Generator/IsExternalInit.cs new file mode 100644 index 0000000..ae5e7a6 --- /dev/null +++ b/dotnet/OpenWaf.Data.Generator/IsExternalInit.cs @@ -0,0 +1,12 @@ +// netstandard2.0 has no IsExternalInit, which the compiler needs for `init` +// accessors in records. Roslyn analyzers target netstandard2.0 so they load in +// every compiler; this is the standard shim, and the neighbouring project ships +// the same one (~/work/tskr/app/lib/IsExternalInit.cs). +using System.ComponentModel; + +namespace System.Runtime.CompilerServices; + +[EditorBrowsable(EditorBrowsableState.Never)] +internal static class IsExternalInit +{ +} diff --git a/dotnet/OpenWaf.Data.Generator/OpenWaf.Data.Generator.csproj b/dotnet/OpenWaf.Data.Generator/OpenWaf.Data.Generator.csproj new file mode 100644 index 0000000..6827b8b --- /dev/null +++ b/dotnet/OpenWaf.Data.Generator/OpenWaf.Data.Generator.csproj @@ -0,0 +1,32 @@ + + + + + + netstandard2.0 + latest + enable + true + + false + false + false + true + + + + + + + diff --git a/dotnet/OpenWaf.Data/OpenWaf.Data.csproj b/dotnet/OpenWaf.Data/OpenWaf.Data.csproj new file mode 100644 index 0000000..88658b9 --- /dev/null +++ b/dotnet/OpenWaf.Data/OpenWaf.Data.csproj @@ -0,0 +1,22 @@ + + + + + net10.0 + enable + enable + + + + + + + + diff --git a/dotnet/OpenWaf.Data/OrmContext.cs b/dotnet/OpenWaf.Data/OrmContext.cs new file mode 100644 index 0000000..a61d14d --- /dev/null +++ b/dotnet/OpenWaf.Data/OrmContext.cs @@ -0,0 +1,136 @@ +#nullable enable +using System; +using System.Data.Common; + +namespace OpenWaf.Data; + +/// +/// What a generated query needs to run: a driver and a dialect, decided once at +/// composition rather than per call. +/// +/// This is the seam that lets the same generated code serve both providers this +/// tree ships. It is taken from the neighbouring deployment's +/// MicroOrm.OrmContext (~/work/tskr/app/lib/MicroOrmRuntime), which +/// keeps the runtime driver-agnostic and supplies Npgsql at composition; here the +/// drivers are sqlite and Npgsql, chosen by the same Database:Provider +/// switch Program.cs already uses for EF. +/// +public sealed class OrmContext +{ + public DbDataSource DataSource { get; } + public ISqlDialect Dialect { get; } + + public OrmContext(DbDataSource dataSource, ISqlDialect dialect) + { + DataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource)); + Dialect = dialect ?? throw new ArgumentNullException(nameof(dialect)); + } +} + +/// +/// The provider-specific half of query rendering and row reading — and only that +/// half. The SQL text is built once; what differs is the identifier quoting, the +/// paging tail, and how a CLR value crosses to and from the wire. +/// +/// The timestamp members are not decoration. This tree stores a +/// as a binary integer on sqlite and as native +/// timestamptz on PostgreSQL — the model does it deliberately, because +/// sqlite stores a timestamp as text and then refuses to compare it, which kills +/// every "is this ban still live" query at translation time (see +/// OpenWafDbContext.StoreTimestampsAsIntegersOnSqlite). A generated +/// materializer therefore cannot know how to read the column; the dialect does. +/// +public interface ISqlDialect +{ + string Quote(string identifier); + + /// The placeholder for the parameter at this ordinal, 0-based. + string Param(int index); + + /// The paging tail, or empty when neither limit nor offset is set. + string Page(int? limit, int? offset); + + string CountAllExpression { get; } + + string PingStatement { get; } + + /// How this provider stores a column. + DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal); + + /// The value to hand the driver for a DateTimeOffset parameter. + object WriteDateTimeOffset(DateTimeOffset value); +} + +/// sqlite, the provider the shipped image runs. +public sealed class SqliteDialect : ISqlDialect +{ + public static SqliteDialect Instance { get; } = new(); + + public string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"", StringComparison.Ordinal) + "\""; + + // Microsoft.Data.Sqlite binds named parameters, so one text works for both + // providers and the rendered SQL stays readable in a log. + public string Param(int index) => "@p" + index.ToString(System.Globalization.CultureInfo.InvariantCulture); + + public string Page(int? limit, int? offset) + { + if (limit is null && offset is null) return string.Empty; + // sqlite requires LIMIT before OFFSET, and an OFFSET needs a LIMIT to + // anchor it — -1 means "no limit" in sqlite's own grammar. + return " LIMIT " + (limit ?? -1).ToString(System.Globalization.CultureInfo.InvariantCulture) + + (offset is null ? string.Empty : " OFFSET " + offset.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + + public string CountAllExpression => "COUNT(*)"; + + public string PingStatement => "SELECT 1"; + + /// + /// The integer EF writes for this column, read back. The model puts a + /// through EF's DateTimeOffsetToBinaryConverter + /// on sqlite, and that encoding is the storage contract of every row the admin + /// API has ever written — so this is not a format this project chose. It is + /// reproduced here as (localTicks / 1000) * 2048 + (offsetMinutes & 2047) + /// and asserted equal to EF's own converter over a spread of instants + /// (positive, negative and half-hour offsets, and DateTime.MinValue) in + /// SqliteTimestampEncodingTests, so a provider upgrade that changes it + /// is red in a test rather than wrong in production. Note the /1000: this + /// column has microsecond resolution, and a round trip through it drops the + /// sub-microsecond digits. That is EF's behaviour, not a bug added here. + /// + public DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal) + { + var stored = reader.GetInt64(ordinal); + var offsetMinutes = (int)(stored & 2047); + if (offsetMinutes >= 1024) offsetMinutes -= 2048; + return new DateTimeOffset((stored >> 11) * 1000, TimeSpan.FromMinutes(offsetMinutes)); + } + + public object WriteDateTimeOffset(DateTimeOffset value) => + (value.Ticks / 1000) * 2048 + ((int)value.Offset.TotalMinutes & 2047); +} + +/// PostgreSQL, the provider a real deployment runs (migrations are its schema of record). +public sealed class PostgresDialect : ISqlDialect +{ + public static PostgresDialect Instance { get; } = new(); + + public string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"", StringComparison.Ordinal) + "\""; + + public string Param(int index) => "@p" + index.ToString(System.Globalization.CultureInfo.InvariantCulture); + + public string Page(int? limit, int? offset) + { + if (limit is null && offset is null) return string.Empty; + return " LIMIT " + (limit ?? int.MaxValue).ToString(System.Globalization.CultureInfo.InvariantCulture) + + (offset is null ? string.Empty : " OFFSET " + offset.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + + public string CountAllExpression => "COUNT(*)"; + + public string PingStatement => "SELECT 1"; + + public DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal) => reader.GetFieldValueAsync(ordinal).GetAwaiter().GetResult(); + + public object WriteDateTimeOffset(DateTimeOffset value) => value; +} diff --git a/dotnet/OpenWaf.Data/OrmMeta.cs b/dotnet/OpenWaf.Data/OrmMeta.cs new file mode 100644 index 0000000..4c0a59a --- /dev/null +++ b/dotnet/OpenWaf.Data/OrmMeta.cs @@ -0,0 +1,52 @@ +#nullable enable +using System; +using System.Collections.Concurrent; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; + +namespace OpenWaf.Data; + +/// Marks a class as a row of a table. The name is the table; the +/// generator reads it and emits the mapping, so nothing at run time has to ask a +/// type what it is. +[AttributeUsage(AttributeTargets.Class)] +public sealed class TableAttribute(string name) : Attribute +{ + public string Name { get; } = name; +} + +/// Names the column a property maps to when it is not the snake_case of +/// the property name. +[AttributeUsage(AttributeTargets.Property)] +public sealed class ColumnAttribute(string name) : Attribute +{ + public string Name { get; } = name; +} + +/// +/// The table's metadata, registered by generated code at module start-up. +/// +/// This is the piece that makes the whole thing AOT-safe: the mapping from a CLR +/// member name to a column name is a function the compiler emitted, not something +/// a run-time resolver discovers. A NativeAOT binary has no resolver to fall back +/// on, and asking for one is exactly the refusal this slice exists to remove. +/// Taken from MicroOrm.OrmMeta in the neighbouring deployment. +/// +public static class OrmMeta +{ + private static readonly ConcurrentDictionary Map = new(); + + public static void Register(string table, Func columnOf, ImmutableArray columns) => + Map[typeof(T)] = new TableMeta(table, columnOf, columns); + + public static bool TryGet(Type type, [MaybeNullWhen(false)] out TableMeta meta) => Map.TryGetValue(type, out meta); + + public static TableMeta Get(Type type) => + Map.TryGetValue(type, out var meta) + ? meta + : throw new InvalidOperationException( + $"No generated ORM metadata is registered for {type.FullName}. The type needs [Table] and the " + + "OpenWaf.Data.Generator analyzer attached to the project that declares it."); +} + +public sealed record TableMeta(string Table, Func ColumnOf, ImmutableArray Columns); diff --git a/dotnet/OpenWaf.Data/Query.cs b/dotnet/OpenWaf.Data/Query.cs new file mode 100644 index 0000000..e0ea954 --- /dev/null +++ b/dotnet/OpenWaf.Data/Query.cs @@ -0,0 +1,339 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Globalization; +using System.Linq.Expressions; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace OpenWaf.Data; + +/// +/// A typed query whose SQL is rendered from an expression tree that is walked, +/// never compiled. +/// +/// That last clause is the whole reason this type exists. EF answers the same +/// shape under NativeAOT with Query wasn't precompiled and dynamic code isn't +/// supported with NativeAOT — 32 of them in the 2026-10-07 probe window +/// before the first query moved off EF, 18 after — +/// because its query pipeline compiles expression trees into IL at run time. +/// Walking the tree with a switch over needs no +/// dynamic code, and the row materializer is a Func<DbDataReader,T> +/// the compiler emitted, so there is nothing left for the runtime to generate. +/// The mechanism is the neighbouring deployment's +/// (~/work/tskr/app/lib/MicroOrmRuntime/Query.cs, 1,219 lines); this is the +/// first slice of it, sized to the one query this tree has moved so far. +/// +/// The supported grammar is a closed set, and it says so. Anything outside +/// it throws naming the node, rather +/// than rendering SQL that is quietly wrong. What is supported today: comparisons +/// (== != < <= > >=) between a column and a value, null tests, +/// &&, ||, !, captured locals and closure fields on the +/// value side, ordering, Take/Skip. What is not: joins, subqueries, +/// aggregates other than Count, updates and deletes, JSON columns, enum +/// comparisons. Each of those is a decision with a cost, not an oversight — and +/// RenderSelect is public so the rendered text can be asserted without a +/// database, which is how the neighbouring project tests its own renderers. +/// +public sealed class Query +{ + private readonly OrmContext _db; + private readonly Func _map; + private readonly TableMeta _meta; + private readonly List _where = []; + private readonly List<(string Column, bool Descending)> _order = []; + private readonly List _args = []; + private int? _limit; + private int? _offset; + + public Query(OrmContext db, TableMeta meta, Func map) + { + _db = db; + _meta = meta; + _map = map; + } + + public Query Where(Expression> predicate) + { + // No extra parentheses here: Translate parenthesizes every binary term it + // emits, so a WHERE over one term reads as WHERE (x = @p0) and a WHERE over + // several reads as WHERE ((…) AND (…)) rather than a stack of brackets. + _where.Add(Translate(predicate.Body, predicate.Parameters[0])); + return this; + } + + public Query OrderBy(Expression> selector) => Order(selector, false); + public Query OrderByDescending(Expression> selector) => Order(selector, true); + + private Query Order(Expression> selector, bool descending) + { + _order.Add((ColumnOf(selector.Body, selector.Parameters[0]), descending)); + return this; + } + + public Query Take(int n) { _limit = n; return this; } + public Query Skip(int n) { _offset = n; return this; } + + /// The SELECT this query would run, with the parameters it binds in + /// the same order. Public on purpose: the renderer is the test seam, and a + /// wrong query should be red against a string, not only against a database. + public string RenderSelect() + { + var sb = new StringBuilder("SELECT "); + var quoted = new List(_meta.Columns.Length); + foreach (var column in _meta.Columns) quoted.Add(_db.Dialect.Quote(column)); + sb.Append(string.Join(", ", quoted)); + return AppendFrom(sb); + } + + /// The COUNT this query would run for . + public string RenderCount() => AppendFrom(new StringBuilder("SELECT " + _db.Dialect.CountAllExpression)); + + private string AppendFrom(StringBuilder sb) + { + sb.Append(" FROM ").Append(_db.Dialect.Quote(_meta.Table)); + if (_where.Count > 0) sb.Append(" WHERE ").Append(string.Join(" AND ", _where)); + if (_order.Count > 0) + { + sb.Append(" ORDER BY "); + var terms = new List(_order.Count); + foreach (var o in _order) + terms.Add(_db.Dialect.Quote(o.Column) + (o.Descending ? " DESC" : " ASC")); + sb.Append(string.Join(", ", terms)); + } + sb.Append(_db.Dialect.Page(_limit, _offset)); + return sb.ToString(); + } + + public IReadOnlyList Arguments => _args; + + public async Task> ToListAsync(CancellationToken ct = default) + { + var sql = RenderSelect(); + await using var connection = await _db.DataSource.OpenConnectionAsync(ct); + await using var command = connection.CreateCommand(); + command.CommandText = sql; + Bind(command); + await using var reader = await command.ExecuteReaderAsync(ct); + var rows = new List(); + while (await reader.ReadAsync(ct)) rows.Add(_map(reader, _db.Dialect)); + return rows; + } + + public async Task CountAsync(CancellationToken ct = default) + { + var sql = RenderCount(); + await using var connection = await _db.DataSource.OpenConnectionAsync(ct); + await using var command = connection.CreateCommand(); + command.CommandText = sql; + Bind(command); + var value = await command.ExecuteScalarAsync(ct); + return Convert.ToInt64(value, CultureInfo.InvariantCulture); + } + + public async Task FirstOrDefaultAsync(CancellationToken ct = default) + { + _limit = 1; + var rows = await ToListAsync(ct); + return rows.Count > 0 ? rows[0] : default; + } + + private void Bind(DbCommand command) + { + for (var i = 0; i < _args.Count; i++) + { + var parameter = command.CreateParameter(); + parameter.ParameterName = "@p" + i.ToString(CultureInfo.InvariantCulture); + parameter.Value = _args[i] ?? DBNull.Value; + command.Parameters.Add(parameter); + } + } + + // ---- the translator ---------------------------------------------------- + + private string Translate(Expression expression, ParameterExpression entity) + { + switch (expression) + { + case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert: + return Translate(convert.Operand, entity); + + case UnaryExpression { NodeType: ExpressionType.Not } not: + return "NOT (" + Translate(not.Operand, entity) + ")"; + + case BinaryExpression binary: + return TranslateBinary(binary, entity); + + case MemberExpression flag when IsColumn(flag, entity): + // A bare boolean column, rendered as a truth test: both providers + // this tree runs store a bool as 1/0. + return _db.Dialect.Quote(ColumnOf(flag, entity)) + " = 1"; + + case MethodCallExpression call: + throw new UnsupportedQueryNodeException( + $"method call '{call.Method.DeclaringType?.Name}.{call.Method.Name}'"); + + default: + throw new UnsupportedQueryNodeException(expression.NodeType.ToString()); + } + } + + private string TranslateBinary(BinaryExpression binary, ParameterExpression entity) + { + switch (binary.NodeType) + { + case ExpressionType.AndAlso: + return "(" + Translate(binary.Left, entity) + " AND " + Translate(binary.Right, entity) + ")"; + case ExpressionType.OrElse: + return "(" + Translate(binary.Left, entity) + " OR " + Translate(binary.Right, entity) + ")"; + } + + var left = Operand(binary.Left, entity); + var right = Operand(binary.Right, entity); + + // A null on either side is an IS [NOT] NULL test, never an equality with a + // parameter: "col = NULL" is unknown, not false, and a ban filter built that + // way silently stops matching the rows it was written for. + if (left.IsNull && right.IsNull) + throw new UnsupportedQueryNodeException("null compared with null"); + if (left.IsNull) return NullTest(right.Column, binary.NodeType); + if (right.IsNull) return NullTest(left.Column, binary.NodeType); + + var op = binary.NodeType switch + { + ExpressionType.Equal => "=", + ExpressionType.NotEqual => "<>", + ExpressionType.GreaterThan => ">", + ExpressionType.GreaterThanOrEqual => ">=", + ExpressionType.LessThan => "<", + ExpressionType.LessThanOrEqual => "<=", + _ => throw new UnsupportedQueryNodeException(binary.NodeType.ToString()), + }; + + // One side is the column, the other is a value already mapped for this + // provider. The parameter is appended before the placeholder is written, so + // the numbering and the bind order cannot disagree. + var column = left.Column ?? right.Column + ?? throw new UnsupportedQueryNodeException("a comparison with no column on either side"); + _args.Add(left.Column is null ? left.Value : right.Value); + // Parenthesized even though SQL's own precedence would usually allow it + // without: a rendered predicate is read by a human in a log, and a test + // that mixes AND and OR should not depend on who remembers the table. + return "(" + _db.Dialect.Quote(column) + " " + op + " " + _db.Dialect.Param(_args.Count - 1) + ")"; + } + + private string NullTest(string? column, ExpressionType nodeType) + { + if (column is null) + throw new UnsupportedQueryNodeException("a null test with no column to test"); + return nodeType switch + { + ExpressionType.Equal => "(" + _db.Dialect.Quote(column) + " IS NULL)", + ExpressionType.NotEqual => "(" + _db.Dialect.Quote(column) + " IS NOT NULL)", + _ => throw new UnsupportedQueryNodeException(nodeType.ToString() + " against null"), + }; + } + + private readonly record struct OperandResult(string? Column, object? Value, bool IsNull); + + private OperandResult Operand(Expression expression, ParameterExpression entity) + { + var unwrapped = Unwrap(expression); + if (unwrapped is ConstantExpression { Value: null }) return new OperandResult(null, null, true); + if (IsColumn(unwrapped, entity)) return new OperandResult(ColumnOf(unwrapped, entity), null, false); + var mapped = Value(unwrapped, entity); + // A captured null is a null test too. Rendering it as "col = @p0" bound to + // DBNull parses, runs, and matches nothing — the quietest wrong answer + // there is, and the one a nullable ban expiry produces. + return new OperandResult(null, mapped, mapped is null); + } + + private static Expression Unwrap(Expression expression) => + expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert + ? Unwrap(convert.Operand) + : expression; + + private static bool IsColumn(Expression expression, ParameterExpression entity) => + Unwrap(expression) is MemberExpression member && RootOf(member) == entity; + + private static Expression? RootOf(Expression expression) => + expression switch + { + MemberExpression member => RootOf(member.Expression!), + UnaryExpression unary => RootOf(unary.Operand), + ParameterExpression parameter => parameter, + _ => null, + }; + + private string ColumnOf(Expression expression, ParameterExpression entity) + { + if (Unwrap(expression) is not MemberExpression member) + throw new UnsupportedQueryNodeException("an ordering or test that is not a column"); + var name = member.Member.Name; + var column = _meta.ColumnOf(name); + if (column.Length == 0) + throw new UnsupportedQueryNodeException($"member '{name}' is not a column of {_meta.Table}"); + return column; + } + + /// The value side of a comparison: a literal, a captured local, or a + /// closure field. Reading a closure field is reflection over a field the + /// compiler generated for a lambda — the same move the neighbouring + /// deployment's renderer makes, and the one its AOT deployment proves works. + private object? Value(Expression expression, ParameterExpression entity) + { + expression = Unwrap(expression); + switch (expression) + { + case ConstantExpression constant: + return MapValue(constant.Value); + + case MemberExpression member: + { + // The root of a captured variable is a ConstantExpression holding + // the closure object itself. It is the OWNER of the field read, not + // a value to bind — mapping it as a parameter is how a captured + // local turns into "a parameter of type <>c__DisplayClass10_0". + object? owner = null; + if (member.Expression is not null) + { + var ownerExpression = Unwrap(member.Expression); + owner = ownerExpression is ConstantExpression root ? root.Value : Value(ownerExpression, entity); + } + + var raw = member.Member switch + { + FieldInfo field => field.GetValue(owner), + PropertyInfo property => property.GetValue(owner), + _ => throw new UnsupportedQueryNodeException($"member '{member.Member.Name}' on the value side"), + }; + return MapValue(raw); + } + + default: + throw new UnsupportedQueryNodeException(expression.NodeType.ToString() + " on the value side"); + } + } + + private object? MapValue(object? value) => value switch + { + null => null, + DateTimeOffset instant => _db.Dialect.WriteDateTimeOffset(instant), + bool flag => flag ? 1 : 0, + string or byte or sbyte or short or ushort or int or uint or long or ulong or float or double or decimal or Guid => value, + _ => throw new UnsupportedQueryNodeException( + $"a parameter of type {value.GetType().Name}; the generated query layer names the CLR types it binds"), + }; +} + +/// A query shape this layer refuses, said by name at the call site +/// rather than answered with SQL that looks right. +public sealed class UnsupportedQueryNodeException(string what) + : NotSupportedException($"OpenWaf.Data cannot render {what}. Either extend the renderer or leave the query to EF.") +{ + public string What { get; } = what; +} diff --git a/dotnet/OpenWaf.Data/RowReader.cs b/dotnet/OpenWaf.Data/RowReader.cs new file mode 100644 index 0000000..f88ead8 --- /dev/null +++ b/dotnet/OpenWaf.Data/RowReader.cs @@ -0,0 +1,84 @@ +#nullable enable +using System; +using System.Data.Common; + +namespace OpenWaf.Data; + +/// +/// The one place a column crosses into a CLR value. +/// +/// Generated code calls these instead of inlining reader.GetString(i) for +/// two reasons. A wrong read is then wrong in one place, and the provider +/// differences have somewhere to live: sqlite stores a bool as an INTEGER and +/// PostgreSQL as a boolean, and a timestamp as an integer and as timestamptz. The +/// generated materializer cannot know which provider it is running against; this +/// can ask. +/// +public static class RowReader +{ + public static string String(DbDataReader reader, int ordinal) => + reader.IsDBNull(ordinal) ? throw Null(ordinal, "string") : reader.GetString(ordinal); + + public static bool Boolean(DbDataReader reader, int ordinal) + { + if (reader.IsDBNull(ordinal)) throw Null(ordinal, "bool"); + // sqlite answers an INTEGER column, Npgsql a boolean one. + return reader.GetValue(ordinal) switch + { + bool flag => flag, + long number => number != 0, + int number => number != 0, + var other => throw Mismatch(ordinal, "bool", other), + }; + } + + public static int Int32(DbDataReader reader, int ordinal) + { + if (reader.IsDBNull(ordinal)) throw Null(ordinal, "int"); + return reader.GetValue(ordinal) switch + { + int number => number, + long number => checked((int)number), + var other => throw Mismatch(ordinal, "int", other), + }; + } + + public static long Int64(DbDataReader reader, int ordinal) + { + if (reader.IsDBNull(ordinal)) throw Null(ordinal, "long"); + return reader.GetValue(ordinal) switch + { + long number => number, + int number => number, + var other => throw Mismatch(ordinal, "long", other), + }; + } + + public static DateTimeOffset DateTimeOffset(DbDataReader reader, int ordinal, ISqlDialect dialect) + { + if (reader.IsDBNull(ordinal)) throw Null(ordinal, "DateTimeOffset"); + return dialect.ReadDateTimeOffset(reader, ordinal); + } + + public static Guid Guid(DbDataReader reader, int ordinal) + { + if (reader.IsDBNull(ordinal)) throw Null(ordinal, "Guid"); + return reader.GetFieldValue(ordinal); + } + + /// A CLR type this layer has no named read for. It still reads — the + /// driver's own conversion is used — so an entity gains a plain column without + /// the generator having to know about it, and a column the driver cannot + /// convert fails with the ordinal and the type in the message. + public static T Required(DbDataReader reader, int ordinal) + { + if (reader.IsDBNull(ordinal)) throw Null(ordinal, typeof(T).Name); + return reader.GetFieldValue(ordinal); + } + + private static InvalidOperationException Null(int ordinal, string type) => + new($"Column {ordinal} is NULL but the generated mapping for {type} does not allow it."); + + private static InvalidCastException Mismatch(int ordinal, string expected, object actual) => + new($"Column {ordinal} came back as {actual.GetType().Name} and the generated mapping expects {expected}."); +} diff --git a/dotnet/OpenWaf.Edge/OpenWaf.Edge.csproj b/dotnet/OpenWaf.Edge/OpenWaf.Edge.csproj index aa9d58b..889a185 100644 --- a/dotnet/OpenWaf.Edge/OpenWaf.Edge.csproj +++ b/dotnet/OpenWaf.Edge/OpenWaf.Edge.csproj @@ -1,5 +1,19 @@ + + + true + true + none + + net10.0 enable diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index dbccb47..ee5f720 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -66,6 +66,9 @@ builder.Services.AddSingleton(sp => sp.GetRequiredService(options => { if (provider.Equals("postgres", StringComparison.OrdinalIgnoreCase)) options.UseNpgsql(connectionString); diff --git a/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj b/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj index 5342c78..88609b4 100644 --- a/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj +++ b/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj @@ -2,6 +2,13 @@ + + + diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs index 4c993d2..fe04ea0 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs @@ -61,9 +61,18 @@ public sealed class EdgePolicyProvider try { using var scope = _scopeFactory.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); var token = ct; - var rows = await db.PolicySettings.AsNoTracking().ToListAsync(token); + // The read moved to the generated query layer (OPEN-79, wall 3). EF + // answers this exact query — a whole-table read with no predicate — with + // "Query wasn't precompiled and dynamic code isn't supported with + // NativeAOT" in an AOT binary, and it was the first refusal in the probe + // log. The SQL is rendered from the expression tree by walking it, and the + // row materializer is a function the compiler emitted, so there is nothing + // left for the run time to generate. The writes below still go through EF; + // they are the next ones standing. + var rows = await PolicySettingOrm + .Query(scope.ServiceProvider.GetRequiredService()) + .ToListAsync(token); _current = ApplyOverrides(_current, rows); Interlocked.Exchange(ref _reloadFailures, 0); Volatile.Write(ref _lastReloadError, null); diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDataComposition.cs b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDataComposition.cs new file mode 100644 index 0000000..658d844 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDataComposition.cs @@ -0,0 +1,41 @@ +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Data; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// Composition of the generated query layer: the driver and the dialect, chosen by +/// the same Database:Provider switch that chooses EF's provider. +/// +/// This is the seam the neighbouring deployment uses the same way — its runtime is +/// driver-agnostic over System.Data.Common and Npgsql is supplied at +/// composition. Keeping the choice in one place is what lets the same generated +/// code serve sqlite (the shipped image) and PostgreSQL (the migrations' provider) +/// without either one knowing about the other. +/// +public static class OpenWafDataComposition +{ + public static IServiceCollection AddOpenWafData(this IServiceCollection services, string provider, string connectionString) + { + var useSqlite = !provider.Equals("postgres", StringComparison.OrdinalIgnoreCase); + + services.AddSingleton(_ => useSqlite + ? new OrmContext(SqliteDataSource(connectionString), SqliteDialect.Instance) + : new OrmContext(PostgresDataSource(connectionString), PostgresDialect.Instance)); + + return services; + } + + private static System.Data.Common.DbDataSource SqliteDataSource(string connectionString) + { + // Microsoft.Data.Sqlite needs the native bundle registered before the + // first connection opens. EF does this when its sqlite provider is + // constructed; a raw data source does not get to assume that happened + // first, and the order here is not guaranteed. The call is idempotent. + SQLitePCL.Batteries.Init(); + return Microsoft.Data.Sqlite.SqliteFactory.Instance.CreateDataSource(connectionString); + } + + private static System.Data.Common.DbDataSource PostgresDataSource(string connectionString) => + Npgsql.NpgsqlDataSource.Create(connectionString); +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs index 9a86f2d..cc475aa 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs @@ -236,6 +236,7 @@ public sealed class OpenWafDbContext(DbContextOptions options) /// 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. /// +[OpenWaf.Data.Table("policy_settings")] public sealed class PolicySetting { public string Key { get; init; } = string.Empty; diff --git a/dotnet/OpenWaf.Tests.Unit/GeneratedQueryTests.cs b/dotnet/OpenWaf.Tests.Unit/GeneratedQueryTests.cs new file mode 100644 index 0000000..2073fc5 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/GeneratedQueryTests.cs @@ -0,0 +1,197 @@ +using System.Data.Common; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using OpenWaf.Data; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Unit; + +/// +/// The generated query layer, checked against rendered SQL rather than against a +/// database. A wrong query should be red against a string — the same reason the +/// neighbouring deployment keeps its renderers public. +/// +/// These tests also assert that the generator contributed to the build at all: +/// the metadata registration is a module initializer, and a generator that stops +/// running would otherwise show up as a failure inside the edge. +/// +public sealed class GeneratedQueryTests +{ + private const string SelectAll = + "SELECT \"Key\", \"Value\", \"UpdatedAt\" FROM \"policy_settings\""; + + /// A data source that is never asked for a connection: rendering a + /// query must not need one, and this says so in the type system. + private sealed class NeverOpenedDataSource : DbDataSource + { + public override string ConnectionString { get; } = string.Empty; + + protected override DbConnection CreateDbConnection() => + throw new NotSupportedException("rendering a query must not open a connection"); + } + + private static OrmContext Sqlite => new(new NeverOpenedDataSource(), SqliteDialect.Instance); + private static OrmContext Postgres => new(new NeverOpenedDataSource(), PostgresDialect.Instance); + + [Fact] + public void The_generator_registered_the_table_it_was_given() + { + Assert.True(OrmMeta.TryGet(typeof(PolicySetting), out var meta), + "no generated metadata is registered for PolicySetting — the analyzer is not running"); + + Assert.Equal("policy_settings", meta.Table); + Assert.Equal(new[] { "Key", "Value", "UpdatedAt" }, meta.Columns.ToArray()); + Assert.Equal("UpdatedAt", PolicySettingOrm.ColumnOf("UpdatedAt")); + Assert.Equal(string.Empty, PolicySettingOrm.ColumnOf("NotAColumn")); + } + + [Fact] + public void A_whole_table_read_renders_the_columns_the_schema_has() => + Assert.Equal(SelectAll, PolicySettingOrm.Query(Sqlite).RenderSelect()); + + [Fact] + public void A_captured_local_becomes_a_parameter_and_never_text_in_the_statement() + { + const string key = "streakThreshold"; + var query = PolicySettingOrm.Query(Sqlite).Where(p => p.Key == key); + + Assert.Equal(SelectAll + " WHERE (\"Key\" = @p0)", query.RenderSelect()); + Assert.Single(query.Arguments); + Assert.Equal("streakThreshold", query.Arguments[0]); + } + + [Fact] + public void A_null_test_stays_an_is_null_and_never_becomes_an_equality_with_null() + { + // "col = NULL" is unknown rather than false: a filter written that way + // silently stops matching the rows it was written for. + var query = PolicySettingOrm.Query(Sqlite).Where(p => p.Key == "mode" && p.Value != null); + + Assert.Equal( + SelectAll + " WHERE ((\"Key\" = @p0) AND (\"Value\" IS NOT NULL))", + query.RenderSelect()); + } + + [Fact] + public void A_captured_null_is_a_null_test_too() + { + string? value = null; + var query = PolicySettingOrm.Query(Sqlite).Where(p => p.Value == value); + + Assert.Equal(SelectAll + " WHERE (\"Value\" IS NULL)", query.RenderSelect()); + Assert.Empty(query.Arguments); + } + + [Fact] + public void Ordering_and_paging_render_in_the_dialects_own_grammar() + { + Assert.Equal( + SelectAll + " ORDER BY \"Key\" ASC", + PolicySettingOrm.Query(Sqlite).OrderBy(p => p.Key).RenderSelect()); + + Assert.Equal( + SelectAll + " ORDER BY \"UpdatedAt\" DESC LIMIT 10 OFFSET 20", + PolicySettingOrm.Query(Sqlite).OrderByDescending(p => p.UpdatedAt).Skip(20).Take(10).RenderSelect()); + } + + [Fact] + public void Count_renders_against_the_same_where_clause() => + Assert.Equal( + "SELECT COUNT(*) FROM \"policy_settings\" WHERE (\"Key\" = @p0)", + PolicySettingOrm.Query(Sqlite).Where(p => p.Key == "mode").RenderCount()); + + [Fact] + public void Both_providers_get_the_same_text_for_this_query() + { + // One SQL text for both providers is not a coincidence to lean on: it + // holds because both quote with double quotes and both bind named + // parameters. Where they differ is the dialect's job — and paging already + // differs, which is why the two tails are asserted apart. + Assert.Equal( + SelectAll + " LIMIT 2147483647 OFFSET 5", + PolicySettingOrm.Query(Postgres).Skip(5).RenderSelect()); + Assert.Equal( + SelectAll + " LIMIT -1 OFFSET 5", + PolicySettingOrm.Query(Sqlite).Skip(5).RenderSelect()); + } + + [Fact] + public void A_shape_this_layer_has_not_built_refuses_by_name() + { + var ex = Assert.Throws( + () => PolicySettingOrm.Query(Sqlite).Where(p => p.Key.Length == 4)); + Assert.Contains("Length", ex.What, StringComparison.Ordinal); + } + + [Fact] + public void A_member_that_is_not_a_column_refuses_rather_than_guessing() + { + var ex = Assert.Throws( + () => PolicySettingOrm.Query(Sqlite).OrderBy(p => "not a column")); + Assert.Contains("not a column", ex.Message, StringComparison.Ordinal); + } +} + +/// +/// The integer a DateTimeOffset becomes on sqlite. The model puts EF's +/// DateTimeOffsetToBinaryConverter on every timestamp column, so that +/// encoding is the storage contract of every row this application has written; +/// the generated layer reproduces it, and this test is what makes "reproduces" +/// mean something rather than "looks plausible". It also records the resolution: +/// the encoding divides the ticks by 1000, so a round trip through the column +/// drops the sub-microsecond digits. That is EF's behaviour, not a loss added +/// here — and it is asserted, so it cannot become a surprise later. +/// +public sealed class SqliteTimestampEncodingTests +{ + private static readonly DateTimeOffset[] Instants = + [ + new DateTimeOffset(2026, 10, 7, 12, 34, 56, TimeSpan.FromHours(3)), + new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(123456), + new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.FromHours(-5)), + new DateTimeOffset(2024, 2, 29, 23, 59, 59, TimeSpan.FromMinutes(330)), + DateTimeOffset.MinValue, + ]; + + [Fact] + public void The_encoding_this_layer_writes_is_the_one_ef_writes() + { + var efEncodes = new DateTimeOffsetToBinaryConverter().ConvertToProviderExpression.Compile(); + + foreach (var instant in Instants) + Assert.Equal(efEncodes(instant), Convert.ToInt64(SqliteDialect.Instance.WriteDateTimeOffset(instant))); + } + + [Fact] + public void What_ef_writes_this_layer_reads_back() + { + var converter = new DateTimeOffsetToBinaryConverter(); + var efEncodes = converter.ConvertToProviderExpression.Compile(); + + foreach (var instant in Instants) + { + var stored = efEncodes(instant); + var efRead = Assert.IsAssignableFrom(converter.ConvertFromProvider(stored)); + Assert.Equal(efRead, ReadFromStored(stored)); + } + } + + [Fact] + public void The_column_has_microsecond_resolution_and_says_so() + { + var instant = new DateTimeOffset(2026, 5, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(1234567); + var read = ReadFromStored(Convert.ToInt64(SqliteDialect.Instance.WriteDateTimeOffset(instant))); + + Assert.Equal(new DateTimeOffset(2026, 5, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(1234000), read); + Assert.NotEqual(instant.Ticks, read.Ticks); + } + + /// Reads the integer the way the sqlite dialect does, without a + /// reader. The dialect's own reader path is exercised end to end by the + /// integration suite against a real database. + private static DateTimeOffset ReadFromStored(long stored) + { + var offsetMinutes = (int)(stored & 2047); + if (offsetMinutes >= 1024) offsetMinutes -= 2048; + return new DateTimeOffset((stored >> 11) * 1000, TimeSpan.FromMinutes(offsetMinutes)); + } +} diff --git a/dotnet/OpenWaf.slnx b/dotnet/OpenWaf.slnx index e65dee7..e9f1b85 100644 --- a/dotnet/OpenWaf.slnx +++ b/dotnet/OpenWaf.slnx @@ -1,6 +1,8 @@ + + diff --git a/scripts/aot-probe.sh b/scripts/aot-probe.sh index d90d30a..6e15ace 100755 --- a/scripts/aot-probe.sh +++ b/scripts/aot-probe.sh @@ -44,8 +44,12 @@ printf '\n=== publish NativeAOT (%s) ===\n' "$RUNTIME" # schema step still calls three design-time APIs. Those are recorded, not hidden — # the counts are printed below from the same log. AOT_LOG=/tmp/openwaf-aot-publish.log +# OpenWafAot, not PublishAot: the latter as a command-line property is global, and +# it then reaches the referenced Roslyn analyzer (netstandard2.0) and the publish +# dies with NETSDK1207. OpenWaf.Edge.csproj turns this switch into PublishAot for +# itself only. (cd dotnet && dotnet publish OpenWaf.Edge/OpenWaf.Edge.csproj -c Release -r "$RUNTIME" \ - -p:PublishAot=true -p:InvariantGlobalization=true -p:DebugType=none \ + -p:OpenWafAot=true \ -p:OpenWafCompiledModel=true -p:NoWarn=IL2026%3BIL3050 \ -p:IlcTreatWarningsAsErrors=false) >"$AOT_LOG" 2>&1 publish_status=$?