Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs
T
Pavlo Ratushnyi 8ee6570458 the streak map can live in the database, so N edges mature one streak
The multi-instance research measured the gap rather than guessing it: four
refusals from one address, two per edge, at a threshold of 3, produced no ban
anywhere, because the block list was shared through the database and the streak
map was not (research/2026-10-01-multi-instance/, D1). OpenWaf:Policy:
SharedStreaks=true moves the counters onto a row in source_streaks; the default
stays the in-process map, because that is the deployment that loses nothing.

The rules were extracted into StreakRules.Apply and both stores call it — the
in-process map against a StreakState, the shared one against a row. A second
copy of the streak semantics would put the drift back where this removes it.
Version is a concurrency token, so two edges writing one source produce a retry
against the winner's row rather than a silently dropped refusal; a clean answer
on any edge ends the run on every edge, in one statement. The rows age out on
the same ObservationRetentionDays window as observations. Both surfaces say
which store answered: /admin-api/streaks scope is this-process or
shared-database, /admin-api/state answers streakScope, and the console's streak
note stops claiming "this edge process only" when it is not true.

Found by running it for real rather than in-process: two edge processes on one
SQLite file both create the schema on startup, and the loser of that race died
in StartAsync with 'table "allow_entries" already exists' — hosting failed to
start and the process never listened. The schema step now re-checks existence
and continues, because what has to be true is that the schema exists, not that
this process made it.

Measured on this tree: build 0 warnings / 0 errors, unit 132/132, integration
191/191 in 32 s (6 new, two real edge instances on one SQLite file each), smoke
28/0, console 78 assertions 0 failed. Out of process, two edge binaries on one
file at a 5 s TTL: A answered 404, 404; B answered 404 on the third refusal and
403 after it; both edges then reported consecutiveRefusals: 3 with
scope: shared-database, and A started enforcing 4 s later. Before the schema fix
the second process aborted on startup, which is how that fix was found.
2026-10-04 17:13:21 +02:00

149 lines
6.6 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Persists the in-memory streak state on a timer. This is the write
/// amplification protection the reference repo already paid for: a scanner
/// hammering thousands of paths a second must not generate matching writes a
/// second, so the tracker stays in memory and at most one durable upsert per
/// source per <c>ObservationWriteInterval</c> leaves this loop.
/// </summary>
public sealed class ObservationWriter : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly IStreakTracker _tracker;
private readonly EdgePolicyProvider _policy;
private readonly DurabilityHealth _health;
private readonly ILogger<ObservationWriter> _log;
private readonly TimeSpan _flushInterval = TimeSpan.FromSeconds(15);
private readonly Dictionary<string, DateTimeOffset> _lastWrittenAt = new(StringComparer.Ordinal);
public ObservationWriter(
IServiceScopeFactory scopeFactory,
IStreakTracker tracker,
EdgePolicyProvider policy,
DurabilityHealth health,
ILogger<ObservationWriter> log)
{
_scopeFactory = scopeFactory;
_tracker = tracker;
_policy = policy;
_health = health;
_log = log;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try { await Task.Delay(_flushInterval, stoppingToken); }
catch (TaskCanceledException) { return; }
await FlushAsync(stoppingToken);
}
await FlushAsync(CancellationToken.None);
}
internal async Task<int> FlushAsync(CancellationToken ct)
{
var policy = _policy.Current;
var now = DateTimeOffset.UtcNow;
var snapshots = _tracker.Snapshot(now, policy);
if (snapshots.Count == 0) return 0;
// The write-amplification bound protects against load, not against
// retries. While this pillar has an outstanding failure, every flush
// re-attempts every tracked source: the rows the failed flush was
// carrying would otherwise be lost until each source happened to be due
// again a full interval later, and the counter would stop being a live
// signal. The flush rate is unchanged (one per 15 s) and the source count
// is already capped by the LRU bound on the map, so retrying cannot turn
// into write amplification.
var retrying = _health.Get(DurabilityHealth.Observations).Failures > 0;
var due = new List<StreakSnapshot>();
foreach (var s in snapshots)
{
if (!retrying
&& _lastWrittenAt.TryGetValue(s.SourceKey, out var last) && now - last < policy.ObservationWriteInterval)
continue;
due.Add(s);
_lastWrittenAt[s.SourceKey] = now;
}
if (_lastWrittenAt.Count > policy.MaxTrackedSources)
{
foreach (var key in _lastWrittenAt.Where(kv => now - kv.Value > policy.StateIdleTtl).Select(kv => kv.Key).ToList())
_lastWrittenAt.Remove(key);
}
if (due.Count == 0) return 0;
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var keys = due.Select(d => d.SourceKey).ToList();
var existing = await db.Observations.Where(o => keys.Contains(o.SourceKey)).ToListAsync(ct);
var byKey = existing.ToDictionary(o => o.SourceKey, StringComparer.Ordinal);
foreach (var s in due)
{
if (byKey.TryGetValue(s.SourceKey, out var row))
{
row.LastSeenAt = s.LastSeenAt;
row.MaxConsecutiveRefusals = Math.Max(row.MaxConsecutiveRefusals, s.MaxConsecutiveRefusals);
row.TotalRefusals = Math.Max(row.TotalRefusals, s.TotalRefusals);
row.TotalServerErrorStreak = Math.Max(row.TotalServerErrorStreak, s.MaxConsecutiveServerErrors);
row.LastStatusCode = s.LastStatusCode ?? row.LastStatusCode;
row.LastPath = s.LastPath ?? row.LastPath;
row.LastUserAgent = s.LastUserAgent ?? row.LastUserAgent;
row.LastCountryCode = s.LastCountryCode ?? row.LastCountryCode;
row.LastCity = s.LastCity ?? row.LastCity;
row.LastRegion = s.LastRegion ?? row.LastRegion;
}
else
{
db.Observations.Add(new SourceObservation
{
SourceKey = s.SourceKey,
FirstSeenAt = s.LastSeenAt,
LastSeenAt = s.LastSeenAt,
MaxConsecutiveRefusals = s.MaxConsecutiveRefusals,
TotalRefusals = s.TotalRefusals,
TotalServerErrorStreak = s.MaxConsecutiveServerErrors,
LastStatusCode = s.LastStatusCode,
LastPath = s.LastPath,
LastUserAgent = s.LastUserAgent,
LastCountryCode = s.LastCountryCode,
LastCity = s.LastCity,
LastRegion = s.LastRegion
});
}
}
await db.SaveChangesAsync(ct);
_health.RecordSuccess(DurabilityHealth.Observations, due.Count);
return due.Count;
}
catch (Exception ex)
{
// The writer must survive: losing observations is better than
// taking the host down over a transient database error. What it may
// not do is survive quietly. Measured on the shipped image with the
// write path aborted by SQLite triggers: three new sources never
// reached source_observations, /admin-api/observations kept
// answering 200 with the same X-Total-Count as before the break,
// /readyz said "ready", and the only trace was this log line. The
// rows are not recoverable later — the streak history the operator
// reasons about is simply missing them.
_health.RecordFailure(DurabilityHealth.Observations, ex, due.Count);
_log.LogWarning(ex, "ObservationWriter: flush failed, {Count} entries dropped.", due.Count);
return 0;
}
}
}