Files
openwaf/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs
T
Pavlo Ratushnyi 565da4fab5 Add EF Core migrations; make schema strategy explicit
- dotnet-ef 10.0.0 as a local tool manifest, InitialCreate generated against
  PostgreSQL (the provider a real deployment runs) via a design-time factory,
  so migrations never need to boot the edge
- EdgeStateWarmer picks the strategy: migrate for postgres, ensurecreated for
  the sqlite default, none when the operator owns the schema. A migration set
  is provider-shaped SQL and is not applied across providers
- README documents the schema story

Regressions checked: 36 unit + 14 integration tests, scripts/smoke.sh 19/19.
2026-10-01 02:32:12 +02:00

57 lines
2.4 KiB
C#

using Microsoft.EntityFrameworkCore;
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,
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.
var isSqlite = string.Equals(
Environment.GetEnvironmentVariable("Database__Provider") ?? "sqlite",
"sqlite", StringComparison.OrdinalIgnoreCase);
var strategy = Environment.GetEnvironmentVariable("OPENWAF_SCHEMA")
?? (isSqlite ? "ensurecreated" : "migrate");
switch (strategy.ToLowerInvariant())
{
case "ensurecreated":
await db.Database.EnsureCreatedAsync(cancellationToken);
break;
case "migrate":
await db.Database.MigrateAsync(cancellationToken);
break;
default:
log.LogInformation("edge: schema management left to the operator (OPENWAF_SCHEMA={Strategy})", strategy);
break;
}
await state.WarmUpAsync(cancellationToken);
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);
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}