Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/HealthReportSenderTests.cs
T

582 lines
24 KiB
C#

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Health;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.StoreAndForward;
using ZB.MOM.WW.ScadaBridge.TestSupport;
namespace ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests;
public class HealthReportSenderTests
{
private class FakeTransport : IHealthReportTransport
{
/// <summary>Gets the reports captured by <c>SendAsync</c>, in send order.</summary>
public List<SiteHealthReport> SentReports { get; } = [];
/// <inheritdoc />
public Task SendAsync(SiteHealthReport report, CancellationToken cancellationToken)
{
SentReports.Add(report);
return Task.CompletedTask;
}
}
private class FakeSiteIdentityProvider : ISiteIdentityProvider
{
/// <inheritdoc />
public string SiteId { get; set; } = "test-site";
}
/// <summary>
/// Captures emitted log entries so tests can assert that non-fatal failures
/// are surfaced rather than silently swallowed.
/// </summary>
private sealed class CapturingLogger<T> : ILogger<T>
{
public sealed record Entry(LogLevel Level, string Message, Exception? Exception);
/// <summary>Gets the log entries captured so far.</summary>
public List<Entry> Entries { get; } = [];
/// <summary>Returns no scope; the fake logger does not track scopes.</summary>
/// <typeparam name="TState">The type of the scope state.</typeparam>
/// <param name="state">The scope state, ignored.</param>
/// <returns>Always null or a no-op scope.</returns>
public IDisposable BeginScope<TState>(TState state) where TState : notnull => NullScope.Instance;
/// <summary>Reports every log level as enabled.</summary>
/// <param name="logLevel">The log level being queried.</param>
/// <returns>Always true.</returns>
public bool IsEnabled(LogLevel logLevel) => true;
/// <summary>Records the log entry for later assertions.</summary>
/// <typeparam name="TState">The type of the log state.</typeparam>
/// <param name="logLevel">The severity of the entry.</param>
/// <param name="eventId">The event identifier.</param>
/// <param name="state">The log state.</param>
/// <param name="exception">The associated exception, if any.</param>
/// <param name="formatter">Formats the state and exception into the message.</param>
public void Log<TState>(
LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
{
lock (Entries)
{
Entries.Add(new Entry(logLevel, formatter(state, exception), exception));
}
}
private sealed class NullScope : IDisposable
{
public static readonly NullScope Instance = new();
/// <summary>Releases the resources held by this test class.</summary>
public void Dispose() { }
}
}
/// <summary>An <see cref="IClusterNodeProvider"/> whose query always throws.</summary>
private sealed class ThrowingClusterNodeProvider : IClusterNodeProvider
{
/// <inheritdoc />
public bool SelfIsPrimary => true;
/// <inheritdoc />
public IReadOnlyList<NodeStatus> GetClusterNodes() =>
throw new InvalidOperationException("cluster query failed");
}
/// <summary>Verifies that successive reports are sent with monotonically increasing sequence numbers.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task SendsReportsWithMonotonicSequenceNumbers()
{
var transport = new FakeTransport();
var collector = new SiteHealthCollector();
collector.SetActiveNode(true);
var options = Options.Create(new HealthMonitoringOptions
{
ReportInterval = TimeSpan.FromMilliseconds(50)
});
var sender = new HealthReportSender(
collector,
transport,
options,
NullLogger<HealthReportSender>.Instance,
new FakeSiteIdentityProvider { SiteId = "site-A" });
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
try
{
await sender.StartAsync(cts.Token);
await Task.Delay(280, CancellationToken.None);
await sender.StopAsync(CancellationToken.None);
}
catch (OperationCanceledException) { }
// Should have sent several reports
Assert.True(transport.SentReports.Count >= 2,
$"Expected at least 2 reports, got {transport.SentReports.Count}");
// Verify strictly-monotonic sequence numbers and matching site id
for (int i = 0; i < transport.SentReports.Count; i++)
{
if (i > 0)
{
Assert.True(
transport.SentReports[i].SequenceNumber > transport.SentReports[i - 1].SequenceNumber,
$"Sequence numbers not strictly increasing at index {i}");
}
Assert.Equal("site-A", transport.SentReports[i].SiteId);
}
}
/// <summary>Verifies that the first report sequence number exceeds the startup Unix time in milliseconds.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task FirstReportSequenceExceedsStartupUnixMs()
{
// Reports are seeded with Unix-ms at construction so a freshly-active
// node always sorts after the prior active. Verify the first emitted
// sequence is at least the startup epoch.
var transport = new FakeTransport();
var collector = new SiteHealthCollector();
collector.SetActiveNode(true);
var options = Options.Create(new HealthMonitoringOptions
{
ReportInterval = TimeSpan.FromMilliseconds(50)
});
var beforeCtor = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var sender = new HealthReportSender(
collector,
transport,
options,
NullLogger<HealthReportSender>.Instance,
new FakeSiteIdentityProvider());
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(150));
try
{
await sender.StartAsync(cts.Token);
await Task.Delay(120, CancellationToken.None);
await sender.StopAsync(CancellationToken.None);
}
catch (OperationCanceledException) { }
Assert.True(transport.SentReports.Count >= 1);
Assert.True(
transport.SentReports[0].SequenceNumber >= beforeCtor,
$"First sequence {transport.SentReports[0].SequenceNumber} should be >= startup epoch {beforeCtor}");
}
/// <summary>Verifies that each report carries a UTC timestamp.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReportsIncludeUtcTimestamp()
{
var transport = new FakeTransport();
var collector = new SiteHealthCollector();
collector.SetActiveNode(true);
var options = Options.Create(new HealthMonitoringOptions
{
ReportInterval = TimeSpan.FromMilliseconds(50)
});
var sender = new HealthReportSender(
collector,
transport,
options,
NullLogger<HealthReportSender>.Instance,
new FakeSiteIdentityProvider());
var before = DateTimeOffset.UtcNow;
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(150));
try
{
await sender.StartAsync(cts.Token);
await Task.Delay(120, CancellationToken.None);
await sender.StopAsync(CancellationToken.None);
}
catch (OperationCanceledException) { }
var after = DateTimeOffset.UtcNow;
Assert.True(transport.SentReports.Count >= 1);
foreach (var report in transport.SentReports)
{
Assert.InRange(report.ReportTimestamp, before, after);
Assert.Equal(TimeSpan.Zero, report.ReportTimestamp.Offset);
}
}
/// <summary>
/// Regression: the documented "store-and-forward buffer
/// depth" metric (pending messages by category) must actually be populated in
/// the emitted report. Previously SetStoreAndForwardDepths had no callers, so
/// StoreAndForwardBufferDepths was always empty. The sender must query the S&amp;F
/// engine's per-category depth API and include it alongside the parked count.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReportsIncludeStoreAndForwardBufferDepthsFromStorage()
{
// LocalDb has no in-memory mode, so the store runs over a real temp file.
var localDb = TestLocalDb.CreateTemp("HealthSfDepth");
try
{
var storage = new StoreAndForwardStorage(localDb.Db, NullLogger<StoreAndForwardStorage>.Instance);
await storage.InitializeAsync();
// Two pending ExternalSystem messages and one pending Notification message.
await storage.EnqueueAsync(MakePendingMessage("m1", StoreAndForwardCategory.ExternalSystem));
await storage.EnqueueAsync(MakePendingMessage("m2", StoreAndForwardCategory.ExternalSystem));
await storage.EnqueueAsync(MakePendingMessage("m3", StoreAndForwardCategory.Notification));
var transport = new FakeTransport();
var collector = new SiteHealthCollector();
collector.SetActiveNode(true);
var options = Options.Create(new HealthMonitoringOptions
{
ReportInterval = TimeSpan.FromMilliseconds(50)
});
var sender = new HealthReportSender(
collector,
transport,
options,
NullLogger<HealthReportSender>.Instance,
new FakeSiteIdentityProvider(),
sfStorage: storage);
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
try
{
await sender.StartAsync(cts.Token);
await Task.Delay(250, CancellationToken.None);
await sender.StopAsync(CancellationToken.None);
}
catch (OperationCanceledException) { }
Assert.True(transport.SentReports.Count >= 1);
var depths = transport.SentReports[^1].StoreAndForwardBufferDepths;
Assert.Equal(2, depths[nameof(StoreAndForwardCategory.ExternalSystem)]);
Assert.Equal(1, depths[nameof(StoreAndForwardCategory.Notification)]);
Assert.False(depths.ContainsKey(nameof(StoreAndForwardCategory.CachedDbWrite)));
}
finally
{
// The master connection anchors the WAL — dispose before deleting.
localDb.Dispose();
TestLocalDb.DeleteFiles(localDb.Path);
}
}
private static StoreAndForwardMessage MakePendingMessage(string id, StoreAndForwardCategory category) =>
new()
{
Id = id,
Category = category,
Target = "target",
PayloadJson = "{}",
RetryCount = 0,
MaxRetries = 50,
RetryIntervalMs = 30_000,
CreatedAt = DateTimeOffset.UtcNow,
Status = StoreAndForwardMessageStatus.Pending
};
/// <summary>Verifies that the initial sequence number is seeded from the current Unix time in milliseconds.</summary>
[Fact]
public void InitialSequenceNumberSeededWithUnixMs()
{
var transport = new FakeTransport();
var collector = new SiteHealthCollector();
var options = Options.Create(new HealthMonitoringOptions());
var beforeCtor = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var sender = new HealthReportSender(
collector,
transport,
options,
NullLogger<HealthReportSender>.Instance,
new FakeSiteIdentityProvider());
var afterCtor = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
Assert.InRange(sender.CurrentSequenceNumber, beforeCtor, afterCtor);
}
/// <summary>
/// Regression: a failure refreshing cluster nodes is
/// non-fatal (the report still ships) but must no longer be swallowed by a
/// bare <c>catch {}</c> — it must be logged as a warning with the exception so
/// persistent degradation is diagnosable.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ClusterNodeRefreshFailure_IsLoggedNotSwallowed()
{
var transport = new FakeTransport();
var collector = new SiteHealthCollector();
collector.SetActiveNode(true);
var logger = new CapturingLogger<HealthReportSender>();
var options = Options.Create(new HealthMonitoringOptions
{
ReportInterval = TimeSpan.FromMilliseconds(50)
});
var sender = new HealthReportSender(
collector,
transport,
options,
logger,
new FakeSiteIdentityProvider(),
clusterNodeProvider: new ThrowingClusterNodeProvider());
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
try
{
await sender.StartAsync(cts.Token);
await Task.Delay(250, CancellationToken.None);
await sender.StopAsync(CancellationToken.None);
}
catch (OperationCanceledException) { }
// The report loop continues despite the failure...
Assert.NotEmpty(transport.SentReports);
// ...but the failure is surfaced as a warning carrying the exception.
CapturingLogger<HealthReportSender>.Entry[] warnings;
lock (logger.Entries)
{
warnings = logger.Entries
.Where(e => e.Level == LogLevel.Warning && e.Exception is InvalidOperationException)
.ToArray();
}
Assert.NotEmpty(warnings);
Assert.Contains(warnings, w => w.Message.Contains("cluster nodes", StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Regression: when the transport's <c>Send</c> throws,
/// the per-interval counters that <see cref="SiteHealthCollector.CollectReport"/>
/// just drained via <c>Interlocked.Exchange</c> must be restored back into the
/// collector so they roll forward into the next interval rather than being
/// silently lost. Before the fix, a transport failure left the counts in the
/// un-sent report only, and the next successful report shipped with the
/// counters at zero.
/// </summary>
/// <remarks>
/// Also covers <c>ScriptRunShedCount</c>, which is drained
/// by <c>CollectReport</c> in the exact same way as the five counters above, but
/// <c>AddIntervalCounters</c> used to take only those five — a failed send
/// destructively lost the shed count forever. <c>DetachedScriptThreads</c> and
/// <c>SiteStreamAlarmDropCount</c> are deliberately NOT exercised here: they are
/// point-in-time gauges (set via <c>Interlocked.CompareExchange</c>/<c>Read</c>,
/// never zeroed by <c>CollectReport</c>), so a failed send loses nothing for them
/// to restore.
/// </remarks>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task SendFailure_PreservesIntervalCountersForNextReport()
{
var transport = new FailingThenSucceedingTransport();
var collector = new SiteHealthCollector();
collector.SetActiveNode(true);
// Pre-populate every per-interval counter so the restore path on each
// field is exercised — script error, alarm error, dead letter, site
// audit write failure, audit redaction failure, script run shed.
collector.IncrementScriptError();
collector.IncrementScriptError();
collector.IncrementAlarmError();
collector.IncrementDeadLetter();
collector.IncrementDeadLetter();
collector.IncrementDeadLetter();
collector.IncrementSiteAuditWriteFailures();
collector.IncrementAuditRedactionFailure();
collector.IncrementAuditRedactionFailure();
collector.IncrementScriptRunShed();
collector.IncrementScriptRunShed();
collector.IncrementScriptRunShed();
collector.IncrementScriptRunShed();
var options = Options.Create(new HealthMonitoringOptions
{
ReportInterval = TimeSpan.FromMilliseconds(50)
});
var sender = new HealthReportSender(
collector,
transport,
options,
NullLogger<HealthReportSender>.Instance,
new FakeSiteIdentityProvider());
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
try
{
await sender.StartAsync(cts.Token);
await Task.Delay(450, CancellationToken.None);
await sender.StopAsync(CancellationToken.None);
}
catch (OperationCanceledException) { }
// The first interval's Send threw, then later intervals succeeded. The
// first successful report must include the previously-failed interval's
// accumulated counts.
Assert.NotEmpty(transport.SentReports);
var firstSuccess = transport.SentReports[0];
Assert.Equal(2, firstSuccess.ScriptErrorCount);
Assert.Equal(1, firstSuccess.AlarmEvaluationErrorCount);
Assert.Equal(3, firstSuccess.DeadLetterCount);
Assert.Equal(1, firstSuccess.SiteAuditWriteFailures);
Assert.Equal(2, firstSuccess.AuditRedactionFailure);
Assert.Equal(4, firstSuccess.ScriptRunShedCount);
}
/// <summary>
/// <see cref="IHealthReportTransport"/> that throws on the first
/// <c>Send</c> call (and only the first), then succeeds. Used by
/// <see cref="SendFailure_PreservesIntervalCountersForNextReport"/> to
/// verify the restore-on-failure path.
/// </summary>
private sealed class FailingThenSucceedingTransport : IHealthReportTransport
{
private int _callCount;
/// <summary>Gets the reports captured by <c>SendAsync</c>, in send order.</summary>
public List<SiteHealthReport> SentReports { get; } = [];
/// <inheritdoc />
public Task SendAsync(SiteHealthReport report, CancellationToken cancellationToken)
{
var n = Interlocked.Increment(ref _callCount);
if (n == 1)
{
throw new InvalidOperationException("transport temporarily unavailable");
}
SentReports.Add(report);
return Task.CompletedTask;
}
}
/// <summary>
/// Regression: the sequence-number seed must be derived
/// from the injected <see cref="TimeProvider"/> so the Unix-ms seeding strategy
/// is deterministically testable and the clock dependency is explicit, rather
/// than reading <c>DateTimeOffset.UtcNow</c> directly at field initialization.
/// </summary>
[Fact]
public void SequenceNumberSeed_UsesInjectedTimeProvider()
{
var fixedInstant = new DateTimeOffset(2026, 5, 16, 12, 0, 0, TimeSpan.Zero);
var timeProvider = new TestTimeProvider(fixedInstant);
var sender = new HealthReportSender(
new SiteHealthCollector(),
new FakeTransport(),
Options.Create(new HealthMonitoringOptions()),
NullLogger<HealthReportSender>.Instance,
new FakeSiteIdentityProvider(),
timeProvider: timeProvider);
Assert.Equal(fixedInstant.ToUnixTimeMilliseconds(), sender.CurrentSequenceNumber);
}
/// <summary>
/// COMM-1 regression: two site nodes started 5 s apart; the older one (A) is active and has
/// sent 6 000 reports (~50 h at 30 s). B becomes active. Under the old "seed at construction,
/// +1 per report" scheme B's first sequence (T_B + 1) sorted below A's last (T_A + 6000) and
/// central rejected every B report. With <c>max(prev + 1, now-ms)</c> B's first report sorts
/// above anything A ever sent.
/// </summary>
[Fact]
public void NextSequenceNumber_AfterFailover_SortsAboveLongRunningPeer()
{
var t0 = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero);
var clock = new TestTimeProvider(t0);
long seqA = t0.ToUnixTimeMilliseconds();
long seqB = t0.AddSeconds(5).ToUnixTimeMilliseconds();
long lastA = 0;
for (var i = 0; i < 6000; i++)
{
clock.Advance(TimeSpan.FromSeconds(30));
lastA = HealthReportSender.NextSequenceNumber(ref seqA, clock);
}
clock.Advance(TimeSpan.FromSeconds(30));
var firstB = HealthReportSender.NextSequenceNumber(ref seqB, clock);
Assert.True(firstB > lastA, $"B's first sequence {firstB} must sort above A's last {lastA}");
// The old scheme would have produced T_B + 1, below A's T_A + 6000.
Assert.True(t0.AddSeconds(5).ToUnixTimeMilliseconds() + 1 < t0.ToUnixTimeMilliseconds() + 6000);
}
/// <summary>COMM-1: the sequence stays strictly monotonic when the wall clock steps backwards.</summary>
[Fact]
public void NextSequenceNumber_ClockStepsBack_StillStrictlyIncreasing()
{
var t0 = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero);
var clock = new TestTimeProvider(t0);
long seq = t0.ToUnixTimeMilliseconds();
var a = HealthReportSender.NextSequenceNumber(ref seq, clock);
clock.Advance(TimeSpan.FromMinutes(-10));
var b = HealthReportSender.NextSequenceNumber(ref seq, clock);
var c = HealthReportSender.NextSequenceNumber(ref seq, clock);
Assert.True(b > a);
Assert.True(c > b);
}
/// <summary>
/// COMM-6 regression: a standby node drains its per-interval counters every tick, so the first
/// report after it becomes active does not carry its whole standby life as one interval.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task StandbyTicks_DrainIntervalCounters_SoFirstActiveReportIsOneInterval()
{
var transport = new FakeTransport();
var collector = new SiteHealthCollector();
collector.SetActiveNode(false);
for (var i = 0; i < 4000; i++) collector.IncrementDeadLetter();
collector.IncrementScriptError();
var sender = new HealthReportSender(
collector,
transport,
Options.Create(new HealthMonitoringOptions { ReportInterval = TimeSpan.FromMilliseconds(30) }),
NullLogger<HealthReportSender>.Instance,
new FakeSiteIdentityProvider());
await sender.StartAsync(CancellationToken.None);
try
{
// Let several standby ticks run (30 ms interval), then promote the node.
await Task.Delay(300);
Assert.Empty(transport.SentReports);
collector.SetActiveNode(true);
await WaitUntilAsync(() => transport.SentReports.Count > 0, TimeSpan.FromSeconds(5));
}
finally
{
await sender.StopAsync(CancellationToken.None);
}
var first = transport.SentReports[0];
Assert.Equal(0, first.DeadLetterCount);
Assert.Equal(0, first.ScriptErrorCount);
}
private static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
if (condition()) return;
await Task.Delay(20);
}
Assert.Fail("Condition not met within timeout");
}
}