using System.Collections.Concurrent; using Akka.Actor; using Akka.TestKit.Xunit2; using Grpc.Core; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; using ZB.MOM.WW.Audit; using ZB.MOM.WW.ScadaBridge.AuditLog.Central; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; using ZB.MOM.WW.ScadaBridge.Commons.Messages.Integration; using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit; using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; using ProtoPullRequest = ZB.MOM.WW.ScadaBridge.Communication.Grpc.PullAuditEventsRequest; using ProtoPullResponse = ZB.MOM.WW.ScadaBridge.Communication.Grpc.PullAuditEventsResponse; namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Central; /// /// AUD-1: the site audit store is per node and unreplicated, so the reconciliation pull reaches /// BOTH nodes of a site every tick, each with its own (site, node) cursor — not NodeA whenever /// NodeA answers, with one cursor shared by two unrelated stores. /// public class ReconciliationPerNodeTests : TestKit { private const string NodeA = "http://site-a-node-a:8083"; private const string NodeB = "http://site-a-node-b:8083"; private static readonly DateTime OwedAt = new(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc); private sealed class StaticEnumerator(params SiteEntry[] sites) : ISiteEnumerator { public Task> EnumerateAsync(CancellationToken ct = default) => Task.FromResult>(sites); } /// /// NodeA (a healthy standby after a restart) owes nothing; NodeB (active) owes one /// PushAbandoned row. Records every per-node pull with the cursor it was sent. /// private sealed class PerNodeClient : IPullAuditEventsClient { public readonly AuditEvent NodeBRow = ScadaBridgeAuditEventFactory.Create( eventId: Guid.NewGuid(), occurredAtUtc: OwedAt, channel: AuditChannel.ApiOutbound, kind: AuditKind.ApiCall, status: AuditStatus.Delivered, sourceSiteId: "site-a"); public ConcurrentQueue<(string Endpoint, DateTime Since, string? AfterId)> Calls { get; } = new(); public Task PullAsync( string siteId, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) => throw new InvalidOperationException("the actor must pull per node"); public Task PullFromEndpointAsync( string siteId, string endpoint, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) { Calls.Enqueue((endpoint, sinceUtc, afterId)); var events = endpoint == NodeB && sinceUtc < OwedAt ? new[] { NodeBRow } : Array.Empty(); return Task.FromResult(new PullAuditEventsResponse(events, MoreAvailable: false)); } } /// /// Regression: the NodeB-owed row reaches central even though NodeA answers, and each node /// keeps its own cursor (NodeA's never moves off its start; NodeB's advances past its row). /// [Fact] public void BothNodesArePulled_EachWithItsOwnCursor() { var client = new PerNodeClient(); var repo = Substitute.For(); var inserted = new ConcurrentBag(); repo.InsertManyIfNotExistsAsync(Arg.Any>(), Arg.Any(), Arg.Any()) .Returns(ci => { foreach (var e in (IReadOnlyList)ci[0]) inserted.Add(e.EventId); return Task.FromResult(((IReadOnlyList)ci[0]).Count); }); var services = new ServiceCollection(); services.AddScoped(_ => repo); var actor = Sys.ActorOf(Props.Create(() => new SiteAuditReconciliationActor( new StaticEnumerator(new SiteEntry("site-a", NodeA, NodeB)), client, services.BuildServiceProvider(), Options.Create(new SiteAuditReconciliationOptions { ReconciliationIntervalOverride = TimeSpan.FromMilliseconds(100), }), NullLogger.Instance))); // Two ticks' worth of pulls on each node. AwaitCondition(() => client.Calls.Count(c => c.Endpoint == NodeB) >= 2 && client.Calls.Count(c => c.Endpoint == NodeA) >= 2, TimeSpan.FromSeconds(10)); Assert.Contains(client.NodeBRow.EventId, inserted); var nodeACalls = client.Calls.Where(c => c.Endpoint == NodeA).ToList(); Assert.All(nodeACalls, c => Assert.Equal(DateTime.MinValue, c.Since)); var nodeBCalls = client.Calls.Where(c => c.Endpoint == NodeB).ToList(); Assert.Equal(DateTime.MinValue, nodeBCalls[0].Since); Assert.Equal(OwedAt, nodeBCalls[1].Since); Assert.Equal(client.NodeBRow.EventId.ToString(), nodeBCalls[1].AfterId); Watch(actor); Sys.Stop(actor); ExpectTerminated(actor); } private sealed class RecordingInvoker : GrpcPullAuditEventsClient.IPullAuditEventsInvoker { public ConcurrentQueue Endpoints { get; } = new(); public Task InvokeAsync(string siteId, string endpoint, ProtoPullRequest request, CancellationToken ct) { Endpoints.Enqueue(endpoint); throw new RpcException(new Grpc.Core.Status(StatusCode.Unavailable, "node down")); } } /// The per-node pull dials only the node it is given — no NodeA→NodeB failover. /// A task that represents the asynchronous operation. [Fact] public async Task PullFromEndpoint_DialsOnlyThatNode_AndCollapsesAFaultToEmpty() { var invoker = new RecordingInvoker(); var client = new GrpcPullAuditEventsClient( new StaticEnumerator(new SiteEntry("site-a", NodeA, NodeB)), invoker, NullLogger.Instance); var response = await client.PullFromEndpointAsync("site-a", NodeA, DateTime.MinValue, null, 10, CancellationToken.None); Assert.Empty(response.Events); Assert.Equal(new[] { NodeA }, invoker.Endpoints.ToArray()); } }