Merge #992: OpcUaClient indexed recovery re-publish, safe unsubscribe ordering, Bad publish for refused refs, post-dispatch BadTimeout, IPv6 probe preflight
This commit is contained in:
@@ -160,4 +160,36 @@ public sealed class GalaxyDriverProbeTests
|
||||
message.ShouldContain("DeadlineExceeded");
|
||||
message.ShouldContain("host:5120");
|
||||
}
|
||||
|
||||
// ── #992 G-15: the TCP preflight is dual-mode (IPv6 literal / AAAA-only hosts) ────────────────
|
||||
|
||||
/// <summary>
|
||||
/// An IPv6 literal endpoint must pass the TCP preflight (it used to fail "Connect failed" on an IPv4-only
|
||||
/// socket before any gRPC traffic). A listener that accepts then closes proves the preflight connected: the
|
||||
/// failure is then the gRPC ping, never "Connect failed".
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_IPv6_literal_endpoint_passes_the_tcp_preflight()
|
||||
{
|
||||
if (!Socket.OSSupportsIPv6) Assert.Skip("IPv6 is not available on this host.");
|
||||
var listener = new TcpListener(IPAddress.IPv6Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
var testCt = TestContext.Current.CancellationToken;
|
||||
var accepted = Task.Run(async () =>
|
||||
{
|
||||
try { using var c = await listener.AcceptTcpClientAsync(testCt); return true; }
|
||||
catch { return false; }
|
||||
}, testCt);
|
||||
try
|
||||
{
|
||||
var result = await _probe.ProbeAsync(
|
||||
ConfigJson($"http://[::1]:{port}"), TimeSpan.FromSeconds(5), testCt);
|
||||
|
||||
result.Ok.ShouldBeFalse("the listener is not a gateway");
|
||||
result.Message.ShouldNotBeNull().ShouldNotContain("Connect failed", Case.Insensitive);
|
||||
(await accepted.WaitAsync(TimeSpan.FromSeconds(5), testCt)).ShouldBeTrue("the preflight reached the IPv6 listener");
|
||||
}
|
||||
finally { listener.Stop(); }
|
||||
}
|
||||
}
|
||||
|
||||
+49
@@ -93,6 +93,55 @@ public sealed class OpcUaClientSmokeTests(OpcPlcFixture sim)
|
||||
await drv.UnsubscribeAsync(handle, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #992 G-12 through the real SDK: a ref whose upstream node does not exist (the server refuses the monitored
|
||||
/// item with <c>BadNodeIdUnknown</c> in the create RESULT, not an exception) used to get no publish, no log and
|
||||
/// no status. It now gets exactly one Bad publish carrying the upstream's code, while the good ref beside it
|
||||
/// still delivers values.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_subscribed_ref_the_server_refuses_gets_one_Bad_publish_with_the_upstream_code()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
const string missingRef = "Sim/OpcUaClient/plc/DoesNotExist";
|
||||
var options = OpcPlcProfile.BuildOptions(sim.EndpointUrl) with
|
||||
{
|
||||
RawTags =
|
||||
[
|
||||
.. OpcPlcProfile.RawTags,
|
||||
new RawTagEntry(missingRef, System.Text.Json.JsonSerializer.Serialize(new { nodeId = "ns=3;s=DoesNotExist" }), WriteIdempotent: true),
|
||||
],
|
||||
};
|
||||
await using var drv = new OpcUaClientDriver(options, driverInstanceId: "opcua-smoke-refused");
|
||||
await drv.InitializeAsync("{}", ct);
|
||||
|
||||
var observed = new List<DataChangeEventArgs>();
|
||||
drv.OnDataChange += (_, e) => { lock (observed) observed.Add(e); };
|
||||
|
||||
var handle = await drv.SubscribeAsync(
|
||||
[OpcPlcProfile.FastUInt1Ref, missingRef], TimeSpan.FromMilliseconds(250), ct);
|
||||
|
||||
// Positive control: the good ref beside the refused one is live.
|
||||
var deadline = DateTime.UtcNow.AddSeconds(5);
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
lock (observed)
|
||||
if (observed.Any(o => o.FullReference == OpcPlcProfile.FastUInt1Ref && o.Snapshot.StatusCode == 0u)) break;
|
||||
await Task.Delay(100, ct);
|
||||
}
|
||||
DataChangeEventArgs[] snapshot;
|
||||
lock (observed) snapshot = [.. observed];
|
||||
snapshot.ShouldContain(o => o.FullReference == OpcPlcProfile.FastUInt1Ref && o.Snapshot.StatusCode == 0u);
|
||||
|
||||
var refused = snapshot.Where(o => o.FullReference == missingRef).ToList();
|
||||
refused.Count.ShouldBe(1, "exactly one Bad publish for the refused ref");
|
||||
refused[0].Snapshot.StatusCode.ShouldBe(Opc.Ua.StatusCodes.BadNodeIdUnknown.Code);
|
||||
refused[0].SubscriptionHandle.ShouldBe(handle);
|
||||
|
||||
await drv.UnsubscribeAsync(handle, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Review 2026-10-21 O-9 + lifecycle generation, through the real SDK: a shutdown with several live
|
||||
/// subscriptions completes inside the one teardown budget, lands Unknown, and a re-initialise of the same
|
||||
|
||||
+32
@@ -157,4 +157,36 @@ public sealed class OpcUaClientDriverProbeTests
|
||||
message.ShouldNotContain("invalid", Case.Insensitive);
|
||||
message.ShouldContain("Connect failed", Case.Insensitive);
|
||||
}
|
||||
|
||||
// ── #992 G-15: the TCP preflight is dual-mode (IPv6 literal / AAAA-only hosts) ────────────────
|
||||
|
||||
/// <summary>
|
||||
/// An IPv6 literal endpoint must pass the TCP preflight (it used to fail "Connect failed" on an IPv4-only
|
||||
/// socket before any OPC UA traffic). A listener that accepts then closes proves the preflight connected: the
|
||||
/// failure is then the discovery handshake, never "Connect failed".
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_IPv6_literal_endpoint_passes_the_tcp_preflight()
|
||||
{
|
||||
if (!Socket.OSSupportsIPv6) Assert.Skip("IPv6 is not available on this host.");
|
||||
var listener = new TcpListener(IPAddress.IPv6Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
var testCt = TestContext.Current.CancellationToken;
|
||||
var accepted = Task.Run(async () =>
|
||||
{
|
||||
try { using var c = await listener.AcceptTcpClientAsync(testCt); return true; }
|
||||
catch { return false; }
|
||||
}, testCt);
|
||||
try
|
||||
{
|
||||
var result = await _probe.ProbeAsync(
|
||||
$$"""{"EndpointUrl":"opc.tcp://[::1]:{{port}}"}""", TimeSpan.FromSeconds(5), testCt);
|
||||
|
||||
result.Ok.ShouldBeFalse("the listener is not an OPC UA server");
|
||||
result.Message.ShouldNotBeNull().ShouldNotContain("Connect failed", Case.Insensitive);
|
||||
(await accepted.WaitAsync(TimeSpan.FromSeconds(5), testCt)).ShouldBeTrue("the preflight reached the IPv6 listener");
|
||||
}
|
||||
finally { listener.Stop(); }
|
||||
}
|
||||
}
|
||||
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
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-11 .. G-14 on the OpcUaClient driver (G-10 is in
|
||||
/// <see cref="OpcUaClientReview1202RecoveryTests"/>, G-15 in the probe tests, G-12's wire half in the
|
||||
/// integration suite).
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class OpcUaClientReview1202FindingsTests
|
||||
{
|
||||
private const string SpeedRef = "Plant/dev/Speed";
|
||||
|
||||
private static readonly IReadOnlyList<RawTagEntry> Tags =
|
||||
[new(SpeedRef, JsonSerializer.Serialize(new { nodeId = "ns=0;s=Speed" }), WriteIdempotent: true)];
|
||||
|
||||
private sealed class ListLogger : ILogger<OpcUaClientDriver>
|
||||
{
|
||||
public List<(LogLevel Level, string Message)> Entries { get; } = [];
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
|
||||
Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
lock (Entries) Entries.Add((logLevel, formatter(state, exception)));
|
||||
}
|
||||
}
|
||||
|
||||
private static (OpcUaClientDriver Driver, Mock<ISession> Session) NewConnectedDriver(ILogger<OpcUaClientDriver>? log = null)
|
||||
{
|
||||
var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions { RawTags = Tags }, "opcua-g11", log);
|
||||
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));
|
||||
return (drv, session);
|
||||
}
|
||||
|
||||
private static void RaiseGoodNotification(MonitoredItem item, int value) =>
|
||||
item.SaveValueInCache(new MonitoredItemNotification
|
||||
{
|
||||
Value = new DataValue(VariantHelper.CastFrom(value), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow),
|
||||
});
|
||||
|
||||
// ── G-11 ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// An unsubscribe whose gate wait is cancelled must not orphan a live subscription: nothing more is delivered
|
||||
/// for it (the host re-subscribes the new set in that window) and the wire delete is still issued once the
|
||||
/// gate frees. Positive control: the notification path demonstrably delivers before the unsubscribe.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_cancelled_unsubscribe_wait_detaches_the_subscription_and_still_deletes_it()
|
||||
{
|
||||
var (drv, _) = NewConnectedDriver();
|
||||
using var _ = drv;
|
||||
var handle = drv.AddSubscriptionForTest([SpeedRef]);
|
||||
var item = drv.MonitoredItemsForTest(handle).Single();
|
||||
var delivered = 0;
|
||||
drv.OnDataChange += (_, _) => Interlocked.Increment(ref delivered);
|
||||
var deleted = new List<Subscription>();
|
||||
drv.DeleteSubscriptionAsync = (sub, _) => { lock (deleted) deleted.Add(sub); return Task.CompletedTask; };
|
||||
|
||||
RaiseGoodNotification(item, 1);
|
||||
delivered.ShouldBe(1, "positive control: the registered handler delivers");
|
||||
|
||||
await drv.SubscriptionGate.WaitAsync(TestContext.Current.CancellationToken); // e.g. a slow ConditionRefresh holds it
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
|
||||
await Should.ThrowAsync<OperationCanceledException>(() => drv.UnsubscribeAsync(handle, cts.Token));
|
||||
|
||||
RaiseGoodNotification(item, 2);
|
||||
delivered.ShouldBe(1, "the orphan must not keep delivering after its unsubscribe was cancelled");
|
||||
lock (deleted) deleted.Count.ShouldBe(0, "the gate is still held, so the delete is queued, not issued");
|
||||
|
||||
drv.SubscriptionGate.Release();
|
||||
await drv.DeferredDeleteForTest.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
lock (deleted) deleted.Count.ShouldBe(1, "the wire delete was still issued once the gate freed");
|
||||
|
||||
await drv.UnsubscribeAsync(handle, TestContext.Current.CancellationToken); // a retry is a quiet no-op
|
||||
lock (deleted) deleted.Count.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// While the unsubscribe waits for the gate (token still live) the subscription stays tracked; once the gate
|
||||
/// frees it is removed, detached and deleted exactly once.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_unsubscribe_waiting_for_the_gate_keeps_the_subscription_tracked_until_it_holds_it()
|
||||
{
|
||||
var (drv, _) = NewConnectedDriver();
|
||||
using var _ = drv;
|
||||
var handle = drv.AddSubscriptionForTest([SpeedRef]);
|
||||
var deleted = new List<Subscription>();
|
||||
drv.DeleteSubscriptionAsync = (sub, _) => { lock (deleted) deleted.Add(sub); return Task.CompletedTask; };
|
||||
|
||||
await drv.SubscriptionGate.WaitAsync(TestContext.Current.CancellationToken);
|
||||
var unsub = drv.UnsubscribeAsync(handle, TestContext.Current.CancellationToken);
|
||||
await Task.Delay(100, TestContext.Current.CancellationToken);
|
||||
|
||||
unsub.IsCompleted.ShouldBeFalse("it is waiting for the gate");
|
||||
drv.MonitoredItemsForTest(handle).Count.ShouldBe(1, "still tracked until the gate is held");
|
||||
|
||||
drv.SubscriptionGate.Release();
|
||||
await unsub.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
drv.MonitoredItemsForTest(handle).Count.ShouldBe(0);
|
||||
lock (deleted) deleted.Count.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>The alarm unsubscribe has the same ordering: a cancelled gate wait still deletes the subscription.</summary>
|
||||
[Fact]
|
||||
public async Task A_cancelled_alarm_unsubscribe_wait_still_deletes_the_subscription()
|
||||
{
|
||||
var (drv, _) = NewConnectedDriver();
|
||||
using var _ = drv;
|
||||
var handle = drv.AddAlarmSubscriptionForTest([SpeedRef]);
|
||||
var deleted = new List<Subscription>();
|
||||
drv.DeleteSubscriptionAsync = (sub, _) => { lock (deleted) deleted.Add(sub); return Task.CompletedTask; };
|
||||
|
||||
await drv.SubscriptionGate.WaitAsync(TestContext.Current.CancellationToken);
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
|
||||
await Should.ThrowAsync<OperationCanceledException>(() => drv.UnsubscribeAlarmsAsync(handle, cts.Token));
|
||||
drv.SubscriptionGate.Release();
|
||||
|
||||
await drv.DeferredDeleteForTest.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
lock (deleted) deleted.Count.ShouldBe(1);
|
||||
}
|
||||
|
||||
// ── G-12 ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// A ref with no monitored item is published Bad with the real code (it used to be silent), once each, and one
|
||||
/// summarised Warning is logged. The accepted ref is not touched.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Refs_with_no_monitored_item_are_published_Bad_with_their_code_and_warned_once()
|
||||
{
|
||||
var log = new ListLogger();
|
||||
var (drv, _) = NewConnectedDriver(log);
|
||||
using var _ = drv;
|
||||
var handle = drv.AddSubscriptionForTest([SpeedRef]);
|
||||
var seen = new List<DataChangeEventArgs>();
|
||||
drv.OnDataChange += (_, e) => seen.Add(e);
|
||||
|
||||
drv.ReportRejectedItems(handle,
|
||||
[
|
||||
new OpcUaClientDriver.RejectedItem("Plant/dev/Gone", 0x80340000u, "the server refused the monitored item"),
|
||||
new OpcUaClientDriver.RejectedItem("Plant/dev/Unresolved", 0x80330000u, "the reference does not resolve"),
|
||||
]);
|
||||
|
||||
seen.Select(e => (e.FullReference, e.Snapshot.StatusCode)).ShouldBe(
|
||||
[("Plant/dev/Gone", 0x80340000u), ("Plant/dev/Unresolved", 0x80330000u)]);
|
||||
seen.ShouldAllBe(e => ReferenceEquals(e.SubscriptionHandle, handle));
|
||||
lock (log.Entries)
|
||||
log.Entries.Where(e => e.Level == LogLevel.Warning).ShouldHaveSingleItem().Message.ShouldContain("2 of the subscribed");
|
||||
}
|
||||
|
||||
// ── G-13 ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly Dictionary<string, string> TripIndex = new() { ["ns=3;s=Alarms.Trip1"] = "Plant/opc/plc/Trip1" };
|
||||
|
||||
private static List<Variant> Fields(NodeId eventType, Variant conditionId, string message) =>
|
||||
[
|
||||
Variant.From(new byte[] { 1 }.ToByteString()),
|
||||
new Variant(eventType),
|
||||
new Variant(NodeId.Parse("ns=3;s=Alarms.Trip1")),
|
||||
new Variant(new LocalizedText(message)),
|
||||
new Variant((ushort)100),
|
||||
new Variant(DateTime.UtcNow),
|
||||
conditionId,
|
||||
];
|
||||
|
||||
private sealed class Handle : IAlarmSubscriptionHandle
|
||||
{
|
||||
public string DiagnosticId => "g13";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An audit event (no ConditionId, no ActiveState/AckedState) naming an authored alarm source is not alarm
|
||||
/// state: it must not reach the host as an Unspecified transition (which wrote an "Activated" row and replaced
|
||||
/// the condition's message). Positive control: a real condition event for the same source still flows.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void A_non_condition_event_from_an_authored_source_is_dropped_but_a_condition_event_flows()
|
||||
{
|
||||
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-g13");
|
||||
var seen = new List<AlarmEventArgs>();
|
||||
drv.OnAlarmEvent += (_, e) => seen.Add(e);
|
||||
var handle = new Handle();
|
||||
|
||||
drv.RouteAlarmEvent(Fields(ObjectTypeIds.AuditWriteUpdateEventType, Variant.Null, "Write by user"), TripIndex, handle);
|
||||
seen.ShouldBeEmpty("an audit event is not an alarm");
|
||||
|
||||
drv.RouteAlarmEvent(
|
||||
Fields(new NodeId("TripAlarmType", 3), new Variant(NodeId.Parse("ns=3;s=Alarms.Trip1.Cond")), "tripped"),
|
||||
TripIndex, handle);
|
||||
seen.Count.ShouldBe(1, "positive control: a condition event for the same source flows");
|
||||
seen[0].Message.ShouldBe("tripped");
|
||||
}
|
||||
|
||||
// ── G-14 ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
public static TheoryData<uint> PostDispatchFailures =>
|
||||
[
|
||||
StatusCodes.BadRequestTimeout.Code,
|
||||
StatusCodes.BadTimeout.Code,
|
||||
StatusCodes.BadSecureChannelClosed.Code,
|
||||
StatusCodes.BadConnectionClosed.Code,
|
||||
StatusCodes.BadRequestInterrupted.Code,
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// A write that failed after it may have been sent (the SDK's request timeout, a channel closed under it)
|
||||
/// reports <c>BadTimeout</c> ("outcome unknown"), not "did not reach the server". Health is still degraded:
|
||||
/// no reply arrived, which is a comms fault.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[MemberData(nameof(PostDispatchFailures))]
|
||||
public async Task A_write_failing_after_dispatch_reports_BadTimeout(uint status)
|
||||
{
|
||||
var (drv, session) = NewConnectedDriver();
|
||||
using var _ = drv;
|
||||
session.Setup(s => s.WriteAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<WriteValue>>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new ServiceResultException(new StatusCode(status)));
|
||||
|
||||
var results = await drv.WriteAsync([new Core.Abstractions.WriteRequest(SpeedRef, 7)], TestContext.Current.CancellationToken);
|
||||
|
||||
results.Single().StatusCode.ShouldBe(0x800A0000u);
|
||||
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
|
||||
}
|
||||
|
||||
/// <summary>Positive control: a failure that cannot have been sent stays <c>BadCommunicationError</c>.</summary>
|
||||
[Fact]
|
||||
public async Task A_write_failing_before_dispatch_stays_BadCommunicationError()
|
||||
{
|
||||
var (drv, session) = NewConnectedDriver();
|
||||
using var _ = drv;
|
||||
session.Setup(s => s.WriteAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<WriteValue>>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new ServiceResultException(StatusCodes.BadNotConnected));
|
||||
|
||||
var results = await drv.WriteAsync([new Core.Abstractions.WriteRequest(SpeedRef, 7)], TestContext.Current.CancellationToken);
|
||||
|
||||
results.Single().StatusCode.ShouldBe(0x80050000u);
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
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)");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -68,7 +68,7 @@ public sealed class OpcUaClientWriteHealthTests
|
||||
var (drv, session) = NewConnectedDriver(new DriverHealth(DriverState.Healthy, Stale, null));
|
||||
using var _ = drv;
|
||||
session.Setup(s => s.WriteAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<WriteValue>>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new ServiceResultException(StatusCodes.BadConnectionClosed));
|
||||
.ThrowsAsync(new ServiceResultException(StatusCodes.BadNotConnected)); // pre-wire: nothing was sent (G-14: BadConnectionClosed may be post-dispatch)
|
||||
|
||||
var results = await drv.WriteAsync(Write(), TestContext.Current.CancellationToken);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user