Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientReview1202RecoveryTests.cs
T

68 lines
3.2 KiB
C#

using System.Diagnostics;
using System.Text.Json;
using Moq;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
/// <summary>
/// #992 / review 2026-12-02 G-10 — the in-place recovery re-publish scanned every monitored item of every
/// subscription per recovered ref (O(refs x items)) while holding the delivery lock.
/// </summary>
[Trait("Category", "Unit")]
public sealed class OpcUaClientReview1202RecoveryTests
{
private const int RefCount = 20_000;
/// <summary>
/// 20k refs on one subscription: a bad then a good keep-alive must re-publish every ref promptly. Before the
/// per-subscription ref index this was ~2 x 10^8 string compares under the delivery lock.
/// </summary>
[Fact]
public async Task Recovery_republish_of_20k_refs_is_not_quadratic()
{
var refs = Enumerable.Range(0, RefCount).Select(i => $"Plant/dev/T{i}").ToList();
var tags = refs.Select((r, i) =>
new RawTagEntry(r, JsonSerializer.Serialize(new { nodeId = $"ns=0;s=T{i}" }), WriteIdempotent: true)).ToList();
var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions { RawTags = tags }, "opcua-g10");
using var _ = drv;
var session = new Mock<ISession>(MockBehavior.Loose);
session.SetupGet(s => s.MessageContext).Returns(ServiceMessageContext.Create(SdkTelemetry.Context));
session.SetupGet(s => s.NamespaceUris).Returns(new NamespaceTable());
drv.SetSessionForTest(session.Object);
drv.SetNamespaceMapForTest(NamespaceMap.FromTable(new NamespaceTable(), tags));
drv.SetHealthForTest(new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null));
drv.PostRecoveryReconcileDelay = () => TimeSpan.FromDays(1); // keep the trailing read out of this test
session.Setup(s => s.ReadAsync(
It.IsAny<RequestHeader>(), It.IsAny<double>(), It.IsAny<TimestampsToReturn>(),
It.IsAny<ArrayOf<ReadValueId>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((RequestHeader _, double _, TimestampsToReturn _, ArrayOf<ReadValueId> nodes, CancellationToken _) =>
new ReadResponse
{
ResponseHeader = new ResponseHeader(),
Results = [.. nodes.ToList().Select(_ => new DataValue(VariantHelper.CastFrom(1), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow))],
DiagnosticInfos = [],
});
drv.AddSubscriptionForTest(refs);
var goodPublishes = 0;
drv.OnDataChange += (_, e) =>
{
if (e.Snapshot.StatusCode == 0u) Interlocked.Increment(ref goodPublishes);
};
drv.RaiseKeepAliveForTest(StatusCodes.BadNoCommunication);
var sw = Stopwatch.StartNew();
drv.RaiseKeepAliveForTest(StatusCodes.Good);
await drv.RecoveryTaskForTest;
sw.Stop();
goodPublishes.ShouldBe(RefCount, "positive control: every awaiting ref was re-published");
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromMilliseconds(1500),
$"recovery of {RefCount} refs took {sw.ElapsedMilliseconds} ms — the per-ref scan is O(refs x items)");
}
}