564 lines
35 KiB
C#
564 lines
35 KiB
C#
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
|
using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
|
|
|
|
[Collection(WarmRedundancyProcessWideCollection.Name)]
|
|
[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
|
|
public sealed class GrpcDataSdkDeliveryWireTests
|
|
{
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task Acknowledged_projected_notification_does_not_poison_the_next_stock_item(bool builtIn)
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync($"ProjectedPool{builtIn}", "None", ct);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
var projected = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
const uint handle = 7;
|
|
var projectedItem = await AddItemAsync(client, sub, projected, handle, 1, ct);
|
|
var first = await PublishDataAsync(client, ct);
|
|
var firstValue = DataChanges(first.NotificationMessage).ShouldHaveSingleItem();
|
|
firstValue.Handle.ShouldBe(handle);
|
|
firstValue.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
firstValue.Value.ClrValue().ShouldBe(1);
|
|
|
|
fixture.Access.Valid = false;
|
|
var sequence = first.NotificationMessage.SequenceNumber;
|
|
var replay = await client.RepublishAsync(H(), sub, sequence, ct);
|
|
var revoked = DataChanges(replay.NotificationMessage).ShouldHaveSingleItem();
|
|
revoked.Handle.ShouldBe(handle);
|
|
revoked.Value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
|
|
revoked.Value.WrappedValue.IsNull.ShouldBeTrue();
|
|
StatusCode.IsGood((await client.DeleteMonitoredItemsAsync(H(), sub, [projectedItem], ct)).Results[0]).ShouldBeTrue();
|
|
|
|
NodeId ordinary;
|
|
object expected;
|
|
if (builtIn)
|
|
{
|
|
const byte level = 91;
|
|
new SdkServiceLevelPublisher(fixture.Rig.Server.CurrentInstance!, NullLogger<SdkServiceLevelPublisher>.Instance).Publish(level);
|
|
ordinary = VariableIds.Server_ServiceLevel;
|
|
expected = level;
|
|
}
|
|
else
|
|
{
|
|
const double value = 42.5;
|
|
var raw = fixture.Rig.EnsureRawVariable("stock", "Double", writable: false);
|
|
fixture.Rig.Sink.WriteValue(raw, value, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw);
|
|
ordinary = Raw(session, raw);
|
|
expected = value;
|
|
}
|
|
await AddItemAsync(client, sub, ordinary, handle, 1, ct);
|
|
|
|
// Hold the pool's next rent so the SDK can return the acknowledged payload to the empty fast slot.
|
|
// Publish handles acknowledgements before renting the notification for the next monitored item.
|
|
var held = (MonitoredItemNotification)MonitoredItemNotificationActivator.Instance.CreateInstance();
|
|
try
|
|
{
|
|
var next = await client.PublishAsync(H(), [new SubscriptionAcknowledgement
|
|
{
|
|
SubscriptionId = sub,
|
|
SequenceNumber = sequence
|
|
}], ct);
|
|
StatusCode.IsGood(next.Results[0]).ShouldBeTrue("the retained mapped notification was acknowledged");
|
|
// A keep-alive cannot consume the stock payload slot.
|
|
if (next.NotificationMessage.NotificationData.Count == 0)
|
|
next = await PublishDataAsync(client, ct);
|
|
var delivered = DataChanges(next.NotificationMessage).ShouldHaveSingleItem();
|
|
delivered.Handle.ShouldBe(handle);
|
|
delivered.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
delivered.Value.ClrValue().ShouldBe(expected);
|
|
}
|
|
finally
|
|
{
|
|
held.Reuse();
|
|
}
|
|
}
|
|
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData("None", false)]
|
|
[InlineData("Warm", false)]
|
|
[InlineData("None", true)]
|
|
[InlineData("Warm", true)]
|
|
public async Task Queued_sample_revoked_before_delivery_is_denied_on_publish_and_republish(string mode, bool rotateSource)
|
|
{
|
|
var ct = Deadline();
|
|
await using var rig = await StartModeAsync("GrpcProjected" + mode, mode, ct);
|
|
if (mode == "Warm") Promote(rig.Server.CreateStandbyProjection()!);
|
|
rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
|
|
var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
|
|
var origin = new DataAddress("origin", "urn:source", "string", "speed");
|
|
var localView = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Speed");
|
|
var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1);
|
|
var metadata = new DataMetadata(localView, "Speed", "Tag", DataValueKind.Int32, -1, [], false,
|
|
DataOperations.Read | DataOperations.Subscribe, 1, null, null, false, Serving: serving);
|
|
var identifier = ProjectedDataIds.Identifier("mapping", origin);
|
|
rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata, 1, () => true), out var projected).ShouldBeTrue();
|
|
var access = new FakeAccess(localView with { MappingId = null, MappingRevision = 0, Subject = "origin/Speed" }, serving);
|
|
rig.Nm.ProjectedDataAccess = access;
|
|
var proof = new SampleProof();
|
|
var sink = (IProjectedValueSink)rig.Sink;
|
|
bool Push(int number) => sink.TryPublish([new(DataRealm.Raw, identifier, 1, serving,
|
|
new DataValueSnapshot(number, StatusCodes.Good.Code, null, null), new(TimeSpan.Zero, TimeSpan.Zero),
|
|
TimeProvider.System.GetTimestamp(), proof)]);
|
|
Push(1).ShouldBeTrue();
|
|
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var node = new NodeId(identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
var itemId = await AddItemAsync(client, sub, node, 7, 10, ct);
|
|
DataChanges((await PublishDataAsync(client, ct)).NotificationMessage).ShouldContain(x => x.Handle == 7 && x.Value.StatusCode == StatusCodes.Good);
|
|
await client.SetPublishingModeAsync(H(), false, [sub], ct);
|
|
Push(42).ShouldBeTrue();
|
|
await client.ModifyMonitoredItemsAsync(H(), sub, TimestampsToReturn.Both, [new MonitoredItemModifyRequest
|
|
{
|
|
MonitoredItemId = itemId, RequestedParameters = new MonitoringParameters { ClientHandle = 9, SamplingInterval = 0, QueueSize = 10, DiscardOldest = true }
|
|
}], ct);
|
|
if (rotateSource)
|
|
{
|
|
proof.Invalidate();
|
|
proof = new SampleProof();
|
|
Push(43).ShouldBeTrue();
|
|
}
|
|
else access.Valid = false;
|
|
await client.SetPublishingModeAsync(H(), true, [sub], ct);
|
|
var delivered = await PublishDataAsync(client, ct);
|
|
var values = DataChanges(delivered.NotificationMessage);
|
|
values.ShouldNotBeEmpty();
|
|
values.ShouldAllBe(x => x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull);
|
|
var replay = await client.RepublishAsync(H(), sub, delivered.NotificationMessage.SequenceNumber, ct);
|
|
DataChanges(replay.NotificationMessage).ShouldAllBe(x => x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull);
|
|
}
|
|
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData("None")]
|
|
[InlineData("Warm")]
|
|
public async Task Deleted_item_with_reused_client_handle_never_reauthorizes_old_republish(string mode)
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("Reuse" + mode, mode, ct);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
var oldItem = await AddItemAsync(client, sub, node, 7, 10, ct);
|
|
var first = await PublishDataAsync(client, ct);
|
|
DataChanges(first.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good);
|
|
await client.DeleteMonitoredItemsAsync(H(), sub, [oldItem], ct);
|
|
await AddItemAsync(client, sub, node, 7, 10, ct);
|
|
var replay = await client.RepublishAsync(H(), sub, first.NotificationMessage.SequenceNumber, ct);
|
|
DataChanges(replay.NotificationMessage).ShouldAllBe(x => x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull);
|
|
}
|
|
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData("None")]
|
|
[InlineData("Warm")]
|
|
public async Task Same_item_recovers_after_fresh_snapshot_but_old_republish_remains_denied(string mode)
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("Recover" + mode, mode, ct);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
await AddItemAsync(client, sub, node, 7, 10, ct);
|
|
var old = await PublishDataAsync(client, ct);
|
|
DataChanges(old.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good);
|
|
fixture.Proof.Invalidate();
|
|
fixture.Proof = new SampleProof();
|
|
fixture.Push(43, completeSnapshot: true).ShouldBeTrue();
|
|
var next = await PublishDataAsync(client, ct);
|
|
DataChanges(next.NotificationMessage).ShouldContain(x => x.Handle == 7 && x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 43));
|
|
var oldReplay = await client.RepublishAsync(H(), sub, old.NotificationMessage.SequenceNumber, ct);
|
|
DataChanges(oldReplay.NotificationMessage).ShouldAllBe(x => x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull);
|
|
}
|
|
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData("None")]
|
|
[InlineData("Warm")]
|
|
public async Task A_newer_sample_cannot_refresh_an_older_queued_samples_age(string mode)
|
|
{
|
|
var ct = Deadline();
|
|
var clock = new TestSampleClock();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("Age" + mode, mode, ct, sampleClock: clock);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 1, true, 0, ct)).SubscriptionId;
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
await AddItemAsync(client, sub, node, 7, 10, ct);
|
|
var initial = DataChanges((await PublishDataAsync(client, ct)).NotificationMessage).ShouldHaveSingleItem();
|
|
initial.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
initial.Value.ClrValue().ShouldBe(1);
|
|
await client.SetPublishingModeAsync(H(), false, [sub], ct);
|
|
var oldTimestamp = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
|
var newTimestamp = oldTimestamp.AddSeconds(1);
|
|
// Both updates enter the real SDK queue while fresh. Advancing the proof clock
|
|
// after the newer sample arrives expires only the old sample at delivery.
|
|
fixture.Push(42, originAge: TimeSpan.FromSeconds(4), sourceTimestamp: oldTimestamp).ShouldBeTrue();
|
|
fixture.Push(43, originAge: TimeSpan.Zero, sourceTimestamp: newTimestamp).ShouldBeTrue();
|
|
clock.Advance(TimeSpan.FromSeconds(2));
|
|
await client.SetPublishingModeAsync(H(), true, [sub], ct);
|
|
var stale = await PublishDataAsync(client, ct);
|
|
AssertDenied(stale.NotificationMessage);
|
|
var replay = await client.RepublishAsync(H(), sub, stale.NotificationMessage.SequenceNumber, ct);
|
|
AssertDenied(replay.NotificationMessage);
|
|
var fresh = await PublishDataAsync(client, ct);
|
|
fresh.NotificationMessage.SequenceNumber.ShouldBe(stale.NotificationMessage.SequenceNumber + 1);
|
|
var row = DataChanges(fresh.NotificationMessage).ShouldHaveSingleItem();
|
|
row.Handle.ShouldBe(7u);
|
|
row.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
row.Value.ClrValue().ShouldBe(43);
|
|
row.Value.SourceTimestamp.ShouldBe((DateTimeUtc)newTimestamp);
|
|
var staleAfterFresh = await client.RepublishAsync(H(), sub, stale.NotificationMessage.SequenceNumber, ct);
|
|
AssertDenied(staleAfterFresh.NotificationMessage);
|
|
}
|
|
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData("None")]
|
|
[InlineData("Warm")]
|
|
public async Task Ambiguous_equal_samples_are_denied_then_recover_with_a_fresh_snapshot(string mode)
|
|
{
|
|
var ct = Deadline();
|
|
var clock = new TestSampleClock();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("Equal" + mode, mode, ct, sampleClock: clock);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
await AddItemAsync(client, sub, node, 7, 10, ct);
|
|
await PublishDataAsync(client, ct);
|
|
await client.SetPublishingModeAsync(H(), false, [sub], ct);
|
|
var equalTimestamp = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
|
// The acquisition ages differ, but either sample would be fresh if selected.
|
|
// Matching value, quality and original timestamp leave the proof ambiguous.
|
|
fixture.Push(42, originAge: TimeSpan.FromSeconds(4), sourceTimestamp: equalTimestamp).ShouldBeTrue();
|
|
fixture.Push(42, originAge: TimeSpan.Zero, sourceTimestamp: equalTimestamp).ShouldBeTrue();
|
|
fixture.Access.BaselineRequests.ShouldBe(0);
|
|
await client.SetPublishingModeAsync(H(), true, [sub], ct);
|
|
var ambiguous = await PublishDataAsync(client, ct);
|
|
AssertDenied(ambiguous.NotificationMessage);
|
|
fixture.Access.BaselineRequests.ShouldBeGreaterThan(0);
|
|
var replay = await client.RepublishAsync(H(), sub, ambiguous.NotificationMessage.SequenceNumber, ct);
|
|
AssertDenied(replay.NotificationMessage);
|
|
var freshTimestamp = equalTimestamp.AddSeconds(1);
|
|
fixture.Push(43, completeSnapshot: true, sourceTimestamp: freshTimestamp).ShouldBeTrue();
|
|
var fresh = await PublishDataAsync(client, ct);
|
|
var rows = DataChanges(fresh.NotificationMessage);
|
|
rows.ShouldNotBeEmpty();
|
|
rows.ShouldAllBe(x => x.Handle == 7 && x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 43) &&
|
|
x.Value.SourceTimestamp == (DateTimeUtc)freshTimestamp);
|
|
var ambiguousAfterFresh = await client.RepublishAsync(H(), sub, ambiguous.NotificationMessage.SequenceNumber, ct);
|
|
AssertDenied(ambiguousAfterFresh.NotificationMessage);
|
|
}
|
|
|
|
private static void AssertDenied(NotificationMessage message)
|
|
{
|
|
var rows = DataChanges(message);
|
|
rows.ShouldNotBeEmpty();
|
|
rows.ShouldAllBe(x => x.Handle == 7 && x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull);
|
|
}
|
|
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData("None")]
|
|
[InlineData("Warm")]
|
|
public async Task Single_slot_overwrite_delivers_only_the_fresh_sample(string mode)
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("OneSlot" + mode, mode, ct);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
await AddItemAsync(client, sub, node, 7, 1, ct);
|
|
await PublishDataAsync(client, ct);
|
|
await client.SetPublishingModeAsync(H(), false, [sub], ct);
|
|
fixture.Push(42, originAge: TimeSpan.FromSeconds(10)).ShouldBeTrue();
|
|
fixture.Push(43, originAge: TimeSpan.Zero).ShouldBeTrue();
|
|
await client.SetPublishingModeAsync(H(), true, [sub], ct);
|
|
var delivered = await PublishDataAsync(client, ct);
|
|
DataChanges(delivered.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 43));
|
|
DataChanges(delivered.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42));
|
|
}
|
|
|
|
[Fact(Timeout = 90000)]
|
|
public async Task Candidate_history_capacity_requests_a_new_snapshot_without_unbounded_retention()
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("HistoryCap", "None", ct);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
await AddItemAsync(client, sub, node, 7, 10, ct);
|
|
await PublishDataAsync(client, ct);
|
|
await client.SetPublishingModeAsync(H(), false, [sub], ct);
|
|
for (var i = 0; i < 1100; i++) fixture.Push(i + 100).ShouldBeTrue();
|
|
fixture.Access.BaselineRequests.ShouldBeGreaterThan(0);
|
|
fixture.Push(2000, completeSnapshot: true).ShouldBeTrue();
|
|
await client.SetPublishingModeAsync(H(), true, [sub], ct);
|
|
var fresh = await PublishDataAsync(client, ct);
|
|
DataChanges(fresh.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 2000));
|
|
}
|
|
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData(DataWriteState.DriverConfirmedSuccess)]
|
|
[InlineData(DataWriteState.OutcomeUnknown)]
|
|
public async Task Mapped_write_returns_rich_remote_outcome_without_optimistic_cache_mutation(DataWriteState state)
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("Write" + state, "None", ct, writable: true);
|
|
fixture.Access.WriteState = state;
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
var result = await client.WriteAsync(H(), [new WriteValue
|
|
{
|
|
NodeId = node, AttributeId = Attributes.Value,
|
|
Value = new Opc.Ua.DataValue(new Variant(42), StatusCodes.Good)
|
|
}], ct);
|
|
fixture.Access.Writes.ShouldBe(1);
|
|
if (state == DataWriteState.DriverConfirmedSuccess) result.Results[0].ShouldBe(StatusCodes.Good);
|
|
else result.Results[0].ShouldBe(StatusCodes.UncertainLastUsableValue);
|
|
var variable = ((Opc.Ua.Server.NodeHandle)fixture.Rig.Nm.GetManagerHandle(node)!).Node.ShouldBeOfType<BaseDataVariableState>();
|
|
variable.Value.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(1);
|
|
}
|
|
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData("None")]
|
|
[InlineData("Warm")]
|
|
public async Task Local_secondary_refuses_mapped_write_before_remote_dispatch(string mode)
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("WriteStandby" + mode, mode, ct, writable: true, promoteWarm: false);
|
|
if (mode == "None") fixture.Rig.Nm.NativeAlarmAckPrimaryGate = () => false;
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
var response = await ((SessionClient)session).WriteAsync(H(), [new WriteValue { NodeId = node, AttributeId = Attributes.Value,
|
|
Value = new Opc.Ua.DataValue(new Variant(42), StatusCodes.Good) }], ct);
|
|
response.Results[0].ShouldBe(StatusCodes.BadInvalidState);
|
|
fixture.Access.Writes.ShouldBe(0);
|
|
}
|
|
|
|
[Theory(Timeout = 90000)]
|
|
[InlineData(true)]
|
|
[InlineData(false)]
|
|
public async Task Unsupported_status_or_timestamp_write_never_dispatches(bool customStatus)
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("WriteMetadata" + customStatus, "None", ct, writable: true);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
var value = new Opc.Ua.DataValue(new Variant(42), customStatus ? StatusCodes.BadOutOfService : StatusCodes.Good,
|
|
customStatus ? DateTimeUtc.MinValue : DateTimeUtc.Now, DateTimeUtc.MinValue);
|
|
var response = await ((SessionClient)session).WriteAsync(H(), [new WriteValue { NodeId = node, AttributeId = Attributes.Value, Value = value }], ct);
|
|
response.Results[0].ShouldBe(StatusCodes.BadWriteNotSupported);
|
|
fixture.Access.Writes.ShouldBe(0);
|
|
}
|
|
|
|
[Fact(Timeout = 90000)]
|
|
public async Task Mixed_write_preserves_legacy_result_and_projected_result_order()
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("MixedWrite", "None", ct, writable: true);
|
|
var localId = fixture.Rig.EnsureRawVariable("local-mixed", "Int32", writable: false);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var mapped = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
var local = Raw(session, localId);
|
|
var response = await ((SessionClient)session).WriteAsync(H(), [
|
|
new WriteValue { NodeId = local, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(7), StatusCodes.Good) },
|
|
new WriteValue { NodeId = mapped, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(42), StatusCodes.Good) }
|
|
], ct);
|
|
StatusCode.IsBad(response.Results[0]).ShouldBeTrue();
|
|
response.Results[1].ShouldBe(StatusCodes.Good);
|
|
fixture.Access.Writes.ShouldBe(1);
|
|
}
|
|
|
|
[Fact(Timeout = 90000)]
|
|
public async Task One_dimensional_byte_array_read_and_subscription_preserve_array_type_and_owned_value()
|
|
{
|
|
var ct = Deadline();
|
|
await using var rig = await StartModeAsync("ProjectedByteArray", "None", ct);
|
|
rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
|
|
var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
|
|
var origin = new DataAddress("origin", "urn:source", "string", "array");
|
|
var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Array");
|
|
var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1);
|
|
var metadata = new DataMetadata(view, "Array", "Variable", DataValueKind.Array, 1, [3], false,
|
|
DataOperations.Read | DataOperations.Subscribe, 1, null, null, false, DataValueKind.UInt8, serving);
|
|
var identifier = ProjectedDataIds.Identifier("mapping", origin);
|
|
rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata, 1, () => true), out _).ShouldBeTrue();
|
|
rig.Nm.ProjectedDataAccess = new FakeAccess(view with { MappingId = null, MappingRevision = 0, Subject = "origin/Array" }, serving);
|
|
var source = new byte[] { 1, 2, 3 };
|
|
var sample = new ProjectedValueWrite(DataRealm.Raw, identifier, 1, serving, new DataValueSnapshot(source, StatusCodes.Good.Code, null, null),
|
|
new(TimeSpan.Zero, TimeSpan.Zero), TimeProvider.System.GetTimestamp(), new SampleProof(), IsCompleteSnapshot: true);
|
|
((IProjectedValueSink)rig.Sink).TryPublish([sample]).ShouldBeTrue();
|
|
source[0] = 99;
|
|
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var node = new NodeId(identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
var read = await client.ReadAsync(H(), 5000, TimestampsToReturn.Both,
|
|
[new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct);
|
|
read.Results[0].StatusCode.ShouldBe(StatusCodes.Good);
|
|
read.Results[0].WrappedValue.TypeInfo.BuiltInType.ShouldBe(BuiltInType.Byte);
|
|
read.Results[0].WrappedValue.TypeInfo.ValueRank.ShouldBe(ValueRanks.OneDimension);
|
|
((byte[])read.Results[0].ClrValue()!).ShouldBe([1, 2, 3]);
|
|
var subscription = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
await AddItemAsync(client, subscription, node, 7, 10, ct);
|
|
var message = await PublishDataAsync(client, ct);
|
|
var delivered = DataChanges(message.NotificationMessage).Single(x => x.Handle == 7).Value;
|
|
delivered.StatusCode.ShouldBe(StatusCodes.Good);
|
|
delivered.WrappedValue.TypeInfo.BuiltInType.ShouldBe(BuiltInType.Byte);
|
|
delivered.WrappedValue.TypeInfo.ValueRank.ShouldBe(ValueRanks.OneDimension);
|
|
((byte[])delivered.ClrValue()!).ShouldBe([1, 2, 3]);
|
|
}
|
|
|
|
[Fact(Timeout = 90000)]
|
|
public async Task Revalidation_keeps_a_live_mapped_item_and_denies_it_after_demand_revocation()
|
|
{
|
|
var ct = Deadline();
|
|
await using var fixture = await DeliveryFixture.CreateAsync("RevalidateMapped", "None", ct);
|
|
using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
await AddItemAsync(client, sub, node, 7, 10, ct);
|
|
await PublishDataAsync(client, ct);
|
|
var authority = new DataPlaneAuthorityState();
|
|
fixture.Rig.Nm.Authorizer = new DataPlaneAuthorizer(authority, new TriePermissionEvaluator(authority.Tries), true, NullLogger.Instance);
|
|
fixture.Rig.Nm.MappedSubjectResolver = (_, _) => MappedNodeResolution.Deny;
|
|
fixture.Rig.Nm.RevalidateMonitoredItems();
|
|
fixture.Push(42).ShouldBeTrue();
|
|
var allowed = await PublishDataAsync(client, ct);
|
|
DataChanges(allowed.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42));
|
|
fixture.Access.Valid = false;
|
|
fixture.Rig.Nm.RevalidateMonitoredItems();
|
|
var denied = await PublishDataAsync(client, ct);
|
|
DataChanges(denied.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good);
|
|
}
|
|
|
|
[Fact(Timeout = 90000)]
|
|
public async Task Removed_mapping_retires_the_original_monitored_item_without_client_deletion()
|
|
{
|
|
var ct = Deadline();
|
|
await using var rig = await StartModeAsync("MappingRetirement", "None", ct);
|
|
rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
|
|
var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
|
|
var origin = new DataAddress("origin", "urn:source", "string", "leaf");
|
|
var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Leaf");
|
|
var identifier = ProjectedDataIds.Identifier("mapping", origin);
|
|
var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, identifier, parent, "Leaf", "Plant/Leaf", "mapping", 1, () => true);
|
|
rig.Nm.TryEnsureProjectedAnchor(anchor, out var anchorId).ShouldBeTrue();
|
|
var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1);
|
|
var metadata = new DataMetadata(view, "Leaf", "Variable", DataValueKind.Int32, -1, [], false,
|
|
DataOperations.Browse | DataOperations.Read | DataOperations.Subscribe, 1, null, null, false, Serving: serving);
|
|
((IProjectedNamespacePageSink)rig.Sink).TryApplyRootLeaf(anchorId!.Value,
|
|
new(DataRealm.Raw, identifier, anchorId.Value, metadata, 1, () => true), () => true).ShouldBeTrue();
|
|
var access = new FakeAccess(view with { MappingId = null, MappingRevision = 0, Subject = "origin/Leaf" }, serving);
|
|
rig.Nm.ProjectedDataAccess = access;
|
|
((IProjectedValueSink)rig.Sink).TryPublish([new(DataRealm.Raw, identifier, 1, serving,
|
|
new DataValueSnapshot(1, StatusCodes.Good.Code, null, null), new(TimeSpan.Zero, TimeSpan.Zero),
|
|
TimeProvider.System.GetTimestamp(), new SampleProof()) { IsCompleteSnapshot = true }]).ShouldBeTrue();
|
|
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
|
var client = (SessionClient)session;
|
|
var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId;
|
|
var node = new NodeId(identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
|
|
await AddItemAsync(client, sub, node, 7, 10, ct);
|
|
await PublishDataAsync(client, ct);
|
|
rig.Nm.TryRemoveProjectedAnchor(anchorId.Value, anchor).ShouldBeTrue();
|
|
access.Disposals.ShouldBeGreaterThan(0, "node removal must retire the item even while the client keeps it alive");
|
|
}
|
|
|
|
private sealed class DeliveryFixture(ServerEventRig rig, string identifier, ServingIdentity serving, FakeAccess access,
|
|
TimeProvider? sampleClock) : IAsyncDisposable
|
|
{
|
|
public ServerEventRig Rig => rig;
|
|
public string Identifier => identifier;
|
|
public FakeAccess Access => access;
|
|
public SampleProof Proof = new(sampleClock);
|
|
public bool Push(int value, bool completeSnapshot = false, TimeSpan? originAge = null, DateTime? sourceTimestamp = null) =>
|
|
((IProjectedValueSink)rig.Sink).TryPublish([
|
|
new ProjectedValueWrite(DataRealm.Raw, identifier, 1, serving,
|
|
new DataValueSnapshot(value, StatusCodes.Good.Code, sourceTimestamp, null),
|
|
new(originAge ?? TimeSpan.Zero, originAge ?? TimeSpan.Zero), Proof.Clock.GetTimestamp(), Proof) { IsCompleteSnapshot = completeSnapshot }
|
|
]);
|
|
public static async Task<DeliveryFixture> CreateAsync(string name, string mode, CancellationToken ct, bool writable = false,
|
|
bool promoteWarm = true, TimeProvider? sampleClock = null)
|
|
{
|
|
var rig = await StartModeAsync(name, mode, ct);
|
|
if (mode == "Warm" && promoteWarm) Promote(rig.Server.CreateStandbyProjection()!);
|
|
rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
|
|
var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
|
|
var origin = new DataAddress("origin", "urn:source", "string", "speed");
|
|
var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Speed");
|
|
var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1);
|
|
var metadata = new DataMetadata(view, "Speed", "Tag", DataValueKind.Int32, -1, [], writable,
|
|
DataOperations.Read | DataOperations.Subscribe | (writable ? DataOperations.Write : DataOperations.None), 1, null, null, false, Serving: serving);
|
|
var identifier = ProjectedDataIds.Identifier("mapping", origin);
|
|
rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata, 1, () => true), out _).ShouldBeTrue();
|
|
var access = new FakeAccess(view with { MappingId = null, MappingRevision = 0, Subject = "origin/Speed" }, serving);
|
|
rig.Nm.ProjectedDataAccess = access;
|
|
var fixture = new DeliveryFixture(rig, identifier, serving, access, sampleClock);
|
|
fixture.Push(1, completeSnapshot: true).ShouldBeTrue();
|
|
return fixture;
|
|
}
|
|
public ValueTask DisposeAsync() => rig.DisposeAsync();
|
|
}
|
|
|
|
private sealed class TestSampleClock : TimeProvider
|
|
{
|
|
private long _ticks;
|
|
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
|
|
public override long GetTimestamp() => Interlocked.Read(ref _ticks);
|
|
public void Advance(TimeSpan value) => Interlocked.Add(ref _ticks, value.Ticks);
|
|
}
|
|
|
|
private sealed class SampleProof(TimeProvider? clock = null) : IProjectedSamplePublicationProof
|
|
{
|
|
public bool IsValid { get; private set; } = true;
|
|
public TimeProvider Clock => clock ?? TimeProvider.System;
|
|
public void Invalidate() => IsValid = false;
|
|
}
|
|
private sealed class FakeAccess(DataView origin, ServingIdentity serving) : IProjectedDataAccess
|
|
{
|
|
public bool Valid = true;
|
|
public int BaselineRequests;
|
|
public int Disposals;
|
|
public int Writes;
|
|
public DataWriteState WriteState = DataWriteState.DriverConfirmedSuccess;
|
|
public bool RequestFreshSnapshot(IProjectedDemandLease demand) { Interlocked.Increment(ref BaselineRequests); return true; }
|
|
public TimeProvider Clock => TimeProvider.System;
|
|
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand)
|
|
{ demand = new Demand(this, origin, serving, nodeId.IdentifierAsString); return Valid; }
|
|
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) { demand.Dispose(); return true; }
|
|
public Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, long requestStartedTimestamp, CancellationToken cancellationToken)
|
|
{ Interlocked.Increment(ref Writes); return Task.FromResult(new DataWriteOutcome(WriteState, WriteState == DataWriteState.DriverConfirmedSuccess ? StatusCodes.Good.Code : StatusCodes.UncertainLastUsableValue.Code, null)); }
|
|
public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) => true;
|
|
}
|
|
private sealed class Demand(FakeAccess owner, DataView view, ServingIdentity serving, string id) : IProjectedDemandLease
|
|
{
|
|
private bool _disposed;
|
|
public DataView OriginView => view;
|
|
public DataRealm Realm => view.Realm;
|
|
public string LocalIdentifier => id;
|
|
public long ProjectionGeneration => 1;
|
|
public TimeSpan MaximumSampleAge => TimeSpan.FromSeconds(5);
|
|
public ServingIdentity Serving => serving;
|
|
public CancellationToken CancellationToken => CancellationToken.None;
|
|
public bool IsValid => !_disposed && owner.Valid;
|
|
public void Dispose() { if (!_disposed) { _disposed = true; Interlocked.Increment(ref owner.Disposals); } }
|
|
}
|
|
}
|