The read side got its counters last cycle; the write side was still catching everything, logging one line and keeping the process alive. A failed write is worse than a failed read - the row never existed and no later request brings it back - and the surface hid it better. Measured on the shipped image with SQLite triggers aborting every INSERT/UPDATE on source_observations and edge_alerts while reads kept working: three new sources refused and a six-request 5xx storm later, GET /admin-api/observations answered 200 with the same X-Total-Count it had before the break (46), GET /admin-api/alerts still showed its one row, /healthz and /readyz were 200, /admin-api/state had no write-side field at all, and the log carried "flush failed, 4 entries dropped" plus two "could not persist". DurabilityHealth counts each writer separately; /state reports observationWriteFailures/observationsLost/observationLastWriteError, alertWriteFailures/alertsLost and retentionPruneFailures; /readyz answers 503 naming the pillar, the rows lost and the innermost error rather than EF's wrapper. A counter clears only on a successful write of its own pillar, and retention is reported without being a readiness failure - stated in code, with the reason. Teeth: WriteFailureVisibilityTests (5) - 5 failed / 0 passed before the fix. Gates: compose-smoke 53 -> 63 (blocks writes with triggers, asserts the unchanged X-Total-Count as the lie, and heals per pillar), smoke.sh 25 -> 28, console-check 53 -> 57.
139 lines
6.0 KiB
C#
139 lines
6.0 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 StreakTracker _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,
|
|
StreakTracker 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;
|
|
|
|
var due = new List<StreakSnapshot>();
|
|
foreach (var s in snapshots)
|
|
{
|
|
if (_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;
|
|
}
|
|
}
|
|
}
|