feat(health): SiteAuditBacklog metric (count + age + bytes) (#23 M6)

This commit is contained in:
Joseph Doherty
2026-05-20 19:02:01 -04:00
parent 75b060e0a8
commit e93f655ce4
11 changed files with 511 additions and 2 deletions

View File

@@ -0,0 +1,136 @@
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ScadaLink.AuditLog.Site;
using ScadaLink.Commons.Entities.Audit;
using ScadaLink.Commons.Types.Enums;
namespace ScadaLink.AuditLog.Tests.Site;
/// <summary>
/// Bundle E (M6-T6) tests for <see cref="SqliteAuditWriter.GetBacklogStatsAsync"/>.
/// Exercises the health-metric surface that <c>SiteAuditBacklogReporter</c>
/// polls every 30 s and pushes onto the site health report as
/// <c>SiteAuditBacklog</c>.
/// </summary>
public class SqliteAuditWriterBacklogStatsTests : IDisposable
{
private readonly string _dbPath;
public SqliteAuditWriterBacklogStatsTests()
{
// OnDiskBytes assertions only make sense against a real file — the
// shared-cache in-memory mode returns 0 for the file size, so this
// suite is opinionated about file-backed storage. Tests in
// SqliteAuditWriterWriteTests use in-memory for performance reasons.
_dbPath = Path.Combine(Path.GetTempPath(),
$"audit-backlog-stats-{Guid.NewGuid():N}.db");
}
public void Dispose()
{
if (File.Exists(_dbPath))
{
try { File.Delete(_dbPath); } catch { /* test cleanup best-effort */ }
}
}
private SqliteAuditWriter CreateWriter()
{
var options = new SqliteAuditWriterOptions { DatabasePath = _dbPath };
return new SqliteAuditWriter(
Options.Create(options),
NullLogger<SqliteAuditWriter>.Instance);
}
private static AuditEvent NewEvent(DateTime? occurredAtUtc = null) => new()
{
EventId = Guid.NewGuid(),
OccurredAtUtc = occurredAtUtc ?? DateTime.UtcNow,
Channel = AuditChannel.ApiOutbound,
Kind = AuditKind.ApiCall,
Status = AuditStatus.Delivered,
PayloadTruncated = false,
};
[Fact]
public async Task EmptyDb_Returns_Zero_Null_AndZeroBytes()
{
// No file exists yet — the writer ctor creates one but no rows are
// inserted; the snapshot should report a clean queue. OnDiskBytes is
// allowed to be zero (fresh ftruncate) OR small (page header) — the
// contract only requires non-negative; we assert >= 0 and exercise
// the pending fields strictly.
await using var writer = CreateWriter();
var snapshot = await writer.GetBacklogStatsAsync();
Assert.Equal(0, snapshot.PendingCount);
Assert.Null(snapshot.OldestPendingUtc);
Assert.True(snapshot.OnDiskBytes >= 0,
$"OnDiskBytes must be non-negative, got {snapshot.OnDiskBytes}");
}
[Fact]
public async Task Pending_5_Returns_5()
{
await using var writer = CreateWriter();
for (var i = 0; i < 5; i++)
{
await writer.WriteAsync(NewEvent());
}
var snapshot = await writer.GetBacklogStatsAsync();
Assert.Equal(5, snapshot.PendingCount);
}
[Fact]
public async Task OldestPending_Is_Earliest_OccurredAtUtc()
{
await using var writer = CreateWriter();
var t1 = new DateTime(2026, 5, 20, 10, 0, 0, DateTimeKind.Utc);
var t2 = new DateTime(2026, 5, 20, 10, 1, 0, DateTimeKind.Utc);
var t3 = new DateTime(2026, 5, 20, 10, 2, 0, DateTimeKind.Utc);
// Insert out of order so the snapshot is not "the last write" by
// accident — the OldestPendingUtc must come from a column-min, not
// an insertion-order proxy.
await writer.WriteAsync(NewEvent(t2));
await writer.WriteAsync(NewEvent(t1));
await writer.WriteAsync(NewEvent(t3));
var snapshot = await writer.GetBacklogStatsAsync();
Assert.Equal(3, snapshot.PendingCount);
Assert.NotNull(snapshot.OldestPendingUtc);
// The DB round-trips OccurredAtUtc through the "o" format which
// preserves Kind=Utc — assert tick-equality.
Assert.Equal(t1, snapshot.OldestPendingUtc!.Value);
}
[Fact]
public async Task OnDiskBytes_ReturnsFileSize()
{
await using var writer = CreateWriter();
// Insert enough rows to grow the file past the empty schema baseline.
for (var i = 0; i < 100; i++)
{
await writer.WriteAsync(NewEvent());
}
var snapshot = await writer.GetBacklogStatsAsync();
// The exact size depends on SQLite page allocation, but a file-backed
// db with 100 inserted rows MUST be larger than the empty schema
// (a few pages, ~4 KB). The implementation should return the
// FileInfo.Length value verbatim.
Assert.True(File.Exists(_dbPath), $"DB file should exist at {_dbPath}");
var expected = new FileInfo(_dbPath).Length;
Assert.Equal(expected, snapshot.OnDiskBytes);
Assert.True(snapshot.OnDiskBytes > 0,
$"after 100 inserts OnDiskBytes must be > 0, got {snapshot.OnDiskBytes}");
}
}

View File

@@ -0,0 +1,73 @@
using ScadaLink.Commons.Types;
namespace ScadaLink.HealthMonitoring.Tests;
/// <summary>
/// Bundle E (M6-T6) regression coverage. The site-side audit-log SQLite writer
/// exposes a backlog snapshot (<c>SiteAuditBacklogSnapshot</c>) via the
/// <c>ISiteAuditQueue.GetBacklogStatsAsync</c> surface. A periodic
/// <c>SiteAuditBacklogReporter</c> hosted service polls that snapshot and
/// pushes it into the collector via <see cref="ISiteHealthCollector.UpdateSiteAuditBacklog"/>
/// so the next <see cref="ISiteHealthCollector.CollectReport"/> includes it in
/// the report payload as <c>SiteAuditBacklog</c>. Unlike the
/// SiteAuditWriteFailures / AuditRedactionFailure interval counters, the
/// backlog snapshot is not reset on collect — the field carries forward
/// whatever the most recent refresh pushed in.
/// </summary>
public class SiteAuditBacklogMetricTests
{
private readonly SiteHealthCollector _collector = new();
[Fact]
public void Update_Then_CollectReport_IncludesBacklog()
{
var snapshot = new SiteAuditBacklogSnapshot(
PendingCount: 42,
OldestPendingUtc: new DateTime(2026, 5, 20, 10, 0, 0, DateTimeKind.Utc),
OnDiskBytes: 1234567);
_collector.UpdateSiteAuditBacklog(snapshot);
var report = _collector.CollectReport("site-1");
Assert.Equal(snapshot, report.SiteAuditBacklog);
}
[Fact]
public void Report_Payload_Includes_SiteAuditBacklog_AsNullByDefault()
{
// No refresh has been pushed yet — the report carries null so the
// central UI can distinguish "no data yet" from "queue empty".
var report = _collector.CollectReport("site-1");
Assert.Null(report.SiteAuditBacklog);
}
[Fact]
public void CollectReport_DoesNotReset_SiteAuditBacklog()
{
// Backlog snapshot is a point-in-time reading, not a per-interval
// counter — successive CollectReport calls before the next
// SiteAuditBacklogReporter tick MUST keep returning the same snapshot
// so a slow refresh cadence doesn't blank the central dashboard.
var snapshot = new SiteAuditBacklogSnapshot(
PendingCount: 7,
OldestPendingUtc: null,
OnDiskBytes: 8192);
_collector.UpdateSiteAuditBacklog(snapshot);
var first = _collector.CollectReport("site-1");
var second = _collector.CollectReport("site-1");
Assert.Equal(snapshot, first.SiteAuditBacklog);
Assert.Equal(snapshot, second.SiteAuditBacklog);
}
[Fact]
public void Update_With_Null_Throws_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(
() => _collector.UpdateSiteAuditBacklog(null!));
}
}

View File

@@ -71,6 +71,7 @@ public class DeploymentManagerRedeployTests : TestKit, IDisposable
public void IncrementDeadLetter() { }
public void IncrementSiteAuditWriteFailures() { }
public void IncrementAuditRedactionFailure() { }
public void UpdateSiteAuditBacklog(ScadaLink.Commons.Types.SiteAuditBacklogSnapshot snapshot) { }
public void UpdateConnectionHealth(string connectionName, ConnectionHealth health) { }
public void RemoveConnection(string connectionName) { }
public void UpdateTagResolution(string connectionName, int totalSubscribed, int successfullyResolved) { }