Files
openwaf/dotnet/OpenWaf.Data/OrmContext.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

137 lines
6.1 KiB
C#

#nullable enable
using System;
using System.Data.Common;
namespace OpenWaf.Data;
/// <summary>
/// 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
/// <c>MicroOrm.OrmContext</c> (<c>~/work/tskr/app/lib/MicroOrmRuntime</c>), which
/// keeps the runtime driver-agnostic and supplies Npgsql at composition; here the
/// drivers are sqlite and Npgsql, chosen by the same <c>Database:Provider</c>
/// switch <c>Program.cs</c> already uses for EF.
/// </summary>
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));
}
}
/// <summary>
/// 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
/// <see cref="DateTimeOffset"/> as a binary integer on sqlite and as native
/// <c>timestamptz</c> 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
/// <c>OpenWafDbContext.StoreTimestampsAsIntegersOnSqlite</c>). A generated
/// materializer therefore cannot know how to read the column; the dialect does.
/// </summary>
public interface ISqlDialect
{
string Quote(string identifier);
/// <summary>The placeholder for the parameter at this ordinal, 0-based.</summary>
string Param(int index);
/// <summary>The paging tail, or empty when neither limit nor offset is set.</summary>
string Page(int? limit, int? offset);
string CountAllExpression { get; }
string PingStatement { get; }
/// <summary>How this provider stores a <see cref="DateTimeOffset"/> column.</summary>
DateTimeOffset ReadDateTimeOffset(DbDataReader reader, int ordinal);
/// <summary>The value to hand the driver for a DateTimeOffset parameter.</summary>
object WriteDateTimeOffset(DateTimeOffset value);
}
/// <summary>sqlite, the provider the shipped image runs.</summary>
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";
/// <summary>
/// The integer EF writes for this column, read back. The model puts a
/// <see cref="DateTimeOffset"/> through EF's <c>DateTimeOffsetToBinaryConverter</c>
/// 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 <c>(localTicks / 1000) * 2048 + (offsetMinutes &amp; 2047)</c>
/// and asserted equal to EF's own converter over a spread of instants
/// (positive, negative and half-hour offsets, and DateTime.MinValue) in
/// <c>SqliteTimestampEncodingTests</c>, 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.
/// </summary>
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);
}
/// <summary>PostgreSQL, the provider a real deployment runs (migrations are its schema of record).</summary>
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<DateTimeOffset>(ordinal).GetAwaiter().GetResult();
public object WriteDateTimeOffset(DateTimeOffset value) => value;
}