using System.Collections.Concurrent; using System.Diagnostics.Metrics; using Akka.Actor; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Shouldly; using Xunit; using ZB.MOM.WW.Audit; using ZB.MOM.WW.OtOpcUa.Configuration; using ZB.MOM.WW.OtOpcUa.ControlPlane.Audit; using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; /// /// #980 / review 05 H-2 — a flush that fails because the database did not answer used to clear the /// buffer first and drop the batch. The writer now keeps it (bounded, drop-oldest + counter) and the next /// tick retries; the unique EventId index makes a retried batch safe. /// public sealed class AuditWriterActorRetryTests : ControlPlaneActorTestBase { [Fact] public void A_transient_connection_failure_keeps_the_batch_and_the_next_flush_persists_it() { var failing = new FailingSaves { Down = true }; var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing); var actor = ActorOfAsTestActorRef(AuditWriterActor.Props(factory)); var ids = Enumerable.Range(0, 20).Select(_ => Guid.NewGuid()).ToList(); foreach (var id in ids) actor.Tell(NewEvent(id)); actor.Tell(AuditWriterActor.Flush.Instance); // outage: the save throws actor.UnderlyingActor.BufferedCount.ShouldBe(20, "the failed batch must stay buffered, not be dropped"); failing.Attempts.ShouldBeGreaterThan(0, "positive control: the failure path really ran"); using (var during = factory.CreateDbContext(withFailure: false)) during.ConfigAuditLogs.Count().ShouldBe(0); failing.Down = false; actor.Tell(AuditWriterActor.Flush.Instance); // recovery actor.UnderlyingActor.BufferedCount.ShouldBe(0); using var db = factory.CreateDbContext(withFailure: false); var persisted = db.ConfigAuditLogs.Select(r => r.EventId).ToList(); persisted.Count.ShouldBe(20, "no event may be lost across the outage"); foreach (var id in ids) persisted.ShouldContain(id); actor.UnderlyingActor.OverflowDroppedCount.ShouldBe(0); } [Fact] public void Events_arriving_during_an_outage_are_kept_and_persist_after_recovery() { var failing = new FailingSaves { Down = true }; var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing); var actor = ActorOfAsTestActorRef(AuditWriterActor.Props(factory)); // Cross the count threshold so a threshold flush fires, fails, and the writer must NOT retry per event. var ids = Enumerable.Range(0, AuditWriterActor.FlushBatchSize + 50).Select(_ => Guid.NewGuid()).ToList(); foreach (var id in ids) actor.Tell(NewEvent(id)); failing.Attempts.ShouldBe(1, "while the database is failing, arriving events must not each trigger a blocking flush attempt"); actor.UnderlyingActor.BufferedCount.ShouldBe(ids.Count); failing.Down = false; actor.Tell(AuditWriterActor.Flush.Instance); using var db = factory.CreateDbContext(withFailure: false); db.ConfigAuditLogs.Count().ShouldBe(ids.Count); } [Fact] public void The_retry_buffer_is_bounded_dropping_the_oldest_and_counting_them() { var failing = new FailingSaves { Down = true }; var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing); var actor = ActorOfAsTestActorRef(AuditWriterActor.Props(factory)); const int extra = 25; var ids = Enumerable.Range(0, AuditWriterActor.MaxBufferedEvents + extra).Select(_ => Guid.NewGuid()).ToList(); foreach (var id in ids) actor.Tell(NewEvent(id)); actor.UnderlyingActor.BufferedCount.ShouldBe(AuditWriterActor.MaxBufferedEvents); actor.UnderlyingActor.OverflowDroppedCount.ShouldBe(extra); failing.Down = false; actor.Tell(AuditWriterActor.Flush.Instance); using var db = factory.CreateDbContext(withFailure: false); var persisted = db.ConfigAuditLogs.Select(r => r.EventId).ToHashSet(); persisted.Count.ShouldBe(AuditWriterActor.MaxBufferedEvents); // Drop-OLDEST: the first `extra` are gone, the newest survive. foreach (var id in ids.Take(extra)) persisted.ShouldNotContain(id); persisted.ShouldContain(ids[^1]); persisted.ShouldContain(ids[extra]); } /// /// #1030: the overflow drop count is exported on the shared OtOpcUa meter as /// otopcua.audit.dropped (it used to be visible only through the actor's own property, which nothing /// outside a test can read). Measurements are filtered by the writer's actor tag so a parallel test's /// writer cannot leak into the sum. /// [Fact] public void Overflow_drops_are_exported_on_the_audit_dropped_meter_counter() { var failing = new FailingSaves { Down = true }; var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing); var actor = ActorOfAsTestActorRef(AuditWriterActor.Props(factory)); var actorTag = actor.Path.ToStringWithoutAddress(); var measured = new ConcurrentQueue(); using var listener = new MeterListener(); listener.InstrumentPublished = (instrument, l) => { if (instrument.Name == AuditWriterActor.DroppedCounterName) l.EnableMeasurementEvents(instrument); }; listener.SetMeasurementEventCallback((_, value, tags, _) => { string? owner = null, reason = null; foreach (var tag in tags) { if (tag.Key == "actor") owner = tag.Value as string; if (tag.Key == "reason") reason = tag.Value as string; } if (owner == actorTag && reason == "buffer_full") measured.Enqueue(value); }); listener.Start(); const int extra = 7; for (var i = 0; i < AuditWriterActor.MaxBufferedEvents + extra; i++) actor.Tell(NewEvent(Guid.NewGuid())); actor.UnderlyingActor.OverflowDroppedCount.ShouldBe(extra, "positive control: the drops really happened"); measured.Sum().ShouldBe(extra, "every dropped event must be counted on the exported meter"); } private static AuditEvent NewEvent(Guid eventId) => new() { EventId = eventId, Category = "Config", Action = "Edit", Actor = "joe", OccurredAtUtc = DateTimeOffset.UtcNow, Outcome = AuditOutcome.Success, DetailsJson = "{}", SourceNode = "node-a", CorrelationId = Guid.NewGuid(), }; /// Throws a connection-level (entry-less) on every save while . private sealed class FailingSaves : ISaveChangesInterceptor { private int _attempts; public volatile bool Down; public int Attempts => Volatile.Read(ref _attempts); public InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) { if (!Down) return result; Interlocked.Increment(ref _attempts); throw new DbUpdateException("connection lost (simulated)"); } } private sealed class FailingDbFactory(string dbName, InMemoryDatabaseRoot root, FailingSaves interceptor) : IDbContextFactory { public OtOpcUaConfigDbContext CreateDbContext() => CreateDbContext(withFailure: true); public OtOpcUaConfigDbContext CreateDbContext(bool withFailure) { var builder = new DbContextOptionsBuilder().UseInMemoryDatabase(dbName, root); if (withFailure) builder.AddInterceptors(interceptor); return new OtOpcUaConfigDbContext(builder.Options); } } }