fix(audit): reconciliation pulls every site node with a per-(site, node) cursor (AUD-1, WP4 task 4.8)
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1192,4 +1192,57 @@ public class SiteCallAuditReconciliationTests : TestKit
|
||||
return new PullSiteCallsResponse(Array.Empty<SiteCall>(), MoreAvailable: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Records each per-node pull; only NodeB owes a row (an unreplicated pair after a NodeA restart).</summary>
|
||||
private sealed class PerNodePullClient(SiteCall nodeBRow) : IPullSiteCallsClient
|
||||
{
|
||||
public System.Collections.Concurrent.ConcurrentQueue<(string Endpoint, DateTime Since)> Calls { get; } = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<PullSiteCallsResponse> PullAsync(
|
||||
string siteId, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) =>
|
||||
throw new InvalidOperationException("the actor must pull per node");
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<PullSiteCallsResponse> PullFromEndpointAsync(
|
||||
string siteId, string endpoint, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct)
|
||||
{
|
||||
Calls.Enqueue((endpoint, sinceUtc));
|
||||
var rows = endpoint == "http://nodeB:8083" && sinceUtc < nodeBRow.UpdatedAtUtc
|
||||
? new[] { nodeBRow }
|
||||
: Array.Empty<SiteCall>();
|
||||
return Task.FromResult(new PullSiteCallsResponse(rows, MoreAvailable: false));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-1 regression: both nodes of the site are pulled every tick, each with its own cursor,
|
||||
/// so a row owed only by NodeB reaches central although NodeA answers.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Reconciliation_PullsBothNodes_EachWithItsOwnCursor()
|
||||
{
|
||||
var row = NewRow(TrackedOperationId.New(), "siteA", status: "Parked",
|
||||
updatedAtUtc: new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc));
|
||||
var client = new PerNodePullClient(row);
|
||||
var repo = new RecordingRepo();
|
||||
var actor = CreateActor(
|
||||
new StaticEnumerator(new SiteEntry("siteA", "http://nodeA:8083", "http://nodeB:8083")),
|
||||
client, repo, FastTickOptions());
|
||||
|
||||
AwaitCondition(() => client.Calls.Count(c => c.Endpoint == "http://nodeB:8083") >= 2
|
||||
&& client.Calls.Count(c => c.Endpoint == "http://nodeA:8083") >= 2,
|
||||
TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.True(repo.Upserted.ContainsKey(row.TrackedOperationId));
|
||||
Assert.All(client.Calls.Where(c => c.Endpoint == "http://nodeA:8083"),
|
||||
c => Assert.Equal(DateTime.MinValue, c.Since));
|
||||
var nodeB = client.Calls.Where(c => c.Endpoint == "http://nodeB:8083").ToList();
|
||||
Assert.Equal(DateTime.MinValue, nodeB[0].Since);
|
||||
Assert.Equal(row.UpdatedAtUtc, nodeB[1].Since);
|
||||
|
||||
Watch(actor);
|
||||
Sys.Stop(actor);
|
||||
ExpectTerminated(actor);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user