Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Central/ReconciliationPerNodeTests.cs
T

146 lines
6.4 KiB
C#

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;
/// <summary>
/// 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.
/// </summary>
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<IReadOnlyList<SiteEntry>> EnumerateAsync(CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<SiteEntry>>(sites);
}
/// <summary>
/// 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.
/// </summary>
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<PullAuditEventsResponse> PullAsync(
string siteId, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) =>
throw new InvalidOperationException("the actor must pull per node");
public Task<PullAuditEventsResponse> 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<AuditEvent>();
return Task.FromResult(new PullAuditEventsResponse(events, MoreAvailable: false));
}
}
/// <summary>
/// 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).
/// </summary>
[Fact]
public void BothNodesArePulled_EachWithItsOwnCursor()
{
var client = new PerNodeClient();
var repo = Substitute.For<IAuditLogRepository>();
var inserted = new ConcurrentBag<Guid>();
repo.InsertManyIfNotExistsAsync(Arg.Any<IReadOnlyList<AuditEvent>>(), Arg.Any<TimeSpan?>(), Arg.Any<CancellationToken>())
.Returns(ci =>
{
foreach (var e in (IReadOnlyList<AuditEvent>)ci[0]) inserted.Add(e.EventId);
return Task.FromResult(((IReadOnlyList<AuditEvent>)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<SiteAuditReconciliationActor>.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<string> Endpoints { get; } = new();
public Task<ProtoPullResponse> InvokeAsync(string siteId, string endpoint, ProtoPullRequest request, CancellationToken ct)
{
Endpoints.Enqueue(endpoint);
throw new RpcException(new Grpc.Core.Status(StatusCode.Unavailable, "node down"));
}
}
/// <summary>The per-node pull dials only the node it is given — no NodeA→NodeB failover.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<GrpcPullAuditEventsClient>.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());
}
}