221 lines
15 KiB
C#
221 lines
15 KiB
C#
using System.Reflection;
|
|
using System.Threading.Channels;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|
{
|
|
[Theory(Timeout = 90000), Trait("Phase", "P11Renewal")]
|
|
[InlineData("ambiguous")]
|
|
[InlineData("missing_timestamp")]
|
|
[InlineData("different_timestamp")]
|
|
[InlineData("different_status")]
|
|
[InlineData("expired_proof")]
|
|
public async Task Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence(string scenario)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
|
peer = origin;
|
|
subscriptions.SampleClock = origin.Clock;
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
|
|
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var source = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
await client.SetPublishingModeAsync(new RequestHeader(), false, [subscription], ct);
|
|
|
|
var witness = new RenewableTestWitness(source.SourceProof);
|
|
var timestamp = origin.Clock.GetUtcNow().UtcDateTime;
|
|
var snapshot = source.Snapshot with { Value = 42, StatusCode = StatusCodes.BadNoCommunication.Code,
|
|
SourceTimestampUtc = timestamp, ServerTimestampUtc = timestamp };
|
|
var sample = new ProjectedValueWrite(source.Route.Realm, source.Route.LocalIdentifier, source.Route.ProjectionGeneration,
|
|
source.Route.Serving, snapshot, new DataAgeBounds(TimeSpan.Zero, TimeSpan.Zero), origin.Clock.GetTimestamp(), witness, false, 2);
|
|
((IProjectedValueSink)sink).TryPublish([sample]).ShouldBeTrue();
|
|
if (scenario is "ambiguous" or "missing_timestamp")
|
|
((IProjectedValueSink)sink).TryPublish([sample with { Snapshot = snapshot with { Value = 43 }, SourceVersion = 3 }]).ShouldBeTrue();
|
|
|
|
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!;
|
|
candidates.Cast<object>().Count().ShouldBe(scenario is "ambiguous" or "missing_timestamp" ? 2 : 1);
|
|
item.SetMonitoringMode(MonitoringMode.Disabled);
|
|
if (scenario == "different_status")
|
|
{
|
|
// Keep the proved status and the injected status distinct if the
|
|
// SDK samples the node again as publishing resumes.
|
|
item.ModifyAttributes(item.DiagnosticsMasks, TimestampsToReturn.Both, item.ClientHandle,
|
|
item.Filter, item.Filter, null, 0, 8, false).ShouldBeNull();
|
|
}
|
|
item.SetMonitoringMode(MonitoringMode.Reporting);
|
|
if (scenario == "expired_proof") witness.Valid = false;
|
|
var sourceTime = scenario switch
|
|
{
|
|
"missing_timestamp" => DateTimeUtc.MinValue,
|
|
"different_timestamp" => (DateTimeUtc)timestamp.AddSeconds(1),
|
|
_ => (DateTimeUtc)timestamp
|
|
};
|
|
var status = scenario == "different_status" ? StatusCodes.BadTimeout : StatusCodes.BadNoCommunication;
|
|
// Deliberately inject a notification at the public SDK queue boundary;
|
|
// this tests identity fences, not a claim that the SDK creates duplicates.
|
|
var queue = typeof(Opc.Ua.Server.MonitoredItem).GetMethods().Single(x => x.Name == "QueueValue" && x.GetParameters().Length == 3);
|
|
var injectedServerTime = scenario == "different_status" ? (DateTimeUtc)timestamp.AddSeconds(3) : DateTimeUtc.MinValue;
|
|
queue.Invoke(item, [new Opc.Ua.DataValue(Variant.Null, status, sourceTime, injectedServerTime), ServiceResult.Good, true]);
|
|
await client.SetPublishingModeAsync(new RequestHeader(), true, [subscription], ct);
|
|
if (scenario == "different_status")
|
|
{
|
|
// The distinct proven sample can arrive before the injected
|
|
// notification, including in the same Publish response.
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
var provenSampleSeen = false;
|
|
var denialSeen = false;
|
|
while (!denialSeen)
|
|
{
|
|
var response = await client.PublishAsync(new RequestHeader(), default, timeout.Token);
|
|
foreach (var change in ComposedChanges(response.NotificationMessage).Where(change => change.ClientHandle == 1))
|
|
{
|
|
var value = change.Value;
|
|
if (!provenSampleSeen && value.StatusCode == StatusCodes.BadNoCommunication &&
|
|
value.SourceTimestamp == (DateTimeUtc)timestamp && value.WrappedValue.IsNull)
|
|
{
|
|
provenSampleSeen = true;
|
|
continue;
|
|
}
|
|
value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
|
|
value.WrappedValue.IsNull.ShouldBeTrue();
|
|
if (value.ServerTimestamp == injectedServerTime) denialSeen = true;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
var denied = await PublishComposedValue(client, 1, ct);
|
|
denied.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
|
|
denied.WrappedValue.IsNull.ShouldBeTrue();
|
|
}, onPublished: update => published.Writer.TryWrite(update));
|
|
}
|
|
|
|
[Theory(Timeout = 90000), Trait("Phase", "P11Renewal")]
|
|
[InlineData(TimestampsToReturn.Server, false)]
|
|
[InlineData(TimestampsToReturn.Neither, false)]
|
|
[InlineData(TimestampsToReturn.Both, true)]
|
|
public async Task Single_bad_null_sample_without_source_timestamp_keeps_original_witness(
|
|
TimestampsToReturn mode, bool sourceTimestampAbsent)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
|
peer = origin;
|
|
subscriptions.SampleClock = origin.Clock;
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
var created = await client.CreateMonitoredItemsAsync(new RequestHeader(), subscription, mode,
|
|
[new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value },
|
|
MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters
|
|
{ ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true,
|
|
Filter = new ExtensionObject(new DataChangeFilter { Trigger = Opc.Ua.DataChangeTrigger.StatusValueTimestamp }) } }], ct);
|
|
created.Results[0].StatusCode.ShouldBe(StatusCodes.Good);
|
|
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var source = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
var witness = new RenewableTestWitness(source.SourceProof);
|
|
var now = origin.Clock.GetUtcNow().UtcDateTime;
|
|
var snapshot = source.Snapshot with { Value = 42, StatusCode = StatusCodes.BadNoCommunication.Code,
|
|
SourceTimestampUtc = sourceTimestampAbsent ? null : now, ServerTimestampUtc = now };
|
|
var sample = new ProjectedValueWrite(source.Route.Realm, source.Route.LocalIdentifier, source.Route.ProjectionGeneration,
|
|
source.Route.Serving, snapshot, new DataAgeBounds(TimeSpan.Zero, TimeSpan.Zero), origin.Clock.GetTimestamp(), witness, false, 2);
|
|
((IProjectedValueSink)sink).TryPublish([sample]).ShouldBeTrue();
|
|
var delivered = await PublishComposedNotification(client, 1, ct);
|
|
delivered.Value.StatusCode.ShouldBe(StatusCodes.BadNoCommunication);
|
|
delivered.Value.WrappedValue.IsNull.ShouldBeTrue();
|
|
witness.Valid = false;
|
|
var replay = await client.RepublishAsync(new RequestHeader(), subscription, delivered.Sequence, ct);
|
|
var replayed = ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value;
|
|
replayed.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
|
|
replayed.WrappedValue.IsNull.ShouldBeTrue();
|
|
}, onPublished: update => published.Writer.TryWrite(update));
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
|
|
public async Task Bad_source_snapshot_retains_matching_evidence_at_the_sdk_notification_boundary()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
|
peer = origin;
|
|
subscriptions.SampleClock = origin.Clock;
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
var connections = new RenewalConnections(origin) { BadFirstRenewalSnapshot = true };
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
|
|
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
await client.SetPublishingModeAsync(new RequestHeader(), false, [subscription], ct);
|
|
|
|
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
item.ModifyAttributes(item.DiagnosticsMasks, TimestampsToReturn.Both, item.ClientHandle,
|
|
item.Filter, item.Filter, null, 0, 1, true).ShouldBeNull();
|
|
|
|
subscriptions.SnapshotVersion = 2;
|
|
subscriptions.SnapshotValue = 8;
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(9));
|
|
var next = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.SourceVersion == 2, ct);
|
|
next.SourceProof.IsValid.ShouldBeTrue();
|
|
next.Snapshot.StatusCode.ShouldBe(StatusCodes.BadNoCommunication.Code);
|
|
var lossPending = item.GetType().GetField("_queuedLoss", flags)!.GetValue(item) is not null;
|
|
var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!;
|
|
var samples = candidates.Cast<object>().Select(candidate =>
|
|
(ProjectedValueWrite)candidate.GetType().GetProperty("Sample")!.GetValue(candidate)!).ToArray();
|
|
var before = ProjectedDeliveryDiagnostics.Capture();
|
|
var notifications = new Queue<MonitoredItemNotification>();
|
|
var diagnostics = new Queue<DiagnosticInfo>();
|
|
item.Publish(new Opc.Ua.Server.OperationContext(item), notifications, diagnostics, 1, NullLogger.Instance);
|
|
var raw = notifications.ShouldHaveSingleItem().Value;
|
|
var after = ProjectedDeliveryDiagnostics.Capture();
|
|
var shape = $"raw status=0x{raw.StatusCode.Code:X8}, null={raw.WrappedValue.IsNull}, " +
|
|
$"source={raw.SourceTimestamp}, server={raw.ServerTimestamp}, pending loss={lossPending}, " +
|
|
$"candidates={samples.Length}, candidate statuses=[{string.Join(',', samples.Select(s => $"0x{s.Snapshot.StatusCode:X8}"))}], " +
|
|
$"source timestamps=[{string.Join(',', samples.Select(s => s.Snapshot.SourceTimestampUtc?.ToString("O") ?? "absent"))}], " +
|
|
$"unique={after["CandidateUnique"] - before["CandidateUnique"]}, missing={after["CandidateMissing"] - before["CandidateMissing"]}, " +
|
|
$"ambiguous={after["CandidateAmbiguous"] - before["CandidateAmbiguous"]}, " +
|
|
$"binding={after["CurrentBindingRejected"] - before["CurrentBindingRejected"]}, " +
|
|
$"proof={after["CurrentProofRejected"] - before["CurrentProofRejected"]}, " +
|
|
$"marker={after["MarkerAuthorizationRejected"] - before["MarkerAuthorizationRejected"]}";
|
|
(after["CandidateUnique"] - before["CandidateUnique"]).ShouldBe(1, shape);
|
|
raw.StatusCode.ShouldBe(StatusCodes.BadNoCommunication);
|
|
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
|
|
}
|
|
}
|