feat: expose mapped raw and uns data through grpc adapters

This commit is contained in:
Joseph Doherty
2026-11-16 20:43:15 -05:00
parent 47960a6d57
commit 8ad03e9c5d
118 changed files with 12645 additions and 227 deletions
@@ -3,6 +3,8 @@ using Serilog;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Host.Engines;
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
@@ -15,6 +17,31 @@ namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
/// </summary>
public sealed class RoslynVirtualTagEvaluatorRunGuardTests
{
private sealed class TrackedLease : IDisposable
{
public int Disposals;
public void Dispose() => Interlocked.Increment(ref Disposals);
}
[Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public async Task Projected_in_process_timeout_holds_lease_until_script_really_finishes()
{
using var sut = new RoslynVirtualTagEvaluator(
NullLogger<RoslynVirtualTagEvaluator>.Instance, NoOpScriptRoot(), TimeSpan.FromMilliseconds(60));
var lease = new TrackedLease();
var now = DateTime.UtcNow;
var inputs = new Dictionary<string, DataValueSnapshot> { ["a"] = new(12, 0, now, now) };
const string script = "var end = System.DateTime.UtcNow.AddSeconds(2); while (System.DateTime.UtcNow < end) { } return ctx.GetTag(\"a\").Value;";
var result = await ((IProjectedVirtualTagEvaluator)sut).EvaluateProjectedAsync("vt-physical", script, inputs, lease);
result.Success.ShouldBeFalse();
result.Reason!.ShouldContain("timed out");
lease.Disposals.ShouldBe(0);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (Volatile.Read(ref lease.Disposals) == 0 && DateTime.UtcNow < deadline)
await Task.Delay(10, TestContext.Current.CancellationToken);
lease.Disposals.ShouldBe(1);
}
private static ScriptRootLogger NoOpScriptRoot() => new(new LoggerConfiguration().CreateLogger());
private const string SpinScript =
@@ -0,0 +1,420 @@
using System.Collections.Concurrent;
using Akka.Actor;
using Akka.Configuration;
using Akka.TestKit.Xunit;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataProjectionRoutingTests : TestKit
{
public GrpcDataProjectionRoutingTests() : base(ConfigurationFactory.ParseString("""
akka.actor.provider = cluster
akka.remote.dot-netty.tcp.hostname = "127.0.0.1"
akka.remote.dot-netty.tcp.port = 0
akka.loglevel = WARNING
""")) { }
private static ProjectedValueRoute Route(string mapping = "mapping", string originIdentifier = "Plant/Value")
{
var id = ProjectedDataIds.Identifier(mapping, new("source", "urn:source/raw", "string", originIdentifier));
return new("grpc-data:connection", ProjectedDataIds.DependencyReference(DataRealm.Raw, id), DataRealm.Raw,
id, 1, new("origin", "boot", "Primary", 1, 1, 1), Guid.NewGuid());
}
private IActorRef Start(RecordingSink sink, IActorRef? mux = null, ActorProjectedValuePublisher? projectedPublisher = null)
{
var publisher = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink: sink));
var acknowledgments = CreateTestProbe();
var fetcher = new EmptyArtifact();
var host = Sys.ActorOf(DriverHostActor.Props(dbFactory: null, localNode: NodeId.Parse("node-a"),
localRoles: new HashSet<string> { "driver" }, dependencyMux: mux, opcUaPublishActor: publisher,
ackRouter: acknowledgments.Ref, fetchAndCacheMode: true, artifactFetcher: fetcher,
projectedPublisher: projectedPublisher));
var revision = RevisionHash.Parse(Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(fetcher.Bytes)));
host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId()));
acknowledgments.ExpectMsg<ApplyAck>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken)
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
return host;
}
private static ProjectedValueUpdate Update(ProjectedValueRoute route, Gate proof, object value) =>
new(route, new(value, 0, null, null), new(TimeSpan.FromSeconds(3), null), proof.Clock.GetTimestamp(), proof);
[Fact(Timeout = 20000)]
public async Task Real_host_routes_immutable_typed_samples_to_sdk_and_exact_dependency_key()
{
var sink = new RecordingSink();
var mux = Sys.ActorOf(DependencyMuxActor.Props());
var subscriber = CreateTestProbe();
var route = Route();
mux.Tell(new DependencyMuxActor.RegisterInterest([route.DependencyReference,
ProjectedDataIds.DependencyReference(DataRealm.Uns, route.LocalIdentifier), "Plant/Value"], subscriber.Ref));
await mux.Ask<ActorIdentity>(new Identify("registered"), TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
IActorRef? host = null;
IActorRef StartOnce() => host ??= Start(sink, mux);
using var broker = new ActorProjectedValuePublisher(() => StartOnce(), _ => true, 8, 1_000_000, TimeProvider.System);
var proof = new Gate();
var bytes = new byte[] { 1, 2 };
broker.TryBind(route).ShouldBeTrue();
broker.TryPublish([Update(route, proof, bytes) with { IsCompleteSnapshot = true }]).ShouldBeTrue();
bytes[0] = 99;
await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var stored = sink.Writes.ShouldHaveSingleItem();
stored.Snapshot.Value.ShouldBeOfType<byte[]>().ShouldBe(new byte[] { 1, 2 });
stored.OriginAgeBounds.Lower.ShouldBe(TimeSpan.FromSeconds(3));
stored.IsCompleteSnapshot.ShouldBeTrue();
stored.Proof.IsValid.ShouldBeTrue();
VirtualTagActor.DependencyValueChanged? dependency = null;
subscriber.ExpectMsg<DependencyMuxActor.ProjectedDependencyWake>(TimeSpan.FromSeconds(5),
cancellationToken: TestContext.Current.CancellationToken).Consume(items => dependency = items.ShouldHaveSingleItem());
dependency.ShouldNotBeNull().TagId.ShouldBe(route.DependencyReference);
proof.Invalidate();
stored.Proof.IsValid.ShouldBeFalse();
AwaitAssert(() => broker.PendingBytes.ShouldBe(0), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
}
[Fact(Timeout = 20000)]
public async Task Replacing_a_live_source_fences_old_witnesses_without_retiring_the_new_source()
{
var sink = new RecordingSink(); var host = Start(sink);
using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System);
var route = Route(); var original = new Gate(); var replacement = new Gate();
broker.TryBind(route).ShouldBeTrue();
broker.TryPublish([Update(route, original, 1)]).ShouldBeTrue();
AwaitAssert(() => sink.Writes.Count.ShouldBe(1), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
var old = sink.Writes.Single().Proof;
broker.TryPublish([Update(route, replacement, 2) with { IsCompleteSnapshot = true }]).ShouldBeTrue();
AwaitAssert(() => sink.Writes.Count.ShouldBe(2), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
var current = sink.Writes.Last().Proof;
original.IsValid.ShouldBeTrue("replacement does not rely on invalidating an external source");
old.IsSourceValid.ShouldBeFalse();
old.IsValid.ShouldBeFalse();
current.IsValid.ShouldBeTrue();
old.Invalidate();
current.IsValid.ShouldBeTrue("retiring the old witness cannot retire its replacement");
}
[Theory(Timeout = 20000)]
[InlineData(false)]
[InlineData(true)]
public void Completed_slot_reuse_cannot_deliver_newer_samples_before_older_queued_samples(bool sdkStage)
{
var host = CreateTestProbe(); var sdk = CreateTestProbe();
using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000, TimeProvider.System);
var route = Route(); var proof = new Gate(); broker.TryBind(route).ShouldBeTrue();
broker.TryPublish([Update(route, proof, 1)]).ShouldBeTrue();
broker.TryPublish([Update(route, proof, 2)]).ShouldBeTrue();
object oldest;
if (sdkStage)
{
var queued = ((Array)Invoke(broker, "TakeQueuedValues", host.Ref)!).Cast<object>().ToArray();
oldest = queued.Single(batch => Value(batch) == 1);
foreach (var batch in queued) Invoke(broker, "EnqueueForSdk", batch, sdk.Ref, null);
}
else
{
var pending = (System.Collections.IEnumerable)typeof(ActorProjectedValuePublisher)
.GetField("_pending", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(broker)!;
oldest = pending.Cast<object>().Single(batch => Value(batch) == 1);
}
Invoke(oldest, "TryBegin").ShouldBe(true);
Invoke(oldest, "Complete", true);
broker.TryPublish([Update(route, proof, 3)]).ShouldBeTrue();
var remaining = ((Array)Invoke(broker, "TakeQueuedValues", host.Ref)!).Cast<object>().ToArray();
if (sdkStage)
{
foreach (var batch in remaining) Invoke(broker, "EnqueueForSdk", batch, sdk.Ref, null);
remaining = ((Array)Invoke(broker, "TakeSdkValues", sdk.Ref)!).Cast<object>().ToArray();
}
remaining.Select(Value).ShouldBe(new[] { 2, 3 });
static object? Invoke(object target, string name, params object?[] arguments) => target.GetType()
.GetMethod(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.Invoke(target, arguments);
static int Value(object batch) => (int)((IReadOnlyList<ProjectedValueWrite>)batch.GetType()
.GetProperty("Writes", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(batch)!)[0].Snapshot.Value!;
}
[Fact(Timeout = 20000)]
public void Paused_host_has_bounded_payload_free_wakeups_after_repeated_cancellations()
{
var host = CreateTestProbe();
using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000, TimeProvider.System);
var route = Route();
var sweep = typeof(ActorProjectedValuePublisher).GetMethod("SweepQueued", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).ShouldNotBeNull();
for (var i = 0; i < 40; i++)
{
var proof = new Gate();
broker.TryBind(route).ShouldBeTrue();
broker.TryPublish([Update(route, proof, new byte[16_384])]).ShouldBeTrue();
proof.Invalidate();
sweep.Invoke(broker, null);
broker.PendingBytes.ShouldBe(0);
}
// One value wake plus one independently coalesced retirement wake at most.
host.ExpectMsg<object>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
host.ExpectMsg<object>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
host.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
}
[Fact(Timeout = 20000)]
public async Task Paused_mux_receives_bounded_wakes_while_sdk_accepts_many_projected_values()
{
var sink = new RecordingSink(); var mux = CreateTestProbe(); var host = Start(sink, mux.Ref);
using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System);
var route = Route(); var proof = new Gate(); broker.TryBind(route).ShouldBeTrue();
for (var i = 0; i < 20; i++)
{
broker.TryPublish([Update(route, proof, new byte[1024])]).ShouldBeTrue();
var expected = i + 1;
AwaitAssert(() => sink.Writes.Count.ShouldBe(expected), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
}
await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
mux.ExpectMsg<object>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
mux.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
}
[Fact(Timeout = 20000)]
public async Task Paused_subscriber_receives_bounded_wakes_after_projected_mux_fanout()
{
var sink = new RecordingSink(); var mux = Sys.ActorOf(DependencyMuxActor.Props()); var subscriber = CreateTestProbe();
var route = Route();
mux.Tell(new DependencyMuxActor.RegisterInterest([route.DependencyReference], subscriber.Ref));
await mux.Ask<ActorIdentity>(new Identify("registered"), TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var host = Start(sink, mux);
using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System);
var proof = new Gate(); broker.TryBind(route).ShouldBeTrue();
for (var i = 0; i < 20; i++)
{
broker.TryPublish([Update(route, proof, new byte[1024])]).ShouldBeTrue();
var expected = i + 1;
AwaitAssert(() => sink.Writes.Count.ShouldBe(expected), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
}
await mux.Ask<ActorIdentity>(new Identify("drained"), TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
subscriber.ExpectMsg<object>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
}
[Fact(Timeout = 20000)]
public async Task Retiring_an_old_stream_owner_cannot_remove_its_replacement()
{
var sink = new RecordingSink();
var host = Start(sink);
using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System);
var old = Route(); var current = old with { PublicationId = Guid.NewGuid() };
broker.TryBind(old).ShouldBeTrue(); broker.TryBind(current).ShouldBeTrue();
broker.Retire(old);
broker.TryPublish([Update(old, new Gate(), 1)]).ShouldBeFalse();
broker.TryPublish([Update(current, new Gate(), 2)]).ShouldBeTrue();
await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
sink.Writes.ShouldHaveSingleItem().Snapshot.Value.ShouldBe(2);
}
[Fact(Timeout = 20000)]
public async Task Disposal_keeps_physical_sink_work_charged_until_it_returns()
{
using var release = new ManualResetEventSlim();
var sink = new RecordingSink { BeforePublish = () => release.Wait(TimeSpan.FromSeconds(10)) };
var host = Start(sink);
using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System);
var route = Route();
var proof = new Gate();
try
{
broker.TryBind(route).ShouldBeTrue();
broker.TryPublish([Update(route, proof, 42)]).ShouldBeTrue();
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var held = broker.PendingBytes;
held.ShouldBeGreaterThan(0);
broker.Dispose();
broker.PendingBytes.ShouldBe(held);
release.Set();
AwaitAssert(() => broker.PendingBytes.ShouldBe(0), TimeSpan.FromSeconds(5),
cancellationToken: TestContext.Current.CancellationToken);
sink.Writes.ShouldBeEmpty();
}
finally { release.Set(); }
}
[Fact(Timeout = 15000)]
public void Retiring_repeated_owners_of_one_view_coalesces_the_host_wakeup()
{
var host = CreateTestProbe();
using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 2, 1_000_000, TimeProvider.System);
var first = Route();
for (var i = 0; i < 100; i++)
{
var route = first with { PublicationId = Guid.NewGuid() };
broker.TryBind(route).ShouldBeTrue();
broker.Retire(route);
}
host.ExpectMsg<object>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
host.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken);
}
[Fact(Timeout = 20000)]
public void New_host_activation_drains_retained_retirement_and_restores_admission()
{
var oldHost = CreateTestProbe();
IActorRef host = oldHost.Ref;
using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 1, 1_000_000, TimeProvider.System);
var old = Route();
broker.TryBind(old).ShouldBeTrue();
broker.Retire(old);
oldHost.ExpectMsg<object>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
var next = Route("next-mapping");
broker.TryBind(next).ShouldBeFalse();
host = Start(new RecordingSink(), projectedPublisher: broker);
AwaitAssert(() => broker.TryBind(next).ShouldBeTrue(), TimeSpan.FromSeconds(5),
cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public void Route_and_retirement_residency_respects_a_byte_limit_independently_of_route_count()
{
var host = CreateTestProbe();
using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000,
TimeProvider.System, maximumControlBytes: 8192);
var large = Route(originIdentifier: new string('x', 8192));
large.DependencyReference.Length.ShouldBeGreaterThan(8192);
broker.TryBind(large).ShouldBeFalse();
broker.TryBind(Route()).ShouldBeTrue();
}
[Fact(Timeout = 20000)]
public async Task Ordinary_deltas_keep_the_same_live_source_witness_at_the_sdk_boundary()
{
var sink = new RecordingSink();
var host = Start(sink);
using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System);
var route = Route();
var proof = new Gate();
broker.TryBind(route).ShouldBeTrue();
broker.TryPublish([Update(route, proof, 1)]).ShouldBeTrue();
await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
broker.TryPublish([Update(route, proof, 2)]).ShouldBeTrue();
AwaitAssert(() => sink.Writes.Count.ShouldBe(2), TimeSpan.FromSeconds(5),
cancellationToken: TestContext.Current.CancellationToken);
var values = sink.Writes.ToArray();
values[0].Proof.SourceIdentity.ShouldBeSameAs(values[1].Proof.SourceIdentity);
proof.Invalidate();
values.ShouldAllBe(value => !value.Proof.IsValid);
}
[Fact(Timeout = 20000)]
public async Task A_new_sample_cannot_freshen_an_older_queued_sample_from_the_same_source()
{
var clock = new TestClock();
var sink = new RecordingSink();
var host = Start(sink);
using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, clock);
var route = Route();
var proof = new Gate(clock);
ProjectedValueUpdate Sample(int value) => new(route, new(value, 0, null, null),
new(TimeSpan.Zero, TimeSpan.Zero), clock.GetTimestamp(), proof, MaximumSampleAge: TimeSpan.FromSeconds(5));
broker.TryBind(route).ShouldBeTrue();
broker.TryPublish([Sample(1)]).ShouldBeTrue();
await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var old = sink.Writes.ShouldHaveSingleItem();
clock.Advance(TimeSpan.FromSeconds(6));
old.Proof.IsSourceValid.ShouldBeTrue();
old.Proof.IsValid.ShouldBeFalse();
broker.TryPublish([Sample(2)]).ShouldBeTrue();
AwaitAssert(() => sink.Writes.Count.ShouldBe(2), TimeSpan.FromSeconds(5),
cancellationToken: TestContext.Current.CancellationToken);
var current = sink.Writes.Last();
current.Proof.SourceIdentity.ShouldBeSameAs(old.Proof.SourceIdentity);
current.Proof.IsValid.ShouldBeTrue();
old.Proof.IsValid.ShouldBeFalse();
}
[Fact]
public void An_unknown_upper_age_bound_cannot_prove_finite_freshness()
{
var host = CreateTestProbe();
using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000, TimeProvider.System);
var route = Route();
broker.TryBind(route).ShouldBeTrue();
broker.TryPublish([Update(route, new Gate(), 1) with
{
OriginAgeBounds = new(TimeSpan.Zero, null), MaximumSampleAge = TimeSpan.FromSeconds(5)
}]).ShouldBeFalse();
}
[Fact]
public void Larger_replacement_route_metadata_cannot_bypass_its_control_byte_limit()
{
var host = CreateTestProbe();
using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000,
TimeProvider.System, maximumControlBytes: 8192);
var route = Route();
broker.TryBind(route).ShouldBeTrue();
var held = broker.RetainedControlBytes;
var replacement = route with { PublicationId = Guid.NewGuid(),
Serving = route.Serving with { Incarnation = new string('x', 100_000) } };
broker.TryBind(replacement).ShouldBeFalse();
broker.RetainedControlBytes.ShouldBe(held);
}
private sealed class Gate(TimeProvider? clock = null) : IProjectedSamplePublicationProof
{
private int _valid = 1;
public bool IsValid => Volatile.Read(ref _valid) != 0;
public TimeProvider Clock => clock ?? TimeProvider.System;
public void Invalidate() => Interlocked.Exchange(ref _valid, 0);
}
private sealed class TestClock : TimeProvider
{
private long _ticks;
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
public override long GetTimestamp() => Volatile.Read(ref _ticks);
public override DateTimeOffset GetUtcNow() => DateTimeOffset.UnixEpoch.AddTicks(GetTimestamp());
internal void Advance(TimeSpan elapsed) => Interlocked.Add(ref _ticks, elapsed.Ticks);
}
private sealed class EmptyArtifact : IDeploymentArtifactFetcher
{
internal readonly byte[] Bytes = System.Text.Encoding.UTF8.GetBytes("{\"DriverInstances\":[]}");
public Task<byte[]?> FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken cancellationToken) =>
Task.FromResult<byte[]?>(Bytes);
}
private sealed class RecordingSink : IOpcUaAddressSpaceSink, IProjectedValueSink
{
internal readonly ConcurrentQueue<ProjectedValueWrite> Writes = new();
internal readonly TaskCompletionSource Completed = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal Action? BeforePublish { get; init; }
public bool TryPublish(IReadOnlyList<ProjectedValueWrite> values)
{
Entered.TrySetResult();
BeforePublish?.Invoke();
if (values.Any(value => !value.Proof.IsValid)) return false;
foreach (var value in values) Writes.Enqueue(value);
Completed.TrySetResult(); return true;
}
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { }
public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { }
public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { }
public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { }
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { }
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { }
public void RebuildAddressSpace() { }
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { }
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
}
}
@@ -22,6 +22,7 @@ using Microsoft.Extensions.Hosting;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
@@ -29,6 +30,32 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
public sealed class GrpcDataRuntimeRegistrationTests
{
[Fact, Trait("Phase", "P08")]
public async Task Projection_services_share_the_live_deployed_connection_and_catalog_graph()
{
var services = new ServiceCollection();
services.AddSingleton<IClusterRoleInfo>(new LocalRole());
services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService<DataWriteDispatchFence>()));
services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService<DataWriteDispatchFence>()));
services.AddSingleton<IPermissionEvaluator>(sp => new TriePermissionEvaluator(sp.GetRequiredService<DataPlaneAuthorityState>().Tries));
services.AddSingleton<ISecretStore>(new GrpcDataSecretProvisioningTests.MemoryStore());
services.AddSingleton<ISecretCipher>(new GrpcDataSecretProvisioningTests.TestCipher());
services.AddSingleton<ISecretCacheInvalidator>(new GrpcDataSecretProvisioningTests.NoopInvalidator());
services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true);
await using var provider = services.BuildServiceProvider();
var resolver = provider.GetRequiredService<RemoteNamespaceResolver>();
provider.GetRequiredService<IFederatedProjectionCatalog>().ShouldBeSameAs(resolver);
provider.GetRequiredService<IGrpcDataAdapterConnectionSource>()
.ShouldBeSameAs(provider.GetRequiredService<DeployedGrpcDataConnectionSource>());
provider.GetRequiredService<ProjectedMappingDeploymentRuntime>().Active.ShouldBeEmpty();
provider.GetRequiredService<IProjectedValuePublisher>()
.ShouldBeSameAs(provider.GetRequiredService<ActorProjectedValuePublisher>());
provider.GetRequiredService<IProjectedDataAccess>().ShouldNotBeNull();
provider.GetRequiredService<IConfiguredProjectionDiscovery>().ShouldNotBeNull();
provider.GetRequiredService<IProjectedDependencyInterestSink>()
.ShouldBeSameAs(provider.GetRequiredService<ConfiguredProjectedInterestOwner>());
}
[Fact]
public void Disabled_registration_requires_no_driver_or_secret_store_and_exposes_no_facade()
{
@@ -4,6 +4,7 @@ using Serilog;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.Host.Engines;
@@ -34,6 +35,48 @@ public sealed class RoslynVirtualTagEvaluatorScriptRunnerTests
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => ["vt-q"];
}
private sealed class RetainedLease : IDisposable
{
public int Disposed;
public void Dispose() => Interlocked.Increment(ref Disposed);
}
private sealed class PhysicalRunner : IPhysicalScriptRunner
{
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ScriptInvocation? Invocation;
public void Release() => _release.TrySetResult();
public async Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
{
Invocation = invocation;
try { await _release.Task; return ScriptRunOutcome.Ok(42); }
finally { invocation.PhysicalLease?.Dispose(); }
}
public void Reset(ScriptContextKind kind) { }
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => [];
}
[Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public async Task Projected_run_transfers_physical_lease_to_the_worker_until_completion()
{
var runner = new PhysicalRunner();
using var sut = Build(runner);
var lease = new RetainedLease();
try
{
var run = ((IProjectedVirtualTagEvaluator)(object)sut).EvaluateProjectedAsync("vt", "return (int)ctx.GetTag(\"a\").Value + 1;", Deps(41), lease);
var deadline = DateTime.UtcNow.AddSeconds(5);
while (runner.Invocation is null && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken);
runner.Invocation.ShouldNotBeNull();
runner.Invocation.PhysicalLease.ShouldNotBeNull();
lease.Disposed.ShouldBe(0);
runner.Release();
(await run).Value.ShouldBe(42);
lease.Disposed.ShouldBe(1);
}
finally { runner.Release(); }
}
private static RoslynVirtualTagEvaluator Build(IScriptRunner? runner) =>
new(NullLogger<RoslynVirtualTagEvaluator>.Instance, new ScriptRootLogger(new LoggerConfiguration().CreateLogger()),
runTimeout: TimeSpan.FromMilliseconds(1500), scriptRunner: runner);
@@ -0,0 +1,209 @@
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataSdkBrowseWireTests
{
[Fact(Timeout = 90000)]
public async Task BrowseNext_is_session_bound_and_rechecks_page_authority_before_each_child()
{
var ct = Deadline();
await using var rig = await StartModeAsync("ProjectedBrowseCursor", "None", ct);
rig.Server.SetProjectedBrowseLimits(maxCursors: 1, maxBytes: 8 * 1024 * 1024);
rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var root = new DataAddress("origin", "urn:raw", "string", "root");
var anchorDefinition = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root),
parent, "Remote", "Plant/Remote", "mapping", 1, () => true);
rig.Nm.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue();
var children = new List<NodeId>();
foreach (var name in new[] { "First", "Second", "Third" })
{
var origin = root with { Identifier = name };
var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Remote/" + name);
var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Int32, -1, [], false,
DataOperations.Browse | DataOperations.Read, 1, null, null, false);
rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), anchor!.Value,
metadata, 1, () => true), out var child).ShouldBeTrue();
children.Add(child!.Value);
}
var pages = new BrowsePages(children);
rig.Nm.ProjectedBrowseAccess = pages;
var access = new BrowseOnlyAccess();
rig.Nm.ProjectedDataAccess = access;
using var first = await rig.ConnectAsync(anonymous: false, ct);
using var second = await rig.ConnectAsync(anonymous: false, ct);
var firstClient = (SessionClient)first;
var secondClient = (SessionClient)second;
var result = await firstClient.BrowseAsync(H(), null, 1, [new BrowseDescription
{
NodeId = anchor!.Value, BrowseDirection = BrowseDirection.Forward, IncludeSubtypes = true,
ResultMask = (uint)BrowseResultMask.All,
}], ct);
StatusCode.IsGood(result.Results[0].StatusCode).ShouldBeTrue();
result.Results[0].References.Count.ShouldBe(1);
var cursor = result.Results[0].ContinuationPoint;
cursor.IsEmpty.ShouldBeFalse();
var stolen = await secondClient.BrowseNextAsync(H(), false, [cursor], ct);
stolen.Results[0].StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid);
var next = await firstClient.BrowseNextAsync(H(), false, [cursor], ct);
StatusCode.IsGood(next.Results[0].StatusCode).ShouldBeTrue();
next.Results[0].References.Count.ShouldBe(1);
var replacement = next.Results[0].ContinuationPoint;
replacement.IsEmpty.ShouldBeFalse("the claimed cursor must reuse its reservation at the configured count limit");
access.OnAcquire = () => pages.Valid = false;
var resumed = await firstClient.BrowseNextAsync(H(), false, [replacement], ct);
StatusCode.IsBad(resumed.Results[0].StatusCode).ShouldBeTrue();
resumed.Results[0].References.Count.ShouldBe(0);
}
[Fact(Timeout = 90000)]
public async Task Mapped_browse_honors_direction_class_mask_and_result_mask()
{
var ct = Deadline();
await using var rig = await StartModeAsync("ProjectedBrowseFilters", "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:raw", "string", "root");
var definition = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), parent,
"Remote", "Plant/Remote", "mapping", 1, () => true);
rig.Nm.TryEnsureProjectedAnchor(definition, out var anchor).ShouldBeTrue();
var childOrigin = origin with { Identifier = "child" };
var childView = new DataView(childOrigin, DataRealm.Raw, "mapping", 1, "Plant/Remote/Child");
var metadata = new DataMetadata(childView, "Child", "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false);
rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", childOrigin), anchor!.Value,
metadata, 1, () => true), out var child).ShouldBeTrue();
rig.Nm.ProjectedBrowseAccess = new BrowsePages([child!.Value]);
rig.Nm.ProjectedDataAccess = new BrowseOnlyAccess();
using var session = await rig.ConnectAsync(anonymous: false, ct);
var client = (SessionClient)session;
async Task<BrowseResult> Browse(BrowseDirection direction, NodeId referenceType, uint classMask, uint resultMask)
{
var reply = await client.BrowseAsync(H(), null, 10, [new BrowseDescription { NodeId = anchor.Value,
BrowseDirection = direction, ReferenceTypeId = referenceType, IncludeSubtypes = true,
NodeClassMask = classMask, ResultMask = resultMask }], ct);
return reply.Results[0];
}
var objects = await Browse(BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, (uint)NodeClass.Object, (uint)BrowseResultMask.All);
StatusCode.IsGood(objects.StatusCode).ShouldBeTrue();
objects.References.Count.ShouldBe(0);
var variables = await Browse(BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, (uint)NodeClass.Variable, 0);
StatusCode.IsGood(variables.StatusCode).ShouldBeTrue();
variables.References.Count.ShouldBe(1);
variables.References[0].BrowseName.IsNull.ShouldBeTrue();
variables.References[0].NodeClass.ShouldBe(NodeClass.Unspecified);
var inverse = await Browse(BrowseDirection.Inverse, ReferenceTypeIds.Organizes, 0, (uint)BrowseResultMask.All);
StatusCode.IsGood(inverse.StatusCode).ShouldBeTrue();
inverse.References.ToArray()!.ShouldContain(reference => reference.NodeId == new ExpandedNodeId(parent) && !reference.IsForward);
var noMatch = await Browse(BrowseDirection.Forward, ReferenceTypeIds.HasTypeDefinition, 0, (uint)BrowseResultMask.All);
StatusCode.IsGood(noMatch.StatusCode).ShouldBeTrue();
noMatch.References.Count.ShouldBe(0);
}
[Fact(Timeout = 90000)]
public async Task Cursor_expiring_during_a_remote_fetch_cannot_publish_or_be_replaced()
{
var ct = Deadline();
await using var rig = await StartModeAsync("ProjectedCursorExpiry", "None", ct);
rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var root = new DataAddress("origin", "urn:raw", "string", "root");
var anchorDefinition = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root), parent,
"Remote", "Plant/Remote", "mapping", 1, () => true);
rig.Nm.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue();
var children = new List<NodeId>();
foreach (var name in new[] { "First", "Second" })
{
var origin = root with { Identifier = name };
var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Remote/" + name);
var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false);
rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), anchor!.Value,
metadata, 1, () => true), out var child).ShouldBeTrue();
children.Add(child!.Value);
}
var clock = new TestMonotonicClock();
var pages = new BlockingPages(children);
rig.Nm.ProjectedBrowseClock = clock;
rig.Nm.ProjectedBrowseAccess = pages;
rig.Nm.ProjectedDataAccess = new BrowseOnlyAccess();
using var session = await rig.ConnectAsync(anonymous: false, ct);
var client = (SessionClient)session;
var first = await client.BrowseAsync(H(), null, 1, [new BrowseDescription { NodeId = anchor!.Value,
BrowseDirection = BrowseDirection.Forward, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All }], ct);
var token = first.Results[0].ContinuationPoint;
token.IsEmpty.ShouldBeFalse();
var next = client.BrowseNextAsync(H(), false, [token], ct).AsTask();
try
{
await pages.FetchEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
clock.Advance(TimeSpan.FromSeconds(61));
}
finally { pages.Release.TrySetResult(); }
var result = await next.WaitAsync(TimeSpan.FromSeconds(10), ct);
StatusCode.IsBad(result.Results[0].StatusCode).ShouldBeTrue();
result.Results[0].References.Count.ShouldBe(0);
result.Results[0].ContinuationPoint.IsEmpty.ShouldBeTrue();
var retry = await client.BrowseNextAsync(H(), false, [token], ct);
retry.Results[0].StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid);
}
private sealed class TestMonotonicClock : 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 BlockingPages(IReadOnlyList<NodeId> children) : IProjectedBrowseAccess
{
public TaskCompletionSource FetchEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context) => ProjectedBrowseReadiness.Ready;
public async Task<ProjectedBrowsePage> WaitForPageAsync(ProjectedBrowsePageRequest request, CancellationToken cancellationToken)
{
if (request.Cursor is null) return new(ProjectedBrowseReadiness.Ready, [children[0]], "next", false, () => true);
FetchEntered.TrySetResult();
await Release.Task.WaitAsync(cancellationToken);
return new(ProjectedBrowseReadiness.Ready, [children[1]], null, true, () => true);
}
}
private sealed class BrowsePages(IReadOnlyList<NodeId> children) : IProjectedBrowseAccess
{
public bool Valid = true;
public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context) => ProjectedBrowseReadiness.Ready;
public ProjectedBrowsePage GetOrSchedulePage(ProjectedBrowsePageRequest request) =>
new(ProjectedBrowseReadiness.Ready, children, null, true, () => Valid);
}
private sealed class BrowseOnlyAccess : IProjectedDataAccess
{
public Action? OnAcquire;
public TimeProvider Clock => TimeProvider.System;
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand)
{ OnAcquire?.Invoke(); demand = new BrowseDemand(); return operation == DataOperations.Browse; }
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) => false;
public Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, long requestStartedTimestamp, CancellationToken cancellationToken) => throw new NotSupportedException();
public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) => false;
}
private sealed class BrowseDemand : IProjectedDemandLease
{
public DataView OriginView { get; } = new(new("origin", "urn:raw", "string", "root"), DataRealm.Raw, null, 0, "root");
public DataRealm Realm => DataRealm.Raw;
public string LocalIdentifier => "unused";
public long ProjectionGeneration => 1;
public TimeSpan MaximumSampleAge => TimeSpan.FromSeconds(5);
public ServingIdentity Serving { get; } = new("node", "boot", "Primary", 1, 1, 1);
public CancellationToken CancellationToken => CancellationToken.None;
public bool IsValid => true;
public void Dispose() { }
}
}
@@ -0,0 +1,449 @@
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;
[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataSdkDeliveryWireTests
{
[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();
await using var fixture = await DeliveryFixture.CreateAsync("Age" + 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);
await PublishDataAsync(client, ct);
await client.SetPublishingModeAsync(H(), false, [sub], ct);
fixture.Push(42, originAge: TimeSpan.FromSeconds(10)).ShouldBeTrue();
await Task.Delay(TimeSpan.FromMilliseconds(150), ct);
fixture.Push(43, originAge: TimeSpan.Zero).ShouldBeTrue();
await Task.Delay(TimeSpan.FromMilliseconds(150), ct);
await client.SetPublishingModeAsync(H(), true, [sub], ct);
var delivered = await PublishDataAsync(client, ct);
var values = DataChanges(delivered.NotificationMessage);
values.Count.ShouldBeGreaterThanOrEqualTo(2, "both queued samples must reach this delivery for the age check to be meaningful");
values.ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42));
var replay = await client.RepublishAsync(H(), sub, delivered.NotificationMessage.SequenceNumber, ct);
DataChanges(replay.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42));
}
[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();
await using var fixture = await DeliveryFixture.CreateAsync("Equal" + 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);
await PublishDataAsync(client, ct);
await client.SetPublishingModeAsync(H(), false, [sub], ct);
fixture.Push(42, originAge: TimeSpan.FromSeconds(10)).ShouldBeTrue();
await Task.Delay(TimeSpan.FromMilliseconds(150), ct);
fixture.Push(42, originAge: TimeSpan.Zero).ShouldBeTrue();
await Task.Delay(TimeSpan.FromMilliseconds(150), ct);
await client.SetPublishingModeAsync(H(), true, [sub], ct);
var ambiguous = await PublishDataAsync(client, ct);
DataChanges(ambiguous.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42));
fixture.Access.BaselineRequests.ShouldBeGreaterThan(0);
fixture.Push(43, completeSnapshot: true).ShouldBeTrue();
var fresh = await PublishDataAsync(client, ct);
DataChanges(fresh.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 43));
var replay = await client.RepublishAsync(H(), sub, ambiguous.NotificationMessage.SequenceNumber, ct);
DataChanges(replay.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42));
}
[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) : IAsyncDisposable
{
public ServerEventRig Rig => rig;
public string Identifier => identifier;
public FakeAccess Access => access;
public SampleProof Proof = new();
public bool Push(int value, bool completeSnapshot = false, TimeSpan? originAge = null) => ((IProjectedValueSink)rig.Sink).TryPublish([
new ProjectedValueWrite(DataRealm.Raw, identifier, 1, serving, new DataValueSnapshot(value, StatusCodes.Good.Code, null, null),
new(originAge ?? TimeSpan.Zero, originAge ?? TimeSpan.Zero), TimeProvider.System.GetTimestamp(), Proof) { IsCompleteSnapshot = completeSnapshot }
]);
public static async Task<DeliveryFixture> CreateAsync(string name, string mode, CancellationToken ct, bool writable = false, bool promoteWarm = true)
{
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);
fixture.Push(1, completeSnapshot: true).ShouldBeTrue();
return fixture;
}
public ValueTask DisposeAsync() => rig.DisposeAsync();
}
private sealed class SampleProof : IProjectedSamplePublicationProof
{
public bool IsValid { get; private set; } = true;
public TimeProvider 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); } }
}
}
@@ -0,0 +1,37 @@
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataCandidateBudgetTests
{
[Fact]
public void Aggregate_pressure_rejects_a_second_item_until_the_first_releases_its_charge()
{
var budget = new ProjectedCandidateBudget(maxEntries: 2, maxBytes: 512);
budget.TryReserve(384, out var firstItem).ShouldBeTrue();
budget.TryReserve(256, out var blockedSecondItem).ShouldBeFalse();
blockedSecondItem.ShouldBeNull();
budget.RetainedBytes.ShouldBe(384);
budget.RetainedEntries.ShouldBe(1);
firstItem!.Dispose();
firstItem.Dispose();
budget.RetainedBytes.ShouldBe(0);
budget.RetainedEntries.ShouldBe(0);
budget.TryReserve(256, out var secondItem).ShouldBeTrue();
secondItem!.Dispose();
budget.RetainedBytes.ShouldBe(0);
}
[Fact]
public void Entry_limit_is_shared_even_for_small_values()
{
var budget = new ProjectedCandidateBudget(maxEntries: 1, maxBytes: 4096);
budget.TryReserve(1, out var first).ShouldBeTrue();
budget.TryReserve(1, out _).ShouldBeFalse();
first!.Dispose();
budget.TryReserve(1, out var next).ShouldBeTrue();
next!.Dispose();
}
}
@@ -113,6 +113,17 @@ public sealed class GrpcDataMappedSubjectTests : IDisposable
finally { await host.DisposeAsync(); }
}
[Fact]
public void Mapped_classifier_uses_the_actual_namespace_not_a_local_identifier_that_looks_opaque()
{
var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Read);
f.Gate.MappedSubjectResolver = (_, _) => MappedNodeResolution.Deny;
f.Gate.MappedNamespacePredicate = id => id.NamespaceIndex == 3;
var sameIdentifier = "p1.canonical-looking";
f.Gate.AuthorizeIfRequired(f.Identity, OpcUaOperation.Read, new NodeId(sameIdentifier, 2), AddressSpaceRealm.Raw).ShouldBeNull();
f.Gate.AuthorizeIfRequired(f.Identity, OpcUaOperation.Read, new NodeId(sameIdentifier, 3), AddressSpaceRealm.Raw).ShouldNotBeNull();
}
[Fact]
public void Cached_allow_rechecks_original_key_version_principal_and_expiry()
{
@@ -0,0 +1,39 @@
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataProjectedNodeLifetimeTests
{
[Fact]
public void Active_pin_blocks_idle_retirement_and_forced_retirement_invalidates_it()
{
var lifetime = new ProjectedNodeLifetime();
lifetime.TryPin(out var pin).ShouldBeTrue();
pin.ShouldNotBeNull();
lifetime.TryRetire().ShouldBeFalse();
pin.IsValid.ShouldBeTrue();
lifetime.ForceRetire();
pin.IsValid.ShouldBeFalse();
lifetime.TryPin(out _).ShouldBeFalse();
pin.Dispose();
}
[Fact(Timeout = 15000)]
public async Task Concurrent_acquisition_and_idle_prune_have_only_one_winner()
{
for (var i = 0; i < 64; i++)
{
var lifetime = new ProjectedNodeLifetime();
using var start = new Barrier(2);
var acquire = Task.Run(() => { start.SignalAndWait(); return lifetime.TryPin(out var pin) ? pin : null; }, TestContext.Current.CancellationToken);
var retire = Task.Run(() => { start.SignalAndWait(); return lifetime.TryRetire(); }, TestContext.Current.CancellationToken);
var pin = await acquire.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var retired = await retire.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
(pin is not null).ShouldBe(!retired);
if (pin is not null) { pin.IsValid.ShouldBeTrue(); pin.Dispose(); lifetime.TryRetire().ShouldBeTrue(); }
lifetime.TryPin(out _).ShouldBeFalse();
}
}
}
@@ -0,0 +1,103 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataSdkBrowseReadinessTests : IDisposable
{
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-projected-browse-{Guid.NewGuid():N}");
[Theory]
[InlineData(ProjectedBrowseReadiness.Pending)]
[InlineData(ProjectedBrowseReadiness.Unavailable)]
public async Task Actual_sdk_browse_reports_the_selected_parents_state_even_when_acl_is_off(ProjectedBrowseReadiness state)
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ProjectedBrowse", ApplicationUri = $"urn:ProjectedBrowse:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
try
{
var manager = started.Server.NodeManager!;
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
manager.EnsureFolder("Plant/Mount", "Plant", "Mount", AddressSpaceRealm.Raw);
manager.EnsureFolder("Plant/Local", "Plant", "Local", AddressSpaceRealm.Raw);
var localParent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var parent = manager.TryGetFolder("Plant/Mount", AddressSpaceRealm.Raw)!.NodeId;
manager.ProjectedBrowseReadiness = id => id == parent ? state : ProjectedBrowseReadiness.Ready;
var localPoint = new ContinuationPoint { NodeToBrowse = manager.GetManagerHandle(localParent)!, BrowseDirection = BrowseDirection.Forward,
IncludeSubtypes = true, ResultMask = BrowseResultMask.All };
var localReferences = new List<ReferenceDescription>();
var context = new OperationContext(new RequestHeader(), null, RequestType.Browse, RequestLifetime.None, (IUserIdentity?)null);
manager.Browse(context, ref localPoint, localReferences);
localReferences.Select(r => r.DisplayName.Text).ShouldContain("Local");
localReferences.Select(r => r.DisplayName.Text).ShouldContain("Mount");
localPoint?.Dispose();
var point = new ContinuationPoint { NodeToBrowse = manager.GetManagerHandle(parent)!, BrowseDirection = BrowseDirection.Forward,
IncludeSubtypes = true, ResultMask = BrowseResultMask.All };
try
{
var originalPoint = point;
var error = Should.Throw<ServiceResultException>(() => manager.Browse(context, ref point, new List<ReferenceDescription>()));
error.StatusCode.Code.ShouldBe(state == ProjectedBrowseReadiness.Pending
? StatusCodes.BadWaitingForInitialData.Code : StatusCodes.BadNoCommunication.Code);
point.ShouldBeSameAs(originalPoint);
}
finally { point?.Dispose(); }
}
finally { await started.Host.DisposeAsync(); }
}
[Fact]
public async Task Browse_passes_the_original_caller_and_continuation_to_the_nonblocking_projection_scheduler()
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ProjectedBrowseIdentity", ApplicationUri = $"urn:ProjectedBrowseIdentity:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
try
{
var manager = started.Server.NodeManager!;
manager.EnsureFolder("Mount", null, "Mount", AddressSpaceRealm.Raw);
var parent = manager.TryGetFolder("Mount", AddressSpaceRealm.Raw)!.NodeId;
var access = new BrowseAccess();
manager.ProjectedBrowseAccess = access;
var identity = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "reader" }, [], "reader", "key", "version", null);
var context = new OperationContext(new RequestHeader(), null, RequestType.Browse, RequestLifetime.None, identity);
var point = new ContinuationPoint { NodeToBrowse = manager.GetManagerHandle(parent)!, BrowseDirection = BrowseDirection.Forward,
IncludeSubtypes = true, ResultMask = BrowseResultMask.All };
try
{
var original = point;
Should.Throw<ServiceResultException>(() => manager.Browse(context, ref point, new List<ReferenceDescription>()));
access.Last.ShouldNotBeNull();
access.Last.Parent.ShouldBe(parent);
access.Last.Caller.ShouldBeSameAs(identity);
access.Last.Continuation.ShouldBeSameAs(original);
point.ShouldBeSameAs(original);
}
finally { point?.Dispose(); }
}
finally { await started.Host.DisposeAsync(); }
}
private sealed class BrowseAccess : IProjectedBrowseAccess
{
public ProjectedBrowseContext? Last;
public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context)
{ Last = context; return ProjectedBrowseReadiness.Pending; }
}
public void Dispose()
{
if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
}
@@ -0,0 +1,33 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataSdkContinuationTests
{
[Fact]
public void Cursor_is_bound_to_original_session_caller_and_parent_and_only_advances_after_commit()
{
var parent = new NodeId("parent", 2);
var firstSession = new NodeId("session-a", 1);
var secondSession = new NodeId("session-b", 1);
var caller = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "reader" }, [], "reader", "key", "v1", null);
var otherKey = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "reader" }, [], "reader", "key", "v2", null);
using var state = new ProjectedBrowseContinuation(parent, firstSession, caller, "cursor-1");
state.TryGetCursor(parent, firstSession, caller, out var original).ShouldBeTrue();
original.ShouldBe("cursor-1");
state.TryGetCursor(parent, secondSession, caller, out _).ShouldBeFalse();
state.TryGetCursor(parent, firstSession, otherKey, out _).ShouldBeFalse();
state.TryGetCursor(new NodeId("other", 2), firstSession, caller, out _).ShouldBeFalse();
state.TryAdvance("cursor-1", "cursor-2", () => false).ShouldBeFalse();
state.TryGetCursor(parent, firstSession, caller, out var stillOriginal).ShouldBeTrue();
stillOriginal.ShouldBe("cursor-1");
state.TryAdvance("cursor-1", "cursor-2", () => true).ShouldBeTrue();
state.TryAdvance("cursor-1", "cursor-3", () => true).ShouldBeFalse();
state.TryGetCursor(parent, firstSession, caller, out var next).ShouldBeTrue();
next.ShouldBe("cursor-2");
}
}
@@ -0,0 +1,142 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataSdkHierarchyTests : IDisposable
{
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"projection-hierarchy-{Guid.NewGuid():N}");
[Theory]
[InlineData(DataRealm.Raw, AddressSpaceRealm.Raw)]
[InlineData(DataRealm.Uns, AddressSpaceRealm.Uns)]
public async Task Folder_hierarchy_and_one_dimensional_variable_preserve_parent_and_shape(DataRealm realm, AddressSpaceRealm localRealm)
{
var started = await StartAsync();
try
{
var manager = started.Server.NodeManager!;
manager.EnsureFolder("Local", null, "Local", localRealm);
var parent = manager.TryGetFolder("Local", localRealm)!.NodeId;
var sink = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager);
foreach (var name in new[] { "Folder", "Driver", "Device", "Group" })
{
var definition = Definition(realm, parent, name, "Folder", DataValueKind.Null, -1, [], null);
sink.TryApply(parent, [definition], () => true).ShouldBeTrue();
((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), definition.LocalIdentifier, out var next).ShouldBeTrue();
parent = next!.Value;
var folder = ((NodeHandle)manager.GetManagerHandle(parent)!).Node;
folder.ShouldBeOfType<FolderState>();
}
var array = Definition(realm, parent, "Tag", "Variable", DataValueKind.Array, 1, [3], DataValueKind.Int32);
sink.TryApply(parent, [array], () => true).ShouldBeTrue();
((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), array.LocalIdentifier, out var tag).ShouldBeTrue();
var variable = ((NodeHandle)manager.GetManagerHandle(tag!.Value)!).Node.ShouldBeOfType<BaseDataVariableState>();
variable.ValueRank.ShouldBe(ValueRanks.OneDimension);
variable.ArrayDimensions.ToArray()!.ShouldBe([3u]);
}
finally { await started.Host.DisposeAsync(); }
}
[Fact]
public async Task Root_leaf_promotion_is_atomic_and_keeps_anchor_node_and_local_name()
{
var started = await StartAsync();
try
{
var manager = started.Server.NodeManager!;
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var origin = new DataAddress("origin", "urn:raw", "string", "leaf-root");
var identifier = ProjectedDataIds.Identifier("mapping", origin);
var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, identifier, parent, "ConfiguredBranch", "Plant/ConfiguredBranch", "mapping", 1, () => true);
manager.TryEnsureProjectedAnchor(anchor, out var id).ShouldBeTrue();
var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/ConfiguredBranch");
var metadata = new DataMetadata(view, "OriginName", "Variable", DataValueKind.Int32, -1, [], false,
DataOperations.Browse | DataOperations.Read, 1, null, null, false);
var definition = new ProjectedVariableDefinition(DataRealm.Raw, identifier, parent, metadata, 1, () => true);
var sink = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager);
sink.TryApplyRootLeaf(id!.Value, definition, () => false).ShouldBeFalse();
((NodeHandle)manager.GetManagerHandle(id.Value)!).Node.ShouldBeOfType<FolderState>();
sink.TryApplyRootLeaf(id.Value, definition with { Parent = id.Value }, () => true).ShouldBeTrue();
var node = ((NodeHandle)manager.GetManagerHandle(id.Value)!).Node.ShouldBeOfType<BaseDataVariableState>();
node.NodeId.ShouldBe(id.Value);
node.DisplayName.Text.ShouldBe("ConfiguredBranch");
((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(id.Value, out var resolved).ShouldBeTrue();
resolved!.Metadata.BrowseName.ShouldBe("OriginName");
resolved.Parent.ShouldBe(parent);
var oldGuard = resolved.AuthorityIsCurrent;
var refreshed = definition with { Parent = id.Value, AuthorityIsCurrent = () => true };
sink.TryApplyRootLeaf(id.Value, refreshed, () => false).ShouldBeFalse();
((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(id.Value, out var afterAbort).ShouldBeTrue();
afterAbort.ShouldBeSameAs(resolved);
sink.TryApplyRootLeaf(id.Value, refreshed, () => true).ShouldBeTrue();
((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(id.Value, out var renewed).ShouldBeTrue();
renewed!.Parent.ShouldBe(parent);
renewed.Lifetime.ShouldBeSameAs(resolved.Lifetime);
renewed.AuthorityIsCurrent.ShouldNotBeSameAs(oldGuard);
((NodeHandle)manager.GetManagerHandle(id.Value)!).Node.ShouldBeSameAs(node);
}
finally { await started.Host.DisposeAsync(); }
}
[Fact]
public async Task Removed_root_leaf_remains_charged_until_its_physical_pin_drains()
{
var started = await StartAsync();
try
{
var manager = started.Server.NodeManager!;
manager.ConfigureProjectedNodeLimits(maxNodes: 4, maxBytes: 3000);
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var origin = new DataAddress("origin", "urn:raw", "string", "leaf-root");
var identifier = ProjectedDataIds.Identifier("mapping", origin);
var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, identifier, parent, "Branch", "Plant/Branch", "mapping", 1, () => true);
manager.TryEnsureProjectedAnchor(anchor, out var id).ShouldBeTrue();
var metadata = new DataMetadata(new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Branch"), "Leaf", "Variable",
DataValueKind.Int32, -1, [], false, DataOperations.Browse | DataOperations.Read, 1, null, null, false);
var definition = new ProjectedVariableDefinition(DataRealm.Raw, identifier, id!.Value, metadata, 1, () => true);
var sink = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager);
sink.TryApplyRootLeaf(id.Value, definition, () => true).ShouldBeTrue();
((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(id.Value, out var installed).ShouldBeTrue();
installed!.Lifetime.TryPin(out var physicalPin).ShouldBeTrue();
manager.TryRemoveProjectedAnchor(id.Value, anchor).ShouldBeTrue();
physicalPin!.IsValid.ShouldBeFalse();
var otherOrigin = new DataAddress("origin", "urn:raw", "string", "other-root");
var other = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("other", otherOrigin), parent,
"Other", "Plant/Other", "other", 1, () => true);
manager.TryEnsureProjectedAnchor(other, out _).ShouldBeFalse();
using var drained = new ManualResetEventSlim();
var lockRace = other with { AuthorityIsCurrent = () =>
{
_ = Task.Run(() => { physicalPin.Dispose(); drained.Set(); });
return drained.Wait(TimeSpan.FromSeconds(2));
} };
manager.TryEnsureProjectedAnchor(lockRace, out _).ShouldBeTrue("pin disposal must not wait for the SDK lock");
}
finally { await started.Host.DisposeAsync(); }
}
private static ProjectedVariableDefinition Definition(DataRealm realm, NodeId parent, string name, string kind,
DataValueKind valueKind, int rank, IReadOnlyList<int> dimensions, DataValueKind? elementKind)
{
var origin = new DataAddress("origin", "urn:raw", "string", name);
var view = new DataView(origin, realm, "mapping", 1, "Local/" + name);
var metadata = new DataMetadata(view, name, kind, valueKind, rank, dimensions, false, DataOperations.Browse | DataOperations.Read,
1, null, null, false, elementKind);
return new(realm, ProjectedDataIds.Identifier("mapping", origin), parent, metadata, 1, () => true);
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> StartAsync() =>
await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ProjectionHierarchy", ApplicationUri = $"urn:ProjectionHierarchy:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
public void Dispose() { if (Directory.Exists(_pki)) try { Directory.Delete(_pki, true); } catch (IOException) { } }
}
@@ -0,0 +1,45 @@
using Opc.Ua;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataSdkMappedAccessTests
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Queued_value_is_denied_after_its_original_proof_is_revoked_on_publish_and_republish(bool republish)
{
var valid = true;
var value = new DataValue(new Variant(42), StatusCodes.Good);
var item = new MonitoredItemNotification { ClientHandle = 7, Value = value };
item.Message = new ProjectedNotificationMarker(7, value, () => valid);
var message = Message(item);
valid = false;
var output = ProjectedNotificationRewriter.Project(message, republish);
output.NotificationData[0].TryGetValue<DataChangeNotification>(out var data).ShouldBeTrue();
data!.MonitoredItems[0].Value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
item.Value.StatusCode.ShouldBe(StatusCodes.Good);
}
[Fact]
public void A_reused_handle_does_not_turn_an_old_item_proof_into_a_new_authorization()
{
var oldValue = new DataValue(new Variant(42), StatusCodes.Good);
var newValue = new DataValue(new Variant(43), StatusCodes.Good);
var item = new MonitoredItemNotification { ClientHandle = 7, Value = newValue };
item.Message = new ProjectedNotificationMarker(7, oldValue, () => true);
var output = ProjectedNotificationRewriter.Project(Message(item), false);
output.NotificationData[0].TryGetValue<DataChangeNotification>(out var data).ShouldBeTrue();
data!.MonitoredItems[0].Value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
}
private static NotificationMessage Message(MonitoredItemNotification item) => new()
{
SequenceNumber = 1,
PublishTime = DateTimeUtc.Now,
NotificationData = new List<ExtensionObject> { new(new DataChangeNotification { MonitoredItems = [item] }) },
};
}
@@ -0,0 +1,120 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataSdkProjectionLifetimeTests : IDisposable
{
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"projection-lifetime-{Guid.NewGuid():N}");
[Fact]
public async Task Cumulative_limit_reclaims_only_expired_nodes_without_live_demand()
{
var started = await StartAsync();
try
{
var manager = started.Server.NodeManager!;
manager.ConfigureProjectedNodeLimits(maxNodes: 1, maxBytes: 4096);
var demand = new DemandStatus();
manager.ProjectedDataAccess = demand;
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var live = true;
var first = Definition(parent, "first", () => live);
var second = Definition(parent, "second", () => true);
manager.TryEnsureProjectedVariable(first, out var oldId).ShouldBeTrue();
manager.TryEnsureProjectedVariable(second, out _).ShouldBeFalse();
first.Lifetime.TryPin(out var pin).ShouldBeTrue();
live = false;
manager.TryEnsureProjectedVariable(second, out _).ShouldBeFalse("expired nodes with live physical demand remain charged");
pin!.Dispose();
manager.TryEnsureProjectedVariable(second, out _).ShouldBeTrue();
((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(oldId!.Value, out _).ShouldBeFalse();
}
finally { await started.Host.DisposeAsync(); }
}
[Fact]
public async Task Retained_authority_is_charged_against_the_node_byte_limit()
{
var started = await StartAsync();
try
{
var manager = started.Server.NodeManager!;
manager.ConfigureProjectedNodeLimits(maxNodes: 2, maxBytes: 4096);
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var large = new RetainedGuard(4096);
var small = new RetainedGuard(1);
manager.TryEnsureProjectedVariable(Definition(parent, "large", large.IsCurrent), out _).ShouldBeFalse();
manager.TryEnsureProjectedVariable(Definition(parent, "small", small.IsCurrent), out _).ShouldBeTrue();
}
finally { await started.Host.DisposeAsync(); }
}
[Fact]
public async Task Same_placement_renewal_commits_a_fresh_guard_without_resurrecting_the_old_one()
{
var started = await StartAsync();
try
{
var manager = started.Server.NodeManager!;
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var oldValid = true;
var oldDefinition = Definition(parent, "same", () => oldValid);
var sink = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager);
sink.TryApply(parent, [oldDefinition], () => true).ShouldBeTrue();
var id = new NodeId(oldDefinition.LocalIdentifier,
(ushort)started.Server.CurrentInstance.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
var lookup = (IProjectedNodeLookup)new SdkAddressSpaceSink(manager);
lookup.TryResolve(id, out var original).ShouldBeTrue();
var replacement = oldDefinition with { Metadata = oldDefinition.Metadata with { Dimensions = Array.Empty<int>() }, AuthorityIsCurrent = () => true };
sink.TryApply(parent, [replacement], () => false).ShouldBeFalse();
lookup.TryResolve(id, out var afterAbort).ShouldBeTrue();
afterAbort.ShouldBeSameAs(original);
oldValid = false;
sink.TryApply(parent, [replacement], () => true).ShouldBeTrue();
lookup.TryResolve(id, out var afterCommit).ShouldBeTrue();
afterCommit.ShouldBeSameAs(replacement);
original!.AuthorityIsCurrent().ShouldBeFalse();
manager.GetManagerHandle(id).ShouldNotBeNull();
}
finally { await started.Host.DisposeAsync(); }
}
private static ProjectedVariableDefinition Definition(NodeId parent, string name, Func<bool> guard)
{
var origin = new DataAddress("origin", "urn:raw", "string", name);
var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/" + name);
var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Read, 1, null, null, false);
return new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), parent, metadata, 1, guard);
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> StartAsync() =>
await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ProjectionLifetime", ApplicationUri = $"urn:ProjectionLifetime:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
private sealed class RetainedGuard(long retainedBytes) : IProjectedRetainedAuthority
{
public long RetainedBytes => retainedBytes;
public bool IsCurrent() => true;
}
private sealed class DemandStatus : IProjectedDataAccess
{
public TimeProvider Clock => TimeProvider.System;
public bool HasLiveDemand(DataRealm realm, string localIdentifier) => false;
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) { demand = null; return false; }
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) => false;
public Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, long requestStartedTimestamp, CancellationToken cancellationToken) => throw new NotSupportedException();
public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) => false;
}
public void Dispose() { if (Directory.Exists(_pki)) try { Directory.Delete(_pki, true); } catch (IOException) { } }
}
@@ -0,0 +1,163 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
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.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataSdkProjectionTests : IDisposable
{
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-projection-{Guid.NewGuid():N}");
[Fact]
public async Task Materialization_requires_the_exact_parent_and_rejects_unsupported_shape()
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ProjectedNode", ApplicationUri = $"urn:ProjectedNode:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
try
{
var manager = started.Server.NodeManager!;
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var anchorOrigin = new DataAddress("origin", "urn:source", "string", "root");
var anchorIdentifier = ProjectedDataIds.Identifier("mapping", anchorOrigin);
var anchorDefinition = new ProjectedAnchorDefinition(DataRealm.Raw, anchorIdentifier, parent, "Mount", "Plant/Mount", "mapping", 1, () => true);
manager.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue();
anchor.ShouldNotBeNull();
var missingAnchorParent = new NodeId("does-not-exist", parent.NamespaceIndex);
manager.TryEnsureProjectedAnchor(anchorDefinition with { Parent = missingAnchorParent }, out _).ShouldBeFalse();
var anchorSink = (IProjectedAnchorSink)new SdkAddressSpaceSink(manager);
anchorSink.TryRemoveProjectedAnchor(anchor.Value, anchorDefinition).ShouldBeTrue();
var replacementAnchor = anchorDefinition with { Lifetime = new ProjectedNodeLifetime() };
anchorSink.TryEnsureProjectedAnchor(replacementAnchor, out var sameAnchorId).ShouldBeTrue();
sameAnchorId.ShouldBe(anchor);
anchorSink.TryRemoveProjectedAnchor(anchor.Value, anchorDefinition).ShouldBeFalse();
var origin = new DataAddress("origin", "urn:source", "string", "Device/Speed");
var view = new DataView(origin, DataRealm.Raw, "map", 1, "Plant/Speed");
var metadata = new DataMetadata(view, "Speed", "Tag", DataValueKind.Int32, -1, [], false,
DataOperations.Browse | DataOperations.Read, 1, null, null, false);
var identifier = ProjectedDataIds.Identifier("map", origin);
var missingParent = new NodeId("missing", parent.NamespaceIndex);
manager.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, missingParent, metadata, 1, () => true), out _).ShouldBeFalse();
manager.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata with { ValueKind = DataValueKind.Array, ArrayElementKind = DataValueKind.Int32, ValueRank = 2, Dimensions = [2, 2] }, 1, () => true), out _).ShouldBeFalse();
manager.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata, 1, () => true), out var node).ShouldBeTrue();
node.ShouldNotBeNull();
started.Server.CurrentInstance.NamespaceUris.GetString(node.Value.NamespaceIndex).ShouldBe(ProjectedDataIds.RawNamespaceUri);
manager.EnsureVariable(identifier, "Plant", "LocalCollision", "Int32", false, AddressSpaceRealm.Raw);
var localCollision = manager.TryGetVariable(identifier, AddressSpaceRealm.Raw)!.NodeId;
var readContext = new OperationContext(new RequestHeader(), null, RequestType.Read, RequestLifetime.None, (IUserIdentity?)null);
var reads = new List<ReadValueId> { new() { NodeId = localCollision, AttributeId = Attributes.Value }, new() { NodeId = node.Value, AttributeId = Attributes.Value } };
var readValues = new List<Opc.Ua.DataValue> { new(), new() };
var readErrors = new List<ServiceResult> { null!, null! };
manager.Read(readContext, 0, reads, readValues, readErrors);
readErrors[0]?.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
readErrors[1].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
var access = new ReadOnlyAccess(view with { MappingId = null, MappingRevision = 0, Subject = "origin/Speed" });
manager.ProjectedDataAccess = access;
var caller = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "reader" }, [], "reader", "key", "version", null);
var callerContext = new OperationContext(new RequestHeader(), null, RequestType.Read, RequestLifetime.None, caller);
var projectedRead = new List<ReadValueId> { new() { NodeId = node.Value, AttributeId = Attributes.Value } };
var projectedValues = new List<Opc.Ua.DataValue> { new() };
var projectedErrors = new List<ServiceResult> { null! };
manager.Read(callerContext, 0, projectedRead, projectedValues, projectedErrors);
access.LastOperation.ShouldBe(DataOperations.Read);
access.ReadSchedules.ShouldBe(1);
projectedValues[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData);
manager.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, missingParent, metadata, 1, () => true), out _).ShouldBeFalse();
var otherOrigin = origin with { Identifier = "Device/Temperature" };
var otherId = ProjectedDataIds.Identifier("map", otherOrigin);
var otherMetadata = metadata with { View = view with { Address = otherOrigin, Subject = "Plant/Temperature" }, BrowseName = "Temperature" };
var definition = new ProjectedVariableDefinition(DataRealm.Raw, otherId, parent, otherMetadata, 1, () => true);
var deferred = new DeferredAddressSpaceSink();
var pageSink = new DeferredProjectedNamespacePageSink(deferred);
pageSink.TryApply(parent, [definition], () => true).ShouldBeFalse();
deferred.SetSink(new SdkAddressSpaceSink(manager));
var pageNode = new NodeId(otherId, node.Value.NamespaceIndex);
pageSink.TryApply(parent, [definition], () => false).ShouldBeFalse();
manager.GetManagerHandle(pageNode).ShouldBeNull("an aborted cursor must roll back all new SDK nodes");
var commits = 0;
pageSink.TryApply(parent, [definition], () => { commits++; return true; }).ShouldBeTrue();
commits.ShouldBe(1);
manager.GetManagerHandle(pageNode).ShouldNotBeNull();
var lookup = (IProjectedNodeLookup)new SdkAddressSpaceSink(manager);
lookup.TryGetNodeId(ProjectedDataIds.RawNamespaceUri, otherId, out var translated).ShouldBeTrue();
translated.ShouldBe(pageNode);
lookup.TryResolve(pageNode, out var originalDefinition).ShouldBeTrue();
var removable = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager);
removable.TryRemove(pageNode, originalDefinition!).ShouldBeTrue();
lookup.TryResolve(pageNode, out _).ShouldBeFalse();
var replacementDefinition = definition with { Lifetime = new ProjectedNodeLifetime() };
removable.TryApply(parent, [replacementDefinition], () => true).ShouldBeTrue();
lookup.TryResolve(pageNode, out var currentDefinition).ShouldBeTrue();
currentDefinition.ShouldNotBeSameAs(originalDefinition);
removable.TryRemove(pageNode, originalDefinition!).ShouldBeFalse();
deferred.SetSink(null);
pageSink.TryApply(parent, [definition], () => true).ShouldBeFalse();
var proof = new SampleProof();
var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1);
var update = new ProjectedValueWrite(DataRealm.Raw, identifier, 1, serving,
new DataValueSnapshot(42, StatusCodes.Good.Code, null, null), new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)),
TimeProvider.System.GetTimestamp(), proof);
var sink = (IProjectedValueSink)new SdkAddressSpaceSink(manager);
sink.TryPublish([update]).ShouldBeTrue();
var variable = ((NodeHandle)manager.GetManagerHandle(node.Value)!).Node.ShouldBeOfType<BaseDataVariableState>();
variable.StatusCode.ShouldBe(StatusCodes.Good);
proof.Invalidate();
sink.TryPublish([update]).ShouldBeFalse();
StatusCode.IsBad(variable.StatusCode).ShouldBeTrue("a rejected stale sample must not leave a Good value visible");
lookup.TryResolve(pageNode, out _).ShouldBeTrue();
manager.RebuildAddressSpace();
lookup.TryResolve(pageNode, out _).ShouldBeFalse("a rebuilt address space must retire old projected identities");
manager.GetManagerHandle(pageNode).ShouldBeNull();
}
finally { await started.Host.DisposeAsync(); }
}
private sealed class ReadOnlyAccess(DataView view) : IProjectedDataAccess
{
public TimeProvider Clock => TimeProvider.System;
public DataOperations LastOperation;
public int ReadSchedules;
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand)
{ LastOperation = operation; demand = new ReadDemand(view); return operation == DataOperations.Read; }
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) { ReadSchedules++; return true; }
public Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, long requestStartedTimestamp, CancellationToken cancellationToken) => throw new NotSupportedException();
public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) => throw new InvalidOperationException("A read must not require subscribe permission.");
}
private sealed class ReadDemand(DataView view) : IProjectedDemandLease
{
public DataView OriginView => view;
public DataRealm Realm => view.Realm;
public string LocalIdentifier => "unused";
public long ProjectionGeneration => 1;
public TimeSpan MaximumSampleAge => TimeSpan.FromSeconds(5);
public ServingIdentity Serving { get; } = new("node", "boot", "Primary", 1, 1, 1);
public CancellationToken CancellationToken => CancellationToken.None;
public bool IsValid => true;
public void Dispose() { }
}
private sealed class SampleProof : IProjectedSamplePublicationProof
{
private bool _valid = true;
public bool IsValid => _valid;
public TimeProvider Clock => TimeProvider.System;
public void Invalidate() => _valid = false;
}
public void Dispose()
{
if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
}
@@ -0,0 +1,205 @@
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Shouldly;
using Xunit;
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.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataAdapterLifecycleTests
{
private static readonly ServingIdentity Serving = new("remote", "boot", "Primary", 3, 4, 1);
private static readonly DataView View = new(new("remote-cluster", "urn:raw", "string", "Device/Speed"), DataRealm.Raw, null, 0, "Device/Speed");
private static readonly DataMetadata Metadata = new(View, "Speed", "Tag", DataValueKind.Int32, -1, [], true,
DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, 3, null, null, false);
private static readonly string Ref = ProjectedDataIds.DependencyReference(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", View.Address));
private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5));
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Fact]
public async Task Unknown_remote_write_is_not_replayed_or_published_as_a_value()
{
var source = new FakeConnectionSource();
var routes = new FakeRoutes();
var adapter = new GrpcDataDriverAdapter("mapped-driver", "connection", source, routes);
var publications = 0;
adapter.OnDataChange += (_, _) => Interlocked.Increment(ref publications);
await adapter.InitializeAsync("{}", Ct);
var outcomes = await adapter.WriteWithOutcomesAsync([new WriteRequest(Ref, 42)], Ct);
outcomes.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.OutcomeUnknown);
source.Connection.WriteCount.ShouldBe(1);
publications.ShouldBe(0);
await adapter.ShutdownAsync(Ct);
}
[Fact]
public async Task Stream_lease_is_retained_until_actual_stream_disposal_completes()
{
var source = new FakeConnectionSource();
var adapter = new GrpcDataDriverAdapter("mapped-driver", "connection", source, new FakeRoutes());
await adapter.InitializeAsync("{}", Ct);
#pragma warning disable OTOPCUA0001 // This test exercises the adapter lifetime directly.
var handle = await adapter.SubscribeAsync([Ref], TimeSpan.FromSeconds(1), Ct);
var closing = adapter.UnsubscribeAsync(handle, Ct);
#pragma warning restore OTOPCUA0001
try
{
await source.Connection.Stream.DisposeEntered.Task.WaitAsync(Ct);
source.LastLease.ShouldNotBeNull();
source.LastLease.Disposed.ShouldBeFalse();
}
finally { source.Connection.Stream.ReleaseDispose.TrySetResult(); }
await closing.WaitAsync(Ct);
source.LastLease!.Disposed.ShouldBeTrue();
await adapter.ShutdownAsync(Ct);
}
[Theory(Timeout = 15000)]
[InlineData(false)]
[InlineData(true)]
public async Task Initial_snapshot_is_atomic_and_typed_publication_keeps_origin_age(bool rejectPublication)
{
var source = new FakeConnectionSource();
source.Connection.Stream.HoldSnapshotEnd = true;
var publisher = new FakePublisher { Reject = rejectPublication };
var adapter = new GrpcDataDriverAdapter("mapped-driver", "connection", source, new FakeRoutes(), publisher);
await adapter.InitializeAsync("{}", Ct);
#pragma warning disable OTOPCUA0001 // Exercise the adapter's stream lifetime directly.
var handle = await adapter.SubscribeAsync([Ref], TimeSpan.FromSeconds(1), Ct);
#pragma warning restore OTOPCUA0001
try
{
await source.Connection.Stream.SnapshotValueConsumed.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct);
publisher.Updates.ShouldBeEmpty();
source.Connection.Stream.FinishSnapshot();
await publisher.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct);
var update = publisher.Updates.ShouldHaveSingleItem();
update.OriginAgeBounds.ShouldBe(new DataAgeBounds(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(4)));
if (rejectPublication)
SpinWait.SpinUntil(() => !update.SourceProof.IsValid, TimeSpan.FromSeconds(2)).ShouldBeTrue();
else update.SourceProof.IsValid.ShouldBeTrue();
update.Route.PublicationId.ShouldNotBe(Guid.Empty);
}
finally
{
source.Connection.Stream.ReleaseDispose.TrySetResult();
#pragma warning disable OTOPCUA0001 // Exercise the adapter's stream lifetime directly.
await adapter.UnsubscribeAsync(handle, Ct);
#pragma warning restore OTOPCUA0001
}
await adapter.ShutdownAsync(Ct);
}
private sealed class FakePublisher : IProjectedValuePublisher
{
public bool Reject { get; init; }
public List<ProjectedValueUpdate> Updates { get; } = [];
public TaskCompletionSource Published { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public bool TryBind(ProjectedValueRoute route) => true;
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates)
{ Updates.AddRange(updates); Published.TrySetResult(); return !Reject; }
public void Retire(ProjectedValueRoute route) { }
}
private sealed class FakeRoutes : IGrpcDataAdapterRouteSource
{
private readonly FakeLease _lease = new();
public bool TryResolve(string fullReference, out GrpcDataAdapterRoute? route)
{
route = fullReference == Ref ? new GrpcDataAdapterRoute(Ref, View, Metadata, Serving, _lease, 1) : null;
return route is not null;
}
}
private sealed class FakeLease : IDataAuthorizationLease
{
public bool IsValid => true;
public ServingIdentity Serving => GrpcDataAdapterLifecycleTests.Serving;
}
private sealed class FakeConnectionSource : IGrpcDataAdapterConnectionSource
{
public FakeConnection Connection { get; } = new();
public FakeConnectionLease? LastLease { get; private set; }
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
LastLease = new FakeConnectionLease(Connection);
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(LastLease);
}
}
private sealed class FakeConnectionLease(FakeConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public bool Disposed { get; private set; }
public ValueTask DisposeAsync() { Disposed = true; return ValueTask.CompletedTask; }
}
private sealed class FakeConnection : IDataConnection
{
public int WriteCount { get; private set; }
public FakeSubscription Stream { get; } = new();
public DataTarget Target { get; } = new(DataTargetMode.Cluster, "remote-cluster", null);
public TimeProvider Clock => TimeProvider.System;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) =>
Task.FromResult(new DataCapabilities(1, 2, Serving, DataReadiness.Ready,
DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits, false, 0, "remote-cluster", true, true));
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{
WriteCount++;
return Task.FromResult<IReadOnlyList<WriteItemResult>>(request.Items.Select(x => new WriteItemResult(x.CorrelationId,
new(DataWriteState.OutcomeUnknown, 0x800A0000u, "uncertain"))).ToArray());
}
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => Task.FromResult<IDataSubscription>(Stream);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class FakeSubscription : IDataSubscription, IDataSubscriptionProvenance
{
private readonly Channel<DataSubscriptionFrame> _frames = Channel.CreateUnbounded<DataSubscriptionFrame>();
private string? _subscriptionId;
private long _streamEpoch;
public bool HoldSnapshotEnd { get; set; }
public TaskCompletionSource SnapshotValueConsumed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ServingIdentity Serving => GrpcDataAdapterLifecycleTests.Serving;
public TaskCompletionSource DisposeEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource ReleaseDispose { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
if (command is OpenSubscription open)
{
_subscriptionId = open.SubscriptionId;
_streamEpoch = open.StreamEpoch;
var settings = open.Items[0].Settings;
_frames.Writer.TryWrite(new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId,
[new(open.Items[0].ClientItemId, DataItemStatus.Good, new(open.SubscriptionId, open.StreamEpoch, 1, 1), settings, null)]));
_frames.Writer.TryWrite(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 2, DataStreamControlKind.SnapshotBegin, [], 3, 4, null));
if (HoldSnapshotEnd)
_frames.Writer.TryWrite(new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, 3, true,
[new(new(open.SubscriptionId, open.StreamEpoch, 1, 1), new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1),
new(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(4)), DataReadiness.Ready)]));
else _frames.Writer.TryWrite(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 3, DataStreamControlKind.SnapshotEnd, [], 3, 4, null));
}
return Task.CompletedTask;
}
public void FinishSnapshot() => _frames.Writer.TryWrite(new DataSubscriptionControl(_subscriptionId!, _streamEpoch, 4,
DataStreamControlKind.SnapshotEnd, [], 3, 4, null));
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var frame in _frames.Reader.ReadAllAsync(cancellationToken))
{
yield return frame;
if (frame is DataSubscriptionValues) SnapshotValueConsumed.TrySetResult();
}
}
public async ValueTask DisposeAsync()
{
DisposeEntered.TrySetResult();
await ReleaseDispose.Task;
_frames.Writer.TryComplete();
}
}
}
@@ -36,6 +36,516 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
private static readonly ServingIdentity BootIdentity = new("node-a", "process-1", "Primary", 0, 0);
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 100, 1_000_000);
[Fact]
public void Mappings_activate_only_with_the_exact_completed_catalog_and_close_on_next_attempt()
{
var authority = new DataPlaneAuthorityState();
var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var attempt = Prepare(coordinator, Artifact());
var mapping = TestMapping();
runtime.Stage(attempt, [mapping], [TestConnection()]);
runtime.Active.ShouldBeEmpty();
coordinator.Complete(attempt, true).ShouldBeTrue();
var placement = runtime.Active.ShouldHaveSingleItem();
var parent = coordinator.Current!.Nodes.Single(x => x.EntityKind == "RawFolder" && x.EntityId == "folder");
placement.Parent.ShouldBe(parent.Metadata.View);
placement.Scope.Segments.ShouldBe(parent.Scope.Segments.Concat(["Remote"]));
placement.Anchor.Address.OriginClusterId.ShouldBe("remote-cluster");
placement.Authority.IsActive.ShouldBeTrue();
runtime.TryGetConnectionId("map", out var connectionId).ShouldBeTrue();
connectionId.ShouldBe("link");
var next = coordinator.BeginAttempt("next");
placement.Authority.IsActive.ShouldBeFalse();
runtime.Active.ShouldBeEmpty();
runtime.TryGetConnectionId("map", out _).ShouldBeFalse();
coordinator.Complete(attempt, true).ShouldBeFalse();
runtime.Active.ShouldBeEmpty();
coordinator.Complete(next, false).ShouldBeFalse();
}
[Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public void Configured_capability_is_minted_only_from_live_authorized_placement_and_expires_with_attempt()
{
var authority = new DataPlaneAuthorityState();
var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var attempt = Prepare(coordinator, Artifact());
var mapping = TestMapping();
runtime.Stage(attempt, [mapping], [TestConnection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
runtime.TryAcquireConfiguredCapability("map", DataRealm.Raw, out _, out _).ShouldBeFalse("Subscribe is required");
var replacement = Prepare(coordinator, Artifact());
mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe;
runtime.Stage(replacement, [mapping], [TestConnection()]);
coordinator.Complete(replacement, true).ShouldBeTrue();
runtime.TryAcquireConfiguredCapability("map", DataRealm.Uns, out _, out _).ShouldBeFalse();
runtime.TryAcquireConfiguredCapability("missing", DataRealm.Raw, out _, out _).ShouldBeFalse();
runtime.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var capability, out var copy).ShouldBeTrue();
capability.ShouldNotBeNull(); copy.ShouldNotBeNull();
runtime.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var shared, out var otherCopy).ShouldBeTrue();
shared.ShouldBeSameAs(capability);
otherCopy.ShouldNotBeSameAs(copy);
var originalView = copy!.Anchor;
var originalAuthority = copy.Authority;
capability!.Matches("map", originalView, originalAuthority).ShouldBeTrue();
copy.Mapping.Revision++;
copy.Mapping.AllowedOperations = DataOperations.None;
capability.Matches("map", originalView, originalAuthority).ShouldBeTrue("the caller cannot mutate the captured placement");
coordinator.BeginAttempt("retire");
capability.Matches("map", originalView, originalAuthority).ShouldBeFalse();
}
[Fact]
public void Retired_configured_capability_does_not_retain_unrelated_placement_graph()
{
var authority = new DataPlaneAuthorityState();
var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var (capability, unrelated) = Publish(runtime, coordinator);
coordinator.BeginAttempt("replacement");
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();
unrelated.IsAlive.ShouldBeFalse("one retired capability must not retain every old mapping");
GC.KeepAlive(capability);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
static (ConfiguredProjectionCapability Capability, WeakReference Unrelated) Publish(ProjectedMappingDeploymentRuntime runtime, LocalCatalogCoordinator coordinator)
{
var attempt = Prepare(coordinator, Artifact());
var selected = TestMapping(); selected.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe;
var other = TestMapping(); other.RemoteNamespaceMappingId = "other"; other.BranchName = "Other";
runtime.Stage(attempt, [selected, other], [TestConnection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
runtime.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var capability, out _).ShouldBeTrue();
// Observe the actual deployment-owned DTO rather than a defensive Active copy.
var fields = typeof(ProjectedMappingDeploymentRuntime).GetField("_byMapping", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
var mappings = (Dictionary<string, ProjectedMappingPlacement>)fields.GetValue(runtime)!;
return (capability!, new WeakReference(mappings["other"].Mapping));
}
}
[Theory]
[InlineData("missing", "Remote")]
[InlineData("folder", "Driver")]
public void Invalid_or_colliding_mapping_is_not_activated(string parent, string name)
{
var authority = new DataPlaneAuthorityState();
var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var attempt = Prepare(coordinator, Artifact(includeDriver: true));
var mapping = TestMapping(); mapping.LocalParentId = parent; mapping.BranchName = name;
runtime.Stage(attempt, [mapping], [TestConnection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
runtime.Active.ShouldBeEmpty();
}
private static RemoteNamespaceMapping TestMapping() => new() { RemoteNamespaceMappingId = "map", ClusterId = "cluster",
DataConnectionId = "link", Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
LocalParentKind = "RawFolder", LocalParentId = "folder", BranchName = "Remote", RemoteRootEntityId = "remote-root",
RemoteNamespaceUri = "urn:raw", RemoteIdentifierKind = "string", RemoteIdentifier = "remote-root", AllowedOperations = DataOperations.Browse };
private static DataConnection TestConnection() => new() { DataConnectionId = "link", ClusterId = "cluster", Enabled = true, ExpectedClusterId = "remote-cluster" };
private sealed class MissingProjectionSource : IGrpcDataAdapterConnectionSource
{
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) => ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
}
[Fact(Timeout = 15000)]
public async Task Browse_controller_mounts_real_placement_and_schedules_bounded_caller_bound_work()
{
var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var catalog = new HeldBrowseCatalog(); var sink = new BrowseControllerSink();
using var applier = new ProjectedNamespaceApplier(catalog, sink, 2);
using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink,
(uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)),
new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 1);
var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
var anchor = sink.Anchor.ShouldNotBeNull();
anchor.Parent.IdentifierAsString.ShouldBe("Plant");
var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity(
new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null);
var point = new Opc.Ua.Server.ContinuationPoint { MaxResultsToReturn = 3 };
var context = new ProjectedBrowseContext(sink.AnchorId.ShouldNotBeNull(), identity, point, TimeProvider.System.GetTimestamp());
controller.GetOrSchedule(context).ShouldBe(ProjectedBrowseReadiness.Pending);
controller.GetOrSchedule(context).ShouldBe(ProjectedBrowseReadiness.Pending);
await catalog.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
catalog.Calls.ShouldBe(1);
catalog.Last.ShouldNotBeNull().Caller.Principal.ShouldBe("peer");
catalog.Last.Caller.ApiKeyId.ShouldBe("peer-key");
catalog.Last.Parent.ShouldBe(lifecycle.Active.ShouldHaveSingleItem().Anchor);
catalog.Last.Budget.MaxItems.ShouldBe(3);
coordinator.BeginAttempt("replacement");
sink.Removals.ShouldBe(1);
controller.GetOrSchedule(context).ShouldBe(ProjectedBrowseReadiness.Unavailable);
catalog.Release.TrySetResult();
}
[Fact(Timeout = 15000)]
public async Task Browse_next_schedules_the_original_cursor_and_caller_without_consuming_it_while_pending()
{
var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var catalog = new HeldBrowseCatalog(); var sink = new BrowseControllerSink();
using var applier = new ProjectedNamespaceApplier(catalog, sink, 2);
using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink,
(uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)),
new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2);
var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity(
new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null);
var request = new ProjectedBrowsePageRequest(sink.AnchorId.ShouldNotBeNull(), identity, "opaque-wrapped-cursor", 3, TimeProvider.System.GetTimestamp());
var first = controller.GetOrSchedulePage(request);
first.Status.ShouldBe(ProjectedBrowseReadiness.Pending); first.Children.ShouldBeEmpty(); first.NextCursor.ShouldBeNull();
controller.GetOrSchedulePage(request).Status.ShouldBe(ProjectedBrowseReadiness.Pending);
await catalog.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
catalog.Calls.ShouldBe(1); catalog.Last.ShouldNotBeNull().Continuation.ShouldBe("opaque-wrapped-cursor");
catalog.Last.Caller.Principal.ShouldBe("peer"); catalog.Last.Caller.ApiKeyId.ShouldBe("peer-key");
request.Cursor.ShouldBe("opaque-wrapped-cursor");
catalog.Release.TrySetResult();
}
[Fact]
public void Browse_page_exposes_only_live_caller_scoped_committed_nodes_and_revokes_old_proof()
{
var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var catalog = new ReadyBrowseCatalog(); var sink = new BrowseControllerSink();
using var applier = new ProjectedNamespaceApplier(catalog, sink, 2);
using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink,
(uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)),
new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2);
var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
var placement = lifecycle.Active.ShouldHaveSingleItem();
var serving = new ServingIdentity("remote", "boot", "Primary", 1, 1, 1);
var lease = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(30)),
TimeProvider.System.GetTimestamp(), TimeSpan.FromSeconds(30), TimeSpan.Zero, TimeProvider.System);
var view = placement.Anchor with { Address = placement.Anchor.Address with { Identifier = "child" }, Subject = "Plant/Remote/child" };
var metadata = new DataMetadata(view, "child", "Variable", DataValueKind.Int32, -1, [], false,
DataOperations.Browse | DataOperations.Read, 1, null, null, false, Serving: serving);
var scope = placement.Scope with { Segments = placement.Scope.Segments.Concat(["child"]).ToArray() };
var subject = new MappedNamespaceSubject(view, scope, placement.LocalAncestry, serving, DataOperations.Browse | DataOperations.Read, false);
var mapped = new MappedSubjectResolver([subject], 1, placement.Authority);
var proof = new ProjectedNodeProof(ProjectedDataIds.Identifier("map", view.Address), metadata, subject, mapped, lease, 1,
metadata with { View = view with { MappingId = null, MappingRevision = 0 } });
catalog.Snapshot = new(ProjectionPageStatus.Ready, [proof], false, "next-wrapped", 1, lease, placement.Authority);
var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity(
new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null);
var page = controller.GetOrSchedulePage(new(sink.AnchorId.ShouldNotBeNull(), identity, "wrapped", 3, TimeProvider.System.GetTimestamp()));
page.Status.ShouldBe(ProjectedBrowseReadiness.Ready); page.Complete.ShouldBeFalse(); page.NextCursor.ShouldBe("next-wrapped");
page.Children.ShouldHaveSingleItem().IdentifierAsString.ShouldBe(proof.LocalIdentifier);
catalog.Last.ShouldNotBeNull().Continuation.ShouldBe("wrapped"); catalog.Last.Caller.Principal.ShouldBe("peer");
page.IsCurrent().ShouldBeTrue();
catalog.Revoked = true;
page.IsCurrent().ShouldBeFalse();
}
private sealed class TestPageGuard(Func<bool> current) : IProjectedPageGuard
{
public bool IsCurrent => current();
public long RetainedBytes => 512;
}
private sealed class ReadyBrowseCatalog : IFederatedProjectionCatalog
{
public bool Revoked; public ProjectedParentSnapshot Snapshot = new(ProjectionPageStatus.Pending, [], false, null, 0);
public ProjectedBrowseRequest? Last;
public TimeProvider Clock => TimeProvider.System;
public event Action<string, long>? Invalidated { add { } remove { } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request)
{ Last = request; return Revoked ? new(ProjectionPageStatus.Unavailable, [], false, null, 0) : Snapshot; }
public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) =>
new TestPageGuard(() => !Revoked && ReferenceEquals(Snapshot, expected));
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => throw new InvalidOperationException();
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; }
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; }
}
[Fact(Timeout = 15000)]
public async Task Browse_renews_expired_page_through_a_new_fetch_and_recovers()
{
var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var catalog = new RenewingBrowseCatalog(); var sink = new BrowseControllerSink();
using var applier = new ProjectedNamespaceApplier(catalog, sink, 2);
using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink,
(uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)),
new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2);
var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
catalog.Local = lifecycle.Active.ShouldHaveSingleItem().Authority;
var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity(
new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null);
var request = new ProjectedBrowsePageRequest(sink.AnchorId.ShouldNotBeNull(), identity, null, 3, TimeProvider.System.GetTimestamp());
var previous = controller.GetOrSchedulePage(request);
previous.Status.ShouldBe(ProjectedBrowseReadiness.Ready); previous.IsCurrent().ShouldBeTrue();
catalog.Lease.Valid = false;
previous.IsCurrent().ShouldBeFalse();
controller.GetOrSchedulePage(request).Status.ShouldBe(ProjectedBrowseReadiness.Pending);
await catalog.Committed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
catalog.Fetches.ShouldBe(1);
controller.GetOrSchedulePage(request).Status.ShouldBe(ProjectedBrowseReadiness.Ready);
controller.GetOrSchedulePage(request with { Cursor = "invalid" }).Status.ShouldBe(ProjectedBrowseReadiness.InvalidContinuation);
catalog.Fetches.ShouldBe(1);
}
[Fact(Timeout = 15000)]
public void Browse_reports_invalid_cursor_found_by_remote_preparation_without_consuming_or_retrying()
{
var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var catalog = new InvalidAsyncBrowseCatalog(); var sink = new BrowseControllerSink();
using var applier = new ProjectedNamespaceApplier(catalog, sink, 2);
using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink,
(uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)),
new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2);
var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity(
new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null);
var request = new ProjectedBrowsePageRequest(sink.AnchorId.ShouldNotBeNull(), identity, "bad-cursor", 3, TimeProvider.System.GetTimestamp());
controller.GetOrSchedulePage(request).Status.ShouldBe(ProjectedBrowseReadiness.Pending);
AwaitCondition(() => controller.GetOrSchedulePage(request).Status == ProjectedBrowseReadiness.InvalidContinuation,
TimeSpan.FromSeconds(5), "invalid cursor status was lost", TestContext.Current.CancellationToken);
catalog.Fetches.ShouldBe(1);
request.Cursor.ShouldBe("bad-cursor");
}
private sealed class InvalidAsyncBrowseCatalog : IFederatedProjectionCatalog
{
public int Fetches;
public TimeProvider Clock => TimeProvider.System;
public event Action<string, long>? Invalidated { add { } remove { } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => new(ProjectionPageStatus.Pending, [], false, null, 0);
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref Fetches); return Task.FromResult<IProjectedPreparedPage>(new InvalidPage()); }
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; }
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; }
private sealed class InvalidPage : IProjectedPreparedPage
{
public ProjectedParentSnapshot Snapshot => new(ProjectionPageStatus.InvalidContinuation, [], false, null, 0);
public bool TryCommit() => throw new InvalidOperationException("Invalid cursor cannot commit.");
public void Dispose() { }
}
}
[Fact]
public void Placement_guards_and_reconciliation_do_not_clone_all_mappings_for_every_check()
{
var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(64, 128, TimeProvider.System, policy),
new BrowseContinuationRegistry(64, TimeProvider.System), new MissingProjectionSource(), policy, 64, 2);
using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var catalog = new HeldBrowseCatalog(); var sink = new BrowseControllerSink();
using var applier = new ProjectedNamespaceApplier(catalog, sink, 2);
using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink,
(uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)),
new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2);
var attempt = Prepare(coordinator, Artifact());
var mappings = Enumerable.Range(0, 12).Select(i => { var x = TestMapping(); x.RemoteNamespaceMappingId = "map" + i; x.BranchName = "Remote" + i; x.RemoteIdentifier = "root" + i; return x; }).ToArray();
lifecycle.Stage(attempt, mappings, [TestConnection()]); coordinator.Complete(attempt, true).ShouldBeTrue();
var placement = lifecycle.Active[0];
var before = lifecycle.PlacementCopiesForTests;
for (var i = 0; i < 100; i++) lifecycle.IsCurrentPlacement(placement).ShouldBeTrue();
lifecycle.PlacementCopiesForTests.ShouldBe(before);
before = lifecycle.PlacementCopiesForTests;
controller.RefreshAnchors();
(lifecycle.PlacementCopiesForTests - before).ShouldBeLessThanOrEqualTo(mappings.Length);
}
private sealed class RenewableLease : IDataAuthorizationLease
{
public bool Valid = true; public bool IsValid => Valid;
public ServingIdentity Serving { get; } = new("remote", "boot", "Primary", 1, 1, 1);
}
private sealed class RenewingBrowseCatalog : IFederatedProjectionCatalog
{
public RenewableLease Lease = new(); public IDataMappedCatalogAuthority Local = null!; public int Fetches;
public TaskCompletionSource Committed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TimeProvider Clock => TimeProvider.System;
public event Action<string, long>? Invalidated { add { } remove { } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => request.Continuation == "invalid"
? new(ProjectionPageStatus.InvalidContinuation, [], false, null, 0)
: Lease.IsValid ? new(ProjectionPageStatus.Ready, [], true, null, 1, Lease, Local)
: new(ProjectionPageStatus.Unavailable, [], false, null, 0);
public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected)
{
var original = Lease;
return new TestPageGuard(() => ReferenceEquals(Lease, original) && original.IsValid && Local.IsActive);
}
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref Fetches); return Task.FromResult<IProjectedPreparedPage>(new RenewalPage(this)); }
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; }
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; }
private sealed class RenewalPage(RenewingBrowseCatalog owner) : IProjectedPreparedPage
{
private readonly RenewableLease _fresh = new();
public ProjectedParentSnapshot Snapshot => new(ProjectionPageStatus.Ready, [], true, null, 1, _fresh, owner.Local);
public bool TryCommit() { owner.Lease = _fresh; owner.Committed.TrySetResult(); return true; }
public void Dispose() { }
}
}
private sealed class BrowseControllerSink : IProjectedNamespacePageSink, IProjectedAnchorSink
{
public ProjectedAnchorDefinition? Anchor; public Opc.Ua.NodeId? AnchorId; public int Removals;
public bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition anchor, out Opc.Ua.NodeId? nodeId)
{ Anchor = anchor; nodeId = AnchorId = new Opc.Ua.NodeId(anchor.LocalIdentifier, 4); return true; }
public bool TryRemoveProjectedAnchor(Opc.Ua.NodeId anchor, ProjectedAnchorDefinition expected) { Removals++; return true; }
public bool TryApply(Opc.Ua.NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit) => commit();
public bool TryRemove(Opc.Ua.NodeId nodeId, ProjectedVariableDefinition expected) => true;
}
private sealed class HeldBrowseCatalog : IFederatedProjectionCatalog
{
public int Calls; public ProjectedBrowseRequest? Last;
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TimeProvider Clock => TimeProvider.System;
public event Action<string, long>? Invalidated { add { } remove { } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => new(ProjectionPageStatus.Pending, [], false, null, 0);
public async Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref Calls); Last = request; Entered.TrySetResult(); await Release.Task.WaitAsync(cancellationToken); return new FailedBrowsePage(); }
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; }
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; }
}
private sealed class FailedBrowsePage : IProjectedPreparedPage
{
public ProjectedParentSnapshot Snapshot => new(ProjectionPageStatus.Unavailable, [], false, null, 0);
public bool TryCommit() => false;
public void Dispose() { }
}
[Fact]
public void Driver_host_activates_only_node_effective_mappings()
{
var bytes = MappingArtifact();
DeploymentArtifact.ParseRemoteNamespaceMappings(bytes, "node-a").ShouldHaveSingleItem();
DeploymentArtifact.ParseRemoteNamespaceMappings(bytes, "node-b").ShouldBeEmpty();
foreach (var node in new[] { "node-a", "node-b" })
{
var authority = new DataPlaneAuthorityState();
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority,
() => BootIdentity with { NodeId = node });
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var acks = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(dbFactory: null, localNode: NodeId.Parse(node), ackRouter: acks.Ref,
localRoles: new HashSet<string> { "driver" }, fetchAndCacheMode: true, artifactFetcher: new MutableFetcher(bytes),
catalogCoordinator: coordinator));
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId()));
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
if (node == "node-a") runtime.Active.ShouldHaveSingleItem().Mapping.RemoteNamespaceMappingId.ShouldBe("map");
else runtime.Active.ShouldBeEmpty();
Sys.Stop(host);
}
}
[Fact]
public void Standalone_publisher_applies_removal_and_failed_topology_closes_mappings()
{
var bytes = MappingArtifact();
var authority = new DataPlaneAuthorityState();
var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var sink = NullOpcUaAddressSpaceSink.Instance;
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
hooks: null, localNode: Node, dataPlaneAuthority: authority, catalogCoordinator: coordinator));
var replies = CreateTestProbe();
void Rebuild(byte[] artifact)
{
replies.Send(actor, new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact, ReportOutcome: true));
replies.ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
Rebuild(bytes);
var previous = runtime.Active.ShouldHaveSingleItem();
Rebuild(MappingArtifact(includeMapping: false));
runtime.Active.ShouldBeEmpty(); previous.Authority.IsActive.ShouldBeFalse();
Rebuild(bytes);
var restored = runtime.Active.ShouldHaveSingleItem();
Rebuild("not json"u8.ToArray());
runtime.Active.ShouldBeEmpty(); restored.Authority.IsActive.ShouldBeFalse();
runtime.TryGetConnectionId("map", out _).ShouldBeFalse();
Sys.Stop(actor);
}
[Fact(Timeout = 30000)]
public async Task Delayed_changed_notification_cannot_reopen_after_a_new_attempt()
{
var bytes = MappingArtifact();
var authority = new DataPlaneAuthorityState();
var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim();
ProjectedMappingPlacement? delayed = null;
runtime.Changed += placements => { if (placements.Count == 0) return; delayed = placements[0]; entered.Set(); release.Wait(TimeSpan.FromSeconds(10)); };
var acks = CreateTestProbe(); var host = NewHost(bytes, coordinator, acks.Ref);
try
{
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId()));
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
coordinator.BeginAttempt("replacement");
runtime.Active.ShouldBeEmpty(); runtime.TryGetConnectionId("map", out _).ShouldBeFalse();
release.Set();
await Task.Run(() => acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken), TestContext.Current.CancellationToken);
delayed.ShouldNotBeNull().Authority.IsActive.ShouldBeFalse();
runtime.Active.ShouldBeEmpty(); runtime.TryGetConnectionId("map", out _).ShouldBeFalse();
}
finally { release.Set(); Sys.Stop(host); }
}
private static byte[] MappingArtifact(bool includeMapping = true)
{
var root = JsonNode.Parse(Artifact())!.AsObject();
root["Nodes"]!.AsArray().Add(JsonNode.Parse("""
{"NodeId":"node-b","ClusterId":"cluster","Host":"node-b","ApplicationUri":"urn:node-b","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}
"""));
root["DataConnectionScopeVersion"] = 1;
root["DataConnections"] = JsonSerializer.SerializeToNode(new[] { new DataConnection { DataConnectionId = "link", ClusterId = "cluster",
Enabled = true, ConsumerNodeIds = ["node-a", "node-b"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "remote-cluster",
ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"], SecretReference = "secret:data/key", SecretScopeClusterId = "cluster",
AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read } });
var mapping = TestMapping(); mapping.ConsumerNodeIds = ["node-a"]; mapping.RemoteNamespaceUri = V3NodeIds.RawNamespaceUri;
root["RemoteNamespaceMappings"] = JsonSerializer.SerializeToNode(includeMapping ? new[] { mapping } : Array.Empty<RemoteNamespaceMapping>());
return Encoding.UTF8.GetBytes(root.ToJsonString());
}
[Fact]
public async Task Returning_to_the_same_role_cannot_revive_a_previous_publication_permit()
{
@@ -0,0 +1,276 @@
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;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
[Fact(Timeout = 90000)]
public async Task Real_sdk_browse_pages_through_nested_projection_and_preserves_array_metadata()
{
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, nestedCatalog: true);
await WithComposedServer(origin, origin.Root, async (session, sink, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var rootReferences = await BrowseAll(client, anchor, 1);
rootReferences.Count.ShouldBe(3);
var folder = rootReferences.Single(x => x.BrowseName.Name == "Driver");
folder.NodeClass.ShouldBe(NodeClass.Object);
var folderNode = ExpandedNodeId.ToNodeId(folder.NodeId, session.NamespaceUris);
var children = await BrowseAll(client, folderNode, 1);
children.Count.ShouldBe(2);
children.Select(x => x.BrowseName.Name).Order().ShouldBe(new[] { "Array", "Speed" });
children.ShouldAllBe(x => x.NodeClass == NodeClass.Variable);
var arrayNode = ExpandedNodeId.ToNodeId(children.Single(x => x.BrowseName.Name == "Array").NodeId, session.NamespaceUris);
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
[new ReadValueId { NodeId = arrayNode, AttributeId = Attributes.ValueRank },
new ReadValueId { NodeId = arrayNode, AttributeId = Attributes.ArrayDimensions },
new ReadValueId { NodeId = arrayNode, AttributeId = Attributes.DataType }], TestContext.Current.CancellationToken);
read.Results.ToArray()!.ShouldAllBe(x => StatusCode.IsGood(x.StatusCode));
read.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(1);
((uint[])read.Results[1].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy)!).ShouldBe(new uint[] { 3 });
read.Results[2].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(DataTypeIds.Byte);
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address with { Identifier = "Plant/Driver/Array" });
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.RawNamespaceUri, id, out var indexed).ShouldBeTrue();
indexed.ShouldNotBeNull().ShouldBe(arrayNode);
});
}
[Fact(Timeout = 90000)]
public async Task Uns_projection_browses_and_reads_the_origin_metadata_through_the_real_registry()
{
using var origin = new LocalDataFixture(servingGeneration: 1, nestedUnsCatalog: true);
var originRoot = origin.Uns with { Address = origin.Uns.Address with { Identifier = "Area" }, Subject = "Area" };
await WithComposedServer(origin, originRoot, async (session, sink, _, _, _, _, anchor) =>
{
var children = await BrowseAll((SessionClient)session, anchor, 1);
var child = children.ShouldHaveSingleItem();
child.BrowseName.Name.ShouldBe("Speed");
child.NodeClass.ShouldBe(NodeClass.Variable);
var node = ExpandedNodeId.ToNodeId(child.NodeId, session.NamespaceUris);
var expected = ProjectedDataIds.Identifier("map", origin.Uns.Address);
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.UnsNamespaceUri, expected, out var indexed).ShouldBeTrue();
indexed.ShouldNotBeNull().ShouldBe(node);
var response = await ((SessionClient)session).ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
[new ReadValueId { NodeId = node, AttributeId = Attributes.ValueRank },
new ReadValueId { NodeId = node, AttributeId = Attributes.DataType }], TestContext.Current.CancellationToken);
response.Results.ToArray()!.ShouldAllBe(x => StatusCode.IsGood(x.StatusCode));
response.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(-1);
response.Results[1].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(DataTypeIds.Int32);
});
}
[Fact(Timeout = 90000)]
public async Task Local_browse_filters_ungranted_sibling_while_preserving_allowed_folder()
{
using var origin = new LocalDataFixture(servingGeneration: 1);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, _) =>
{
var namespaceIndex = session.NamespaceUris.GetIndex(V3NodeIds.RawNamespaceUri);
namespaceIndex.ShouldBeGreaterThan(0);
var root = new NodeId(V3NodeIds.SharedRootFolderId, (ushort)namespaceIndex);
var children = await BrowseAll((SessionClient)session, root, 10);
children.ShouldContain(x => x.DisplayName.Text == "Plant");
children.ShouldNotContain(x => x.DisplayName.Text == "Outside");
}, restrictToPlant: true);
}
[Fact(Timeout = 90000)]
public async Task Mapped_value_root_is_discovered_headlessly_then_read_and_monitored_by_sdk()
{
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin;
origin.Publish(42);
await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) =>
{
var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access,
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
var reference = Reference("map", DataRealm.Raw, origin.Raw.Address);
await using var lease = await discovery.ResolveAsync(reference, TestContext.Current.CancellationToken);
lease.ShouldNotBeNull();
lease.IsValid.ShouldBeTrue();
await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
((IProjectedNodeLookup)sink).TryResolve(anchor, out var root).ShouldBeTrue();
root.ShouldNotBeNull().Metadata.ValueKind.ShouldBe(DataValueKind.Int32);
var client = (SessionClient)session;
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.NodeClass }], TestContext.Current.CancellationToken);
read.Results[0].StatusCode.ShouldBe(StatusCodes.Good);
read.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe((int)NodeClass.Variable);
// A cold SDK read schedules a remote read; the next read can consume its published sample.
var deadline = DateTime.UtcNow.AddSeconds(10);
Opc.Ua.DataValue value;
do
{
var values = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], TestContext.Current.CancellationToken);
value = values.Results[0];
if (StatusCode.IsGood(value.StatusCode)) break;
await Task.Delay(25, TestContext.Current.CancellationToken);
} while (DateTime.UtcNow < deadline);
StatusCode.IsGood(value.StatusCode).ShouldBeTrue();
value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 10, 0, true, 0,
TestContext.Current.CancellationToken)).SubscriptionId;
var monitored = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both,
[new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value },
MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters
{ ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], TestContext.Current.CancellationToken);
monitored.Results[0].StatusCode.ShouldBe(StatusCodes.Good);
access.HasLiveDemand(DataRealm.Raw, ProjectedDataIds.Identifier("map", origin.Raw.Address)).ShouldBeTrue();
});
}
private async Task WithComposedServer(LocalDataFixture origin, DataView root,
Func<ISession, SdkAddressSpaceSink, RemoteNamespaceResolver, ProjectedNamespaceApplier, ProjectedDataAccess, ProjectedMappingDeploymentRuntime, NodeId, Task> exercise,
bool restrictToPlant = false)
{
var ct = TestContext.Current.CancellationToken;
var pki = Path.Combine(Path.GetTempPath(), $"composed-projection-{Guid.NewGuid():N}");
var port = 0;
var started = await OpcUaHostStart.StartAsync(p =>
{
port = p;
return new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ComposedProjection", ApplicationUri = $"urn:composed:{Guid.NewGuid():N}",
OpcUaPort = p, PublicHostname = "127.0.0.1", PkiStoreRoot = pki,
EnabledSecurityProfiles = [OpcUaSecurityProfile.None], AutoAcceptUntrustedClientCertificates = true,
}, NullLogger<OpcUaApplicationHost>.Instance, new PeerAuthenticator(origin.Context));
}, () => new OtOpcUaSdkServer(), ct);
try
{
var connections = new FakeConnections(origin);
var authority = new DataPlaneAuthorityState();
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority,
() => new ServingIdentity("node-a", "boot", "Primary", 0, 0, 1));
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock), origin.Clock);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(16, 128, origin.Clock, policy),
new BrowseContinuationRegistry(16, origin.Clock), connections, policy, 16, 2);
using var placements = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var attempt = Prepare(coordinator, restrictToPlant);
var mapping = Mapping(root);
if (root.Realm == DataRealm.Uns)
{
mapping.Realm = mapping.RemoteRealm = DataRealm.Uns;
mapping.LocalParentKind = "UnsArea";
mapping.LocalParentId = "area";
}
mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata;
placements.Stage(attempt, [mapping], [Connection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
var manager = started.Server.NodeManager!;
manager.ProjectedBrowseClock = origin.Clock;
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
manager.EnsureFolder("Outside", null, "Outside", AddressSpaceRealm.Raw);
if (root.Realm == DataRealm.Uns)
manager.EnsureFolder("area", null, "area", AddressSpaceRealm.Uns);
manager.DataPlaneAuthority = authority;
manager.Authorizer = new DataPlaneAuthorizer(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock),
enabled: true, NullLogger.Instance, origin.Clock);
manager.MappedSubjectResolver = (realm, identifier) =>
resolver.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns, identifier, out var proof) && proof is not null
? MappedNodeResolution.Mapped(proof.Metadata.View, proof.Subject, proof.Resolver, proof.Lease)
: MappedNodeResolution.Deny;
var sink = new SdkAddressSpaceSink(manager);
using var applier = new ProjectedNamespaceApplier(resolver, sink, 2);
using var access = new ProjectedDataAccess(resolver, sink, connections,
id => placements.TryGetConnectionId(id, out var connection) ? connection : null,
policy, new DirectPublisher(sink), origin.Clock, new(8, 4, 8_000_000, 2));
using var browse = new ProjectedBrowseAccess(placements, resolver, applier, sink,
(uri, id) => manager.TryGetNodeId(uri, id, out var node) ? node : null,
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
manager.ProjectedBrowseAccess = browse;
manager.ProjectedDataAccess = access;
var identifier = ProjectedDataIds.Identifier("map", root.Address);
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.NamespaceUri(root.Realm), identifier, out var node).ShouldBeTrue();
var anchor = node.ShouldNotBeNull();
using var session = await ConnectComposed(port, pki, ct);
await exercise(session, sink, resolver, applier, access, placements, anchor);
}
finally
{
await started.Host.DisposeAsync();
if (Directory.Exists(pki)) Directory.Delete(pki, recursive: true);
}
}
private static async Task<List<ReferenceDescription>> BrowseAll(SessionClient client, NodeId node, uint size)
{
var ct = TestContext.Current.CancellationToken;
var response = await client.BrowseAsync(new RequestHeader(), null, size, [new BrowseDescription
{
NodeId = node, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All,
}], ct);
var page = response.Results[0];
StatusCode.IsGood(page.StatusCode).ShouldBeTrue();
var references = new List<ReferenceDescription>(page.References.ToArray()!);
var cursor = page.ContinuationPoint;
while (!cursor.IsEmpty)
{
var next = await client.BrowseNextAsync(new RequestHeader(), false, [cursor], ct);
page = next.Results[0];
StatusCode.IsGood(page.StatusCode).ShouldBeTrue();
references.AddRange(page.References.ToArray()!);
cursor = page.ContinuationPoint;
}
return references;
}
private static async Task<ISession> ConnectComposed(int port, string pki, CancellationToken ct)
{
var clientPki = Path.Combine(pki, "client");
var security = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "own") },
TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "issuer") },
TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "trusted") },
RejectedCertificateStore = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "rejected") },
AutoAcceptUntrustedCertificates = true,
};
var telemetry = DefaultTelemetry.Create(_ => { });
var config = new ApplicationConfiguration(telemetry)
{
ApplicationName = "ComposedClient", ApplicationUri = $"urn:composed-client:{Guid.NewGuid():N}",
ApplicationType = ApplicationType.Client, SecurityConfiguration = security,
ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60_000 },
};
await config.ValidateAsync(ApplicationType.Client, ct);
var endpoint = await CoreClientUtils.SelectEndpointAsync(config, $"opc.tcp://127.0.0.1:{port}/OtOpcUa", false, telemetry, ct);
return await new DefaultSessionFactory(telemetry).CreateAsync(config,
new ConfiguredEndpoint(null, endpoint!, EndpointConfiguration.Create(config)), false, false, "ComposedClient", 60_000,
new UserIdentity("apikey", System.Text.Encoding.UTF8.GetBytes("test-secret")), default, ct);
}
private sealed class DirectPublisher(SdkAddressSpaceSink sink) : IProjectedValuePublisher
{
public bool TryBind(ProjectedValueRoute route) => true;
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates) => ((IProjectedValueSink)sink).TryPublish(
updates.Select(x => new ProjectedValueWrite(x.Route.Realm, x.Route.LocalIdentifier, x.Route.ProjectionGeneration,
x.Route.Serving, x.Snapshot, x.OriginAgeBounds, x.ReceivedTimestamp, x.SourceProof, x.IsCompleteSnapshot)).ToArray());
public void Retire(ProjectedValueRoute route) { }
}
private sealed class PeerAuthenticator(DataAuthenticatedContext context) : IOpcUaUserAuthenticator
{
public Task<OpcUaUserAuthResult> AuthenticateUserNameAsync(string username, string password, CancellationToken ct) =>
Task.FromResult(username == "apikey" && password == "test-secret"
? OpcUaUserAuthResult.AllowKey(context.PrincipalId, [], context.ApiKeyId) with
{ CredentialVersion = context.CredentialVersion, CredentialExpiresUtc = context.CredentialExpiresUtc }
: OpcUaUserAuthResult.Deny("Invalid key"));
}
}
@@ -0,0 +1,77 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataConfiguredAcquisitionTests
{
[Fact(Timeout = 30000)]
public async Task Configured_interest_owns_one_scoped_acquisition_until_last_interest_is_removed()
{
var reference = ProjectedDataIds.DependencyReference(DataRealm.Raw,
ProjectedDataIds.Identifier("mapping", new DataAddress("origin", "urn:raw", "string", "plant/tag")));
var discovery = new Discovery();
await using var owner = new ConfiguredProjectedInterestOwner(discovery, 2);
owner.SetInterest(reference, true);
var token = TestContext.Current.CancellationToken;
await discovery.Started.Task.WaitAsync(TimeSpan.FromSeconds(5), token);
owner.SetInterest(reference, true);
discovery.Calls.ShouldBe(1);
owner.SetInterest(reference, false);
await discovery.Lease.Closed.Task.WaitAsync(TimeSpan.FromSeconds(5), token);
discovery.Lease.Valid.ShouldBeFalse();
}
[Fact(Timeout = 30000)]
public async Task Many_interests_share_a_fixed_acquisition_worker_limit()
{
var discovery = new BlockingDiscovery();
await using var owner = new ConfiguredProjectedInterestOwner(discovery, 16, maxConcurrentCalls: 2);
try
{
for (var i = 0; i < 12; i++)
owner.SetInterest(ProjectedDataIds.DependencyReference(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", new DataAddress("origin", "urn:raw", "string", "plant/" + i))), true);
await discovery.TwoEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
discovery.Maximum.ShouldBe(2);
discovery.Calls.ShouldBe(2);
}
finally { discovery.Release.TrySetResult(); }
}
private sealed class BlockingDiscovery : IConfiguredProjectionDiscovery
{
private int _running; public int Calls, Maximum;
public readonly TaskCompletionSource TwoEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
public readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously);
public async Task<IConfiguredProjectionLease?> ResolveAsync(string reference, CancellationToken cancellationToken)
{
var count = Interlocked.Increment(ref _running); Interlocked.Increment(ref Calls);
if (count > Maximum) Maximum = count;
if (count == 2) TwoEntered.TrySetResult();
try { await Release.Task.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); return new ScopedLease(); }
finally { Interlocked.Decrement(ref _running); }
}
}
private sealed class Discovery : IConfiguredProjectionDiscovery
{
public int Calls;
public readonly TaskCompletionSource Started = new(TaskCreationOptions.RunContinuationsAsynchronously);
public readonly ScopedLease Lease = new();
public Task<IConfiguredProjectionLease?> ResolveAsync(string reference, CancellationToken cancellationToken)
{
Interlocked.Increment(ref Calls); Started.TrySetResult();
return Task.FromResult<IConfiguredProjectionLease?>(Lease);
}
}
private sealed class ScopedLease : IConfiguredProjectionLease
{
public bool Valid = true;
public bool IsValid => Valid;
public readonly TaskCompletionSource Closed = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ValueTask DisposeAsync() { Valid = false; Closed.TrySetResult(); return ValueTask.CompletedTask; }
}
}
@@ -0,0 +1,261 @@
using System.Security.Cryptography;
using System.Text;
using System.Threading.Channels;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
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;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08Wire")]
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
[Fact(Timeout = 15000)]
public void Mint_reuses_one_mapping_capability_until_the_published_attempt_changes()
{
using var origin = new LocalDataFixture(servingGeneration: 1);
var authority = new DataPlaneAuthorityState();
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority,
() => new ServingIdentity("node-a", "boot", "Primary", 0, 0, 1));
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock), origin.Clock);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(16, 128, origin.Clock, policy),
new BrowseContinuationRegistry(16, origin.Clock), new FakeConnections(origin), policy, 16, 2);
using var placements = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var attempt = Prepare(coordinator);
var mapping = Mapping(origin.Root);
placements.Stage(attempt, [mapping], [Connection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
placements.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var first, out var firstPlacement).ShouldBeTrue();
placements.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var second, out var secondPlacement).ShouldBeTrue();
first.ShouldNotBeNull(); firstPlacement.ShouldNotBeNull(); secondPlacement.ShouldNotBeNull();
second.ShouldBeSameAs(first);
firstPlacement!.Mapping.Revision++;
secondPlacement!.Mapping.Revision.ShouldBe(1);
var replacement = Prepare(coordinator);
placements.Stage(replacement, [mapping], [Connection()]);
coordinator.Complete(replacement, true).ShouldBeTrue();
placements.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var fresh, out var freshPlacement).ShouldBeTrue();
fresh.ShouldNotBeNull().ShouldNotBeSameAs(first);
first!.Matches("map", freshPlacement!.Anchor, freshPlacement!.Authority).ShouldBeFalse();
}
[Fact(Timeout = 90000)]
public async Task Configured_interest_browses_and_subscribes_without_an_sdk_caller_and_retires_on_removal_and_deployment()
{
var pki = Path.Combine(Path.GetTempPath(), $"configured-projection-{Guid.NewGuid():N}");
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ConfiguredProjection", ApplicationUri = $"urn:configured:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
try
{
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin;
var connections = new FakeConnections(origin);
var authority = new DataPlaneAuthorityState();
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority,
() => new ServingIdentity("node-a", "boot", "Primary", 0, 0, 1));
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock), origin.Clock);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(16, 128, origin.Clock, policy),
new BrowseContinuationRegistry(16, origin.Clock), connections, policy, 16, 2);
using var placements = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var attempt = Prepare(coordinator);
var mapping = Mapping(origin.Root);
placements.Stage(attempt, [mapping], [Connection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
var placement = placements.Active.ShouldHaveSingleItem();
var manager = started.Server.NodeManager!;
manager.ShouldNotBeNull();
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
manager.TryGetNodeId(V3NodeIds.RawNamespaceUri, "Plant", out var parentId).ShouldBeTrue();
var parent = parentId.ShouldNotBeNull();
var sink = new SdkAddressSpaceSink(manager);
var anchorId = ProjectedDataIds.Identifier("map", placement.Anchor.Address);
var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, anchorId, parent, "Remote", "Plant/Remote", "map", 1,
() => placement.Authority.IsActive);
((IProjectedAnchorSink)sink).TryEnsureProjectedAnchor(anchor, out _).ShouldBeTrue();
using var applier = new ProjectedNamespaceApplier(resolver, sink, 2);
using var access = new ProjectedDataAccess(resolver, sink, connections,
id => placements.TryGetConnectionId(id, out var connection) ? connection : null,
policy, new Publisher(), origin.Clock, new(8, 4, 2_000_000, 2));
var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access,
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
var reference = Reference("map", DataRealm.Raw, origin.Raw.Address);
var identifier = ProjectedDataIds.Identifier("map", origin.Raw.Address);
await using (var owner = new ConfiguredProjectedInterestOwner(discovery, 8))
{
owner.SetInterest(reference, true);
await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
connections.BrowseCalls.ShouldBeGreaterThan(0);
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.RawNamespaceUri, identifier, out var node).ShouldBeTrue();
node.ShouldNotBeNull();
((IProjectedNodeLookup)sink).TryResolve(node!.Value, out var materialized).ShouldBeTrue();
materialized.ShouldNotBeNull();
access.HasLiveDemand(DataRealm.Raw, identifier).ShouldBeTrue();
var wrongMap = Reference("unconfigured", DataRealm.Raw, origin.Raw.Address);
var wrongRealm = Reference("map", DataRealm.Uns, origin.Raw.Address);
(await discovery.ResolveAsync(wrongMap, TestContext.Current.CancellationToken)).ShouldBeNull();
(await discovery.ResolveAsync(wrongRealm, TestContext.Current.CancellationToken)).ShouldBeNull();
var forged = origin.Raw.Address with { Identifier = "outside-the-exported-page" };
(await discovery.ResolveAsync(Reference("map", DataRealm.Raw, forged), TestContext.Current.CancellationToken)).ShouldBeNull();
subscriptions.Opens.ShouldBe(1, "decoded addresses must not create a subscription without a verified page");
var browsesBeforeExpiry = connections.BrowseCalls;
origin.Clock.Advance(TimeSpan.FromSeconds(16));
await subscriptions.Closed.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
connections.BrowseCalls.ShouldBeGreaterThan(browsesBeforeExpiry, "expired metadata must be renewed from the peer");
access.HasLiveDemand(DataRealm.Raw, identifier).ShouldBeTrue();
owner.SetInterest(reference, false);
await subscriptions.Closed.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
}
await using (var owner = new ConfiguredProjectedInterestOwner(discovery, 8))
{
owner.SetInterest(reference, true);
await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
var replacement = Prepare(coordinator);
await subscriptions.Closed.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
mapping.Enabled = false;
placements.Stage(replacement, [mapping], [Connection()]);
coordinator.Complete(replacement, true).ShouldBeTrue();
(await discovery.ResolveAsync(reference, TestContext.Current.CancellationToken)).ShouldBeNull();
}
}
finally
{
await started.Host.DisposeAsync();
if (Directory.Exists(pki)) Directory.Delete(pki, recursive: true);
}
}
private static string Reference(string mapping, DataRealm realm, DataAddress address) =>
ProjectedDataIds.DependencyReference(realm, ProjectedDataIds.Identifier(mapping, address));
private static RemoteNamespaceMapping Mapping(DataView root) => new()
{
RemoteNamespaceMappingId = "map", ClusterId = "cluster", DataConnectionId = "link", Revision = 1,
Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, LocalParentKind = "RawFolder",
LocalParentId = "folder", BranchName = "Remote", RemoteRootEntityId = root.Subject,
RemoteNamespaceUri = root.Address.NamespaceUri, RemoteIdentifierKind = root.Address.IdentifierKind,
RemoteIdentifier = root.Address.Identifier, AllowedOperations = DataOperations.Browse | DataOperations.Subscribe,
MetadataLeaseMilliseconds = 15000, StaleTimeoutMilliseconds = 30000,
};
private static DataConnection Connection() => new()
{ DataConnectionId = "link", ClusterId = "cluster", Enabled = true, ExpectedClusterId = "cluster" };
private static CatalogAttempt Prepare(LocalCatalogCoordinator coordinator, bool restrictToPlant = false)
{
var bytes = Encoding.UTF8.GetBytes("""
{"Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}],
"Nodes":[{"NodeId":"node-a","ClusterId":"cluster","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}],
"ApiKeys":[{"ApiKeyId":"peer-key","Name":"peer-key","SecretHash":"hash","Principal":"peer","Enabled":true}],
"NodeAcls":[{"NodeAclId":"acl","ClusterId":"cluster","Principal":"peer","ScopeKind":0,"PermissionFlags":7}],
"RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}],
"DriverInstances":[],"Devices":[],"TagGroups":[],"Tags":[],"UnsAreas":[{"UnsAreaId":"area","ClusterId":"cluster","Name":"area"}],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[],
"DataConnections":[],"RemoteNamespaceMappings":[],
"DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":7}]}
""");
if (restrictToPlant)
bytes = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bytes).Replace(
"\"ScopeKind\":0,\"PermissionFlags\":7", "\"ScopeKind\":7,\"ScopeId\":\"folder\",\"PermissionFlags\":7", StringComparison.Ordinal));
var attempt = coordinator.BeginAttempt(Convert.ToHexStringLower(SHA256.HashData(bytes)));
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue();
using var parsed = DeploymentArtifact.Open(bytes);
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!).ShouldBeTrue();
return attempt;
}
private sealed class Publisher : IProjectedValuePublisher
{
public bool TryBind(ProjectedValueRoute route) => true;
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates) => true;
public void Retire(ProjectedValueRoute route) { }
}
private sealed class FakeConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private int _browseCalls;
public int BrowseCalls => Volatile.Read(ref _browseCalls);
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null);
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => connection.DisposeAsync();
}
private sealed class Connection(IDataConnection inner, FakeConnections owner) : IDataConnection
{
public DataTarget Target => inner.Target;
public TimeProvider Clock => inner.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._browseCalls); return inner.BrowseAsync(request, cancellationToken); }
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken);
public Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken);
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
}
private sealed class FakeSubscriptions(Func<ServingIdentity> serving) : IDataSubscriptionService
{
public readonly Channel<int> Opened = Channel.CreateUnbounded<int>();
public readonly Channel<int> Closed = Channel.CreateUnbounded<int>();
private int _opens;
public int Opens => Volatile.Read(ref _opens);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
var number = Interlocked.Increment(ref _opens);
return Task.FromResult<IDataSubscription>(new Stream(this, serving(), number));
}
private sealed class Stream(FakeSubscriptions owner, ServingIdentity serving, int number) : IDataSubscription, IDataSubscriptionProvenance
{
private readonly Channel<DataSubscriptionFrame> _frames = Channel.CreateUnbounded<DataSubscriptionFrame>();
private readonly Dictionary<DataItemHandle, string> _ids = new();
private long _sequence;
private ulong _handle;
public ServingIdentity Serving => serving;
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
IReadOnlyList<DataSubscriptionItem> items = command switch { OpenSubscription open => open.Items, AddSubscriptionItems add => add.Items, _ => [] };
var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good,
new DataItemHandle(command.SubscriptionId, command.StreamEpoch, ++_handle, 1), item.Settings, null)).ToArray();
foreach (var ack in acks) if (ack.Handle is not null) _ids[ack.Handle] = ack.ClientItemId;
if (command is RemoveSubscriptionItems remove)
acks = remove.Items.Select(handle => new DataSubscriptionItemAck(_ids[handle], DataItemStatus.Good, handle, null, null)).ToArray();
_frames.Writer.TryWrite(new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++_sequence, command.CommandId, acks));
if (items.Count > 0)
{
owner.Opened.Writer.TryWrite(number);
_frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));
_frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));
}
return Task.CompletedTask;
}
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); owner.Closed.Writer.TryWrite(number); return ValueTask.CompletedTask; }
}
}
}
@@ -0,0 +1,37 @@
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataConfiguredInterestTests : RuntimeActorTestBase
{
[Fact(Timeout = 30000)]
public void Mux_notifies_only_first_and_last_configured_projected_interest()
{
var events = CreateTestProbe(); var first = CreateTestProbe(); var second = CreateTestProbe();
var sink = new Sink(events.Ref);
var mux = Sys.ActorOf(DependencyMuxActor.Props(interestSink: sink));
var id = ProjectedDataIds.Identifier("mapping", new DataAddress("origin", "urn:raw", "string", "plant/tag"));
var reference = ProjectedDataIds.DependencyReference(DataRealm.Raw, id);
mux.Tell(new DependencyMuxActor.RegisterInterest([reference, "ordinary"], first.Ref));
events.ExpectMsg<Transition>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken).ShouldBe(new Transition(reference, true));
mux.Tell(new DependencyMuxActor.RegisterInterest([reference], second.Ref));
mux.Tell(new DependencyMuxActor.RegisterInterest([reference], first.Ref));
mux.Tell(new DependencyMuxActor.UnregisterInterest(first.Ref));
events.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken);
mux.Tell(new DependencyMuxActor.UnregisterInterest(second.Ref));
events.ExpectMsg<Transition>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken).ShouldBe(new Transition(reference, false));
}
private sealed record Transition(string Reference, bool Active);
private sealed class Sink(IActorRef target) : IProjectedDependencyInterestSink
{
public void SetInterest(string projectedReference, bool active) => target.Tell(new Transition(projectedReference, active));
}
}
@@ -82,6 +82,132 @@ public sealed class GrpcDataConnectionClientTests
await Should.ThrowAsync<InvalidOperationException>(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken));
}
[Fact]
public async Task Strict_generation_mismatch_is_rejected_without_dispatch_or_rebinding()
{
var first = new FailoverHandler("a", true);
var second = new FailoverHandler("b", false);
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null),
[new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"),
65536, 2, eligibleNodeIds: new HashSet<string> { "a", "b" });
using var value = DataValue.FromScalar(DataValueKind.Int32, 1);
var result = await connection.WriteAsync(new([new("retry", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 2)], Budget), TestContext.Current.CancellationToken);
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
first.WrittenIds.ShouldBeEmpty(); second.WrittenIds.ShouldBeEmpty();
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Strict_discovery_skips_unavailable_or_mismatching_peer_before_first_dispatch(bool unavailable)
{
var first = new FailoverHandler("a", false, generation: 1, unavailable: unavailable);
var second = new FailoverHandler("b", false, generation: 2);
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null),
[new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"),
65536, 2, eligibleNodeIds: new HashSet<string> { "a", "b" });
using var value = DataValue.FromScalar(DataValueKind.Int32, 1);
var result = await connection.WriteAsync(new([new("item", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 2)], Budget), TestContext.Current.CancellationToken);
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
first.WrittenIds.ShouldBeEmpty(); second.WrittenIds.ShouldBe(new[] { "item" });
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Failed_legacy_metadata_does_not_block_strict_item_on_matching_endpoint(bool malformed)
{
var first = new FailoverHandler("a", true, generation: 1);
var second = new FailoverHandler("b", false, generation: 2, metadataFailure: !malformed, badMetadata: malformed);
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null),
[new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"),
65536, 2, eligibleNodeIds: new HashSet<string> { "a", "b" });
using var legacy = DataValue.FromScalar(DataValueKind.Int32, 1);
using var strict = DataValue.FromScalar(DataValueKind.Int32, 2);
var result = await connection.WriteAsync(new([
new("retry", "legacy", View, legacy, 1, "boot", TimeSpan.FromSeconds(4)),
new("strict", "strict", View, strict, 1, "boot", TimeSpan.FromSeconds(4), 2)], Budget), TestContext.Current.CancellationToken);
result.Select(x => x.Outcome.State).ShouldBe([DataWriteState.RejectedBeforeDispatch, DataWriteState.DriverConfirmedSuccess]);
first.WrittenIds.ShouldBe(new[] { "retry" });
second.WrittenIds.ShouldBe(new[] { "strict" });
}
[Fact]
public async Task Failed_legacy_metadata_preserves_strict_item_for_a_later_matching_endpoint()
{
var first = new FailoverHandler("a", true, generation: 1);
var second = new FailoverHandler("b", false, generation: 2, metadataFailure: true);
var third = new FailoverHandler("c", false, generation: 3, metadataFailure: true);
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null),
[new Uri("https://a.test"), new Uri("https://b.test"), new Uri("https://c.test")], new TripleSecurity(first, second, third), manager.Acquire("link"),
65536, 3, eligibleNodeIds: new HashSet<string> { "a", "b", "c" });
using var legacy = DataValue.FromScalar(DataValueKind.Int32, 1);
using var strict = DataValue.FromScalar(DataValueKind.Int32, 2);
var result = await connection.WriteAsync(new([
new("retry", "legacy", View, legacy, 1, "boot", TimeSpan.FromSeconds(4)),
new("strict", "strict", View, strict, 1, "boot", TimeSpan.FromSeconds(4), 3)], Budget), TestContext.Current.CancellationToken);
result.Select(x => x.Outcome.State).ShouldBe([DataWriteState.RejectedBeforeDispatch, DataWriteState.DriverConfirmedSuccess]);
first.WrittenIds.ShouldBe(new[] { "retry" }); second.WrittenIds.ShouldBeEmpty();
third.WrittenIds.ShouldBe(new[] { "strict" });
}
[Fact]
public async Task Strict_generation_rejection_is_not_rebound_to_another_primary()
{
var first = new FailoverHandler("a", true);
var second = new FailoverHandler("b", false);
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null),
[new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"),
65536, 2, eligibleNodeIds: new HashSet<string> { "a", "b" });
using var value = DataValue.FromScalar(DataValueKind.Int32, 1);
var result = await connection.WriteAsync(new([new("retry", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 1)], Budget), TestContext.Current.CancellationToken);
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
first.WrittenIds.ShouldBe(new[] { "retry" }); second.WrittenIds.ShouldBeEmpty();
}
[Fact]
public async Task Legacy_peer_remains_readable_but_does_not_advertise_writable_metadata()
{
var handler = new WireHandler { NoWriteGenerationEnforcement = true };
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1);
var caps = await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
(caps.Operations & DataOperations.Read).ShouldBe(DataOperations.Read);
(caps.Operations & DataOperations.Write).ShouldBe(DataOperations.None);
var branch = await connection.BrowseAsync(new(View, null, null, Budget), TestContext.Current.CancellationToken);
branch.Items.ShouldHaveSingleItem().Writable.ShouldBeFalse();
(branch.Items[0].AllowedOperations & DataOperations.Write).ShouldBe(DataOperations.None);
var metadata = await connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken);
metadata.ShouldHaveSingleItem().Value!.Writable.ShouldBeFalse();
(metadata[0].Value!.AllowedOperations & DataOperations.Write).ShouldBe(DataOperations.None);
}
[Fact]
public async Task Peer_without_generation_enforcement_is_never_sent_a_write()
{
var handler = new WireHandler { NoWriteGenerationEnforcement = true, LoseWrite = true };
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1);
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
var result = await connection.WriteAsync(new([new("item", "op", View, value, 1, "boot", TimeSpan.FromSeconds(4))], Budget), TestContext.Current.CancellationToken);
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
handler.WriteCalls.ShouldBe(0);
}
[Fact]
public async Task Lost_write_reply_is_unknown_and_is_not_resent()
{
@@ -207,25 +333,35 @@ public sealed class GrpcDataConnectionClientTests
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca1", "key", () => endpoint.Host == "a.test" ? first : second));
}
private sealed class FailoverHandler(string node, bool rejectFirst, Action? onCapabilities = null, Action? onMetadata = null) : HttpMessageHandler
private sealed class TripleSecurity(FailoverHandler first, FailoverHandler second, FailoverHandler third) : IDataConnectionSecurityProvider
{
public event Action<string>? Changed { add { } remove { } }
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca1", "key", () => endpoint.Host switch
{ "a.test" => first, "b.test" => second, _ => third }));
}
private sealed class FailoverHandler(string node, bool rejectFirst, Action? onCapabilities = null, Action? onMetadata = null,
long generation = 1, bool unavailable = false, bool metadataFailure = false, bool badMetadata = false) : HttpMessageHandler
{
public List<string> WrittenIds { get; } = [];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var serving = new ServingIdentity(node, "boot", "Primary", 1, 1, 1);
var serving = new ServingIdentity(node, "boot", "Primary", 1, 1, generation);
IMessage message;
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
{
onCapabilities?.Invoke();
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, serving, DataReadiness.Ready,
if (unavailable) throw new HttpRequestException("unavailable");
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, serving, DataReadiness.Ready,
DataOperations.Read | DataOperations.Write | DataOperations.Metadata, new HashSet<DataValueKind> { DataValueKind.Int32 },
Limits, false, 0, "c", false, true));
Limits, false, 0, "c", false, true, true));
}
else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal))
{
onMetadata?.Invoke();
if (metadataFailure) throw new HttpRequestException("metadata unavailable");
var metadata = new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Write,
2, null, null, false);
badMetadata ? 2 : 1, null, null, false);
var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]);
wire.Serving = DataProtoMapper.EncodeServing(serving); message = wire;
}
@@ -751,6 +887,7 @@ public sealed class GrpcDataConnectionClientTests
private sealed class WireHandler : HttpMessageHandler
{
public bool LoseWrite { get; init; }
public bool NoWriteGenerationEnforcement { get; init; }
public bool WrongReadServing { get; init; }
public bool ZeroServingGeneration { get; init; }
public bool BadBrowseLease { get; init; }
@@ -759,9 +896,9 @@ public sealed class GrpcDataConnectionClientTests
{
IMessage message;
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, ZeroServingGeneration ? Serving with { ServingGeneration = 0 } : Serving, DataReadiness.Ready,
DataOperations.Read | DataOperations.Write, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits,
false, 0, "c", false, true));
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, NoWriteGenerationEnforcement ? 2 : 3, ZeroServingGeneration ? Serving with { ServingGeneration = 0 } : Serving, DataReadiness.Ready,
DataOperations.Read | DataOperations.Write | DataOperations.Browse | DataOperations.Metadata, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits,
false, 0, "c", false, true, !NoWriteGenerationEnforcement));
else if (request.RequestUri.AbsolutePath.EndsWith("/Write", StringComparison.Ordinal))
{
WriteCalls++;
@@ -770,10 +907,17 @@ public sealed class GrpcDataConnectionClientTests
}
else if (request.RequestUri.AbsolutePath.EndsWith("/Browse", StringComparison.Ordinal))
{
var browse = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good, [], true, null,
var children = NoWriteGenerationEnforcement ? new[] { new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Write, 1, null, null, false) } : [];
var browse = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good, children, true, null,
new MetadataLease(Serving.CatalogEpoch, BadBrowseLease ? Serving.AuthorityEpoch + 1 : Serving.AuthorityEpoch, TimeSpan.FromSeconds(1))));
browse.Serving = DataProtoMapper.EncodeServing(Serving); message = browse;
}
else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal))
{
var metadata = new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Write, 1, null, null, false);
var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]);
wire.Serving = DataProtoMapper.EncodeServing(Serving); message = wire;
}
else if (request.RequestUri.AbsolutePath.EndsWith("/Read", StringComparison.Ordinal))
message = new W.ReadResponse { Serving = DataProtoMapper.EncodeServing(WrongReadServing ? Serving with { Incarnation = "other" } : Serving) };
else throw new InvalidOperationException("Unexpected call.");
@@ -0,0 +1,56 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataContinuationTests
{
[Fact]
public void Cursor_is_bound_to_caller_mapping_parent_filter_and_full_remote_generation()
{
var clock = new ManualTimeProvider(); var registry = new BrowseContinuationRegistry(4, clock);
var binding = Binding(); var token = registry.Issue(binding, "peer-secret-cursor", TimeSpan.FromSeconds(15));
token.ShouldNotContain("peer-secret-cursor");
registry.TryPrepare(token, binding with { PrincipalId = "other" }, out _).ShouldBeFalse();
registry.TryPrepare(token, binding with { Filter = "different" }, out _).ShouldBeFalse();
registry.TryPrepare(token, binding with { MappingRevision = 2 }, out _).ShouldBeFalse();
registry.TryPrepare(token, binding with { RemoteServing = binding.RemoteServing with { ServingGeneration = 2 } }, out _).ShouldBeFalse();
registry.TryPrepare(token, binding, out var prepared).ShouldBeTrue();
prepared.ShouldNotBeNull().RemoteCursor.ShouldBe("peer-secret-cursor");
prepared.Dispose();
registry.TryPrepare(token, binding, out var retry).ShouldBeTrue();
retry.ShouldNotBeNull().TryCommit(nextPeerCursor: null, out _).ShouldBeTrue();
registry.TryPrepare(token, binding, out _).ShouldBeFalse();
}
[Fact]
public void Expired_or_capacity_exhausted_handles_fail_closed()
{
var clock = new ManualTimeProvider(); var registry = new BrowseContinuationRegistry(1, clock);
var binding = Binding(); var token = registry.Issue(binding, "cursor", TimeSpan.FromSeconds(1));
Should.Throw<InvalidOperationException>(() => registry.Issue(binding, "second", TimeSpan.FromSeconds(1)));
clock.Advance(TimeSpan.FromSeconds(2));
registry.TryPrepare(token, binding, out _).ShouldBeFalse();
registry.Issue(binding, "replacement", TimeSpan.FromSeconds(1)).ShouldNotBeNullOrWhiteSpace();
}
[Fact]
public void Invalidation_between_prepare_and_commit_cannot_publish_a_stale_cursor()
{
var registry = new BrowseContinuationRegistry(1, new ManualTimeProvider());
var binding = Binding(); var token = registry.Issue(binding, "old", TimeSpan.FromSeconds(10));
registry.TryPrepare(token, binding, out var prepared).ShouldBeTrue();
registry.InvalidateMapping(binding.MappingId);
prepared!.TryCommit("new", out var next).ShouldBeFalse();
next.ShouldBeNull();
registry.TryPrepare(token, binding, out _).ShouldBeFalse();
}
private static BrowseContinuationBinding Binding() => new("peer", "key", "credential", "mapping", 1,
new DataView(new DataAddress("origin", "urn:raw", "string", "plant"), DataRealm.Raw, "mapping", 1, "local/anchor"),
null, 4, new ServingIdentity("node", "boot", "Primary", 8, 9, 1));
}
@@ -0,0 +1,583 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataFederatedBrowseTests
{
[Fact]
public void Missing_or_unavailable_parent_is_not_reported_as_a_successful_empty_branch()
{
var clock = new ManualTimeProvider(); var cache = new ProjectedCatalogCache(4, 8, clock);
var request = Request(clock);
var pending = cache.TryGetParent(request);
pending.Status.ShouldBe(ProjectionPageStatus.Pending);
pending.Complete.ShouldBeFalse();
cache.MarkUnavailable(request.MappingId, request.Parent);
var unavailable = cache.TryGetParent(request);
unavailable.Status.ShouldBe(ProjectionPageStatus.Unavailable);
unavailable.Complete.ShouldBeFalse();
}
[Fact]
public void Unknown_projected_identity_fails_closed_instead_of_becoming_local()
{
var clock = new ManualTimeProvider(); var cache = new ProjectedCatalogCache(4, 8, clock);
cache.TryResolveProjected(DataRealm.Raw, "unknown", out var proof).ShouldBeFalse();
proof.ShouldBeNull();
}
[Fact]
public void Empty_complete_page_expires_with_its_authority_lease()
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller };
cache.CaptureGeneration(request.MappingId).ShouldBe(1);
var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)),
fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock);
var local = fixture.Activation.CaptureAuthority();
var page = new ProjectedParentSnapshot(ProjectionPageStatus.Ready, [], true, null, 1,
Lease: lease, LocalAuthority: local, ParentProof: ParentProof(fixture, request, lease, local));
cache.TryPublish(request, page).ShouldBeTrue();
cache.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Ready);
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
cache.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Unavailable);
}
[Fact]
public void Invalidated_pinned_metadata_stays_charged_until_last_pin_is_released()
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(4, 1, fixture.Clock, policy);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller };
cache.CaptureGeneration(request.MappingId).ShouldBe(1);
var local = fixture.Activation.CaptureAuthority();
var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, fixture.Clock);
ProjectedNodeProof Proof(string id, string identifier, long generation = 1)
{
var view = new DataView(new DataAddress("origin", "urn:raw", "string", identifier), DataRealm.Raw, "mapping", 1, "Plant/branch/" + id);
var scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch", id] };
var subject = new MappedNamespaceSubject(view, scope, ["folder"], lease.Serving, DataOperations.Browse);
var resolver = new MappedSubjectResolver([subject], fixture.Serving.CatalogEpoch, local);
var metadata = new DataMetadata(view, id, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: lease.Serving);
var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/" + id } };
return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, lease, generation, origin);
}
var first = Proof("first", "first");
first.OriginMetadata.View.Subject.ShouldBe("origin/first");
first.OriginMetadata.View.MappingId.ShouldBeNull();
first.Metadata.View.MappingId.ShouldBe("mapping");
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [first], true, null, 1, lease, local, ParentProof(fixture, request, lease, local))).ShouldBeTrue();
cache.TryPinProjected(DataRealm.Raw, first.LocalIdentifier, out var pin).ShouldBeTrue();
cache.MarkUnavailable(request.MappingId, request.Parent);
cache.TryResolveProjected(DataRealm.Raw, first.LocalIdentifier, out _).ShouldBeFalse();
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [Proof("second", "second", 2)], true, null, 2, lease, local, ParentProof(fixture, request, lease, local, 2))).ShouldBeFalse();
pin!.Dispose();
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [Proof("second", "second", 2)], true, null, 2, lease, local, ParentProof(fixture, request, lease, local, 2))).ShouldBeTrue();
}
[Fact]
public void Empty_page_still_consumes_the_aggregate_metadata_byte_budget()
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy, maxBytes: 128);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller };
cache.CaptureGeneration(request.MappingId);
var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock);
var local = fixture.Activation.CaptureAuthority();
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [], true, null, 1, lease, local, ParentProof(fixture, request, lease, local))).ShouldBeFalse();
}
[Fact]
public void Empty_page_cannot_bypass_local_parent_browse_authorization()
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping");
var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock);
var local = fixture.Activation.CaptureAuthority();
var denied = ParentProof(fixture, request, lease, local, forbidden: true);
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [], true, null, 1, lease, local, denied)).ShouldBeFalse();
}
[Fact(Timeout = 30000)]
public async Task Prepared_remote_page_keeps_origin_subject_and_publishes_only_after_commit()
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy);
var source = new FakeProjectionSource(fixture.Clock, fixture.Serving);
using var resolver = new RemoteNamespaceResolver(cache, new BrowseContinuationRegistry(8, fixture.Clock), source, policy, 4, 8);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller };
var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mapping", ClusterId = "cluster", DataConnectionId = "connection",
Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, BranchName = "branch", RemoteRootEntityId = "root",
RemoteNamespaceUri = "urn:raw", RemoteIdentifierKind = "string", RemoteIdentifier = "plant", AllowedOperations = DataOperations.Browse };
resolver.ApplyMappings([new ProjectedMappingBinding(mapping, request.Parent,
new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch"] },
["folder"], fixture.Activation.CaptureAuthority(), (_, _) => false)]);
using var prepared = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
prepared.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
resolver.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Pending);
var item = prepared.Snapshot.Items.ShouldHaveSingleItem();
item.OriginMetadata.View.Subject.ShouldBe("origin/child");
item.OriginMetadata.View.MappingId.ShouldBeNull();
item.Metadata.View.MappingId.ShouldBe("mapping");
prepared.TryCommit().ShouldBeTrue();
resolver.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Ready);
resolver.TryResolveProjected(DataRealm.Raw, item.LocalIdentifier, out var live).ShouldBeTrue();
live.ShouldNotBeNull().OriginMetadata.View.Subject.ShouldBe("origin/child");
}
[Fact(Timeout = 30000)]
public async Task Concurrent_identical_browse_waiters_share_one_bounded_origin_fetch()
{
using var fixture = new LocalDataFixture();
var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.BlockBrowse = true;
using var resolver = CreateResolver(fixture, source, out var request);
var ct = TestContext.Current.CancellationToken;
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
Task<IProjectedPreparedPage>? firstTask = null, secondTask = null;
try
{
firstTask = resolver.PreparePageAsync(request, stop.Token);
await source.Connection.BrowseEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
secondTask = resolver.PreparePageAsync(request, stop.Token);
source.Connection.ReleaseBrowse.TrySetResult();
using var first = await firstTask.WaitAsync(TimeSpan.FromSeconds(5), ct);
using var second = await secondTask.WaitAsync(TimeSpan.FromSeconds(5), ct);
first.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
second.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
source.Connection.BrowseCalls.ShouldBe(1);
first.TryCommit().ShouldBeTrue();
second.TryCommit().ShouldBeTrue();
}
finally
{
source.Connection.ReleaseBrowse.TrySetResult(); stop.Cancel();
await DrainAsync(firstTask); await DrainAsync(secondTask);
}
}
[Fact(Timeout = 30000)]
public async Task Retiring_mapping_before_commit_fences_the_prepared_page()
{
using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving);
using var resolver = CreateResolver(fixture, source, out var request);
using var prepared = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
prepared.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
resolver.ApplyMappings([]);
prepared.TryCommit().ShouldBeFalse();
resolver.TryResolveProjected(DataRealm.Raw, prepared.Snapshot.Items[0].LocalIdentifier, out _).ShouldBeFalse();
}
[Fact(Timeout = 30000)]
public async Task Cancelling_one_shared_waiter_does_not_cancel_the_other()
{
using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.BlockBrowse = true;
using var resolver = CreateResolver(fixture, source, out var request);
using var cancelFirst = new CancellationTokenSource(); var ct = TestContext.Current.CancellationToken;
Task<IProjectedPreparedPage>? first = null, second = null;
try
{
first = resolver.PreparePageAsync(request, cancelFirst.Token);
await source.Connection.BrowseEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
second = resolver.PreparePageAsync(request, ct);
cancelFirst.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await first.WaitAsync(TimeSpan.FromSeconds(5), ct));
source.Connection.ReleaseBrowse.TrySetResult();
using var result = await second.WaitAsync(TimeSpan.FromSeconds(5), ct);
result.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
source.Connection.BrowseCalls.ShouldBe(1);
}
finally { source.Connection.ReleaseBrowse.TrySetResult(); cancelFirst.Cancel(); await DrainAsync(first); await DrainAsync(second); }
}
[Fact(Timeout = 30000)]
public async Task Last_cancelled_waiter_keeps_physical_capacity_until_peer_finishes()
{
using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving);
source.Connection.BlockBrowse = true; source.Connection.IgnoreCancellation = true;
using var resolver = CreateResolver(fixture, source, out var request);
using var cancel = new CancellationTokenSource(); var ct = TestContext.Current.CancellationToken;
Task<IProjectedPreparedPage>? first = null;
try
{
first = resolver.PreparePageAsync(request, cancel.Token);
await source.Connection.BrowseEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
cancel.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await first.WaitAsync(TimeSpan.FromSeconds(5), ct));
using (var blocked = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct))
blocked.Snapshot.Status.ShouldBe(ProjectionPageStatus.Unavailable);
source.Connection.BrowseCalls.ShouldBe(1);
source.Connection.ReleaseBrowse.TrySetResult();
await source.LeaseDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
using var after = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
after.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
}
finally { source.Connection.ReleaseBrowse.TrySetResult(); cancel.Cancel(); await DrainAsync(first); }
}
[Fact(Timeout = 30000)]
public async Task Duplicate_sibling_across_pages_is_rejected_without_consuming_the_cursor()
{
using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving);
source.Connection.DuplicateSecondPage = true;
using var resolver = CreateResolver(fixture, source, out var request); var ct = TestContext.Current.CancellationToken;
using var first = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
first.Snapshot.Complete.ShouldBeFalse(); first.TryCommit().ShouldBeTrue();
var next = first.Snapshot.Continuation.ShouldNotBeNull();
var followup = request with { Continuation = next };
using var second = await resolver.PreparePageAsync(followup, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
second.TryCommit().ShouldBeFalse();
using var retry = await resolver.PreparePageAsync(followup, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
retry.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
}
[Fact(Timeout = 30000)]
public async Task Unversioned_remote_serving_generation_cannot_authorize_a_projection()
{
using var fixture = new LocalDataFixture();
var source = new FakeProjectionSource(fixture.Clock, fixture.Serving with { ServingGeneration = 0 }, preserveGeneration: true);
using var resolver = CreateResolver(fixture, source, out var request);
using var result = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
result.Snapshot.Status.ShouldBe(ProjectionPageStatus.Unavailable);
}
[Fact]
public void Expired_unpinned_pages_and_nodes_are_reclaimed_for_new_work()
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(1, 1, fixture.Clock, policy);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping");
var local = fixture.Activation.CaptureAuthority();
MetadataAuthorityLease Lease() => new(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock);
var firstLease = Lease(); var first = ParentProof(fixture, request, firstLease, local);
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [first], true, null, 1, firstLease, local, first)).ShouldBeTrue();
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
var secondRequest = request with { Filter = "new-filter" }; var secondLease = Lease(); var second = ParentProof(fixture, secondRequest, secondLease, local);
cache.TryPublish(secondRequest, new(ProjectionPageStatus.Ready, [second], true, null, 1, secondLease, local, second)).ShouldBeTrue();
cache.TryGetParent(secondRequest).Status.ShouldBe(ProjectionPageStatus.Ready);
}
[Fact]
public void Pinned_expired_proof_does_not_prevent_current_identical_placement_from_renewing()
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(2, 2, fixture.Clock, policy);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping");
var local = fixture.Activation.CaptureAuthority();
MetadataAuthorityLease Lease() => new(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock);
var oldLease = Lease(); var old = ParentProof(fixture, request, oldLease, local);
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [old], true, null, 1, oldLease, local, old)).ShouldBeTrue();
cache.TryPinProjected(DataRealm.Raw, old.LocalIdentifier, out var pin).ShouldBeTrue();
try
{
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
var renewedLease = Lease(); var renewed = ParentProof(fixture, request, renewedLease, local);
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [renewed], true, null, 1, renewedLease, local, renewed)).ShouldBeTrue();
cache.TryResolveProjected(DataRealm.Raw, old.LocalIdentifier, out var current).ShouldBeTrue();
current.ShouldNotBeNull().Lease.ShouldBeSameAs(renewedLease);
}
finally { pin!.Dispose(); }
}
[Fact]
public void Parent_filter_and_caller_identifiers_are_charged_to_byte_budget()
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy, maxBytes: 4096);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller, Filter = new string('x', 5000) }; cache.CaptureGeneration("mapping");
var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock);
var local = fixture.Activation.CaptureAuthority(); var parent = ParentProof(fixture, request, lease, local);
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [], true, null, 1, lease, local, parent)).ShouldBeFalse();
}
[Fact(Timeout = 30000)]
public async Task Projection_depth_is_relative_to_mapping_anchor_not_local_scope_depth()
{
using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving);
using var resolver = CreateResolver(fixture, source, out var request, maximumDepth: 1);
using var result = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
result.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
result.TryCommit().ShouldBeTrue();
}
[Fact(Timeout = 30000)]
public async Task Mapping_node_limit_applies_across_continuation_pages()
{
using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving);
source.Connection.DistinctSecondPage = true;
using var resolver = CreateResolver(fixture, source, out var request, maximumNodes: 1);
var ct = TestContext.Current.CancellationToken;
using var first = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
first.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); first.TryCommit().ShouldBeTrue();
var next = first.Snapshot.Continuation.ShouldNotBeNull();
using var second = await resolver.PreparePageAsync(request with { Continuation = next }, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
(second.Snapshot.Status != ProjectionPageStatus.Ready || !second.TryCommit()).ShouldBeTrue();
}
[Fact(Timeout = 30000)]
public async Task Cancelled_queued_fetches_remain_bounded_until_physical_work_finishes()
{
using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving);
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var entered = new SemaphoreSlim(0);
Task BeforeFetch(CancellationToken _) { entered.Release(); return gate.Task; }
using var resolver = CreateResolver(fixture, source, out var request, beforeFetch: BeforeFetch);
var ct = TestContext.Current.CancellationToken;
try
{
for (var i = 0; i < 16; i++)
{
using var cancel = new CancellationTokenSource();
var task = resolver.PreparePageAsync(request with { Filter = i.ToString() }, cancel.Token);
(await entered.WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue();
cancel.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await task.WaitAsync(TimeSpan.FromSeconds(5), ct));
}
resolver.OutstandingPhysicalJobs.ShouldBe(16);
using var rejected = await resolver.PreparePageAsync(request with { Filter = "overflow" }, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
rejected.Snapshot.Status.ShouldBe(ProjectionPageStatus.Unavailable);
resolver.OutstandingPhysicalJobs.ShouldBe(16);
}
finally { gate.TrySetResult(); }
await resolver.WaitForPhysicalJobsAsync().WaitAsync(TimeSpan.FromSeconds(5), ct);
resolver.OutstandingPhysicalJobs.ShouldBe(0);
using var recovered = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
recovered.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
}
[Fact]
public void Publishing_a_fresh_page_does_not_revalidate_unrelated_live_pages()
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(8, 8, fixture.Clock, policy);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping");
var local = fixture.Activation.CaptureAuthority();
var inner = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock);
var tracked = new CountingLease(inner); var parent = ParentProof(fixture, request, tracked, local);
cache.TryPublish(request, new(ProjectionPageStatus.Ready, [parent], true, null, 1, tracked, local, parent)).ShouldBeTrue();
tracked.Reads = 0;
var other = request with { Filter = "another-query" }; var otherParent = ParentProof(fixture, other, inner, local);
cache.TryPublish(other, new(ProjectionPageStatus.Ready, [], true, null, 1, inner, local, otherParent)).ShouldBeTrue();
tracked.Reads.ShouldBe(0);
}
[Fact]
public void Captured_page_validity_does_not_revisit_siblings_for_each_returned_name()
{
using var fixture = new LocalDataFixture();
var (cache, request, tracked) = LargeGuardPage(fixture);
var page = cache.TryGetParent(request);
var guard = cache.CaptureParentGuard(request, page).ShouldNotBeNull();
tracked.Reads = 0;
for (var i = 0; i < 200; i++) guard.IsCurrent.ShouldBeTrue();
tracked.Reads.ShouldBe(0, "per-child emission checks must not authorize the other 199 siblings again");
cache.MarkUnavailable(request.MappingId, request.Parent);
guard.IsCurrent.ShouldBeFalse();
}
[Fact]
public void Captured_page_guard_does_not_keep_a_retired_page_graph_alive()
{
using var fixture = new LocalDataFixture();
var (cache, request, _) = LargeGuardPage(fixture);
var (guard, weak) = Capture(cache, request);
cache.MarkUnavailable(request.MappingId, request.Parent);
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();
weak.IsAlive.ShouldBeFalse("a cursor guard owns its detached control proof, not the retired page graph");
guard.IsCurrent.ShouldBeFalse();
GC.KeepAlive(guard);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
static (IProjectedPageGuard Guard, WeakReference Page) Capture(ProjectedCatalogCache cache, ProjectedBrowseRequest request)
{
var page = cache.TryGetParent(request);
return (cache.CaptureParentGuard(request, page).ShouldNotBeNull(), new WeakReference(page));
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Oversized_origin_metadata_is_charged_for_parent_and_child_proofs(bool child)
{
using var fixture = new LocalDataFixture();
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy, maxBytes: 32768);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller };
cache.CaptureGeneration(request.MappingId);
var local = fixture.Activation.CaptureAuthority();
var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)),
fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock);
var parent = ParentProof(fixture, request, lease, local);
var large = parent with { OriginMetadata = parent.OriginMetadata with { StableSourceId = new string('x', 32768), EngineeringUnits = new string('u', 32768) } };
cache.TryPublish(request, new(ProjectionPageStatus.Ready, child ? [large] : [], true, null, 1, lease, local, child ? parent : large)).ShouldBeFalse();
}
private static (ProjectedCatalogCache Cache, ProjectedBrowseRequest Request, CountingLease Tracked) LargeGuardPage(LocalDataFixture fixture)
{
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(4, 512, fixture.Clock, policy);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
var request = Request(fixture.Clock) with { Caller = caller, Budget = new DataBudget(TimeSpan.FromSeconds(3), 256, 1_000_000) };
cache.CaptureGeneration("mapping");
var local = fixture.Activation.CaptureAuthority();
var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)),
fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock);
var tracked = new CountingLease(lease);
var children = Enumerable.Range(0, 200).Select(index =>
{
var id = "child" + index;
var view = request.Parent with { Address = request.Parent.Address with { Identifier = id }, Subject = "local/anchor/" + id };
var subject = new MappedNamespaceSubject(view,
new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", id] }, ["folder"], lease.Serving, DataOperations.Browse);
var metadata = new DataMetadata(view, id, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: lease.Serving);
var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/" + id } };
return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject,
new MappedSubjectResolver([subject], 1, local), tracked, 1, origin);
}).ToArray();
cache.TryPublish(request, new(ProjectionPageStatus.Ready, children, true, null, 1, lease, local,
ParentProof(fixture, request, lease, local))).ShouldBeTrue();
return (cache, request, tracked);
}
private sealed class CountingLease(IDataAuthorizationLease inner) : IDataAuthorizationLease
{
public int Reads { get; set; }
public bool IsValid { get { Reads++; return inner.IsValid; } }
public ServingIdentity Serving => inner.Serving;
}
[Fact(Timeout = 30000)]
public async Task Per_mapping_limit_reclaims_expired_nodes_even_when_global_capacity_is_available()
{
using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving);
source.Connection.DistinctFiltered = true;
using var resolver = CreateResolver(fixture, source, out var request, maximumNodes: 1);
var ct = TestContext.Current.CancellationToken;
using (var first = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct))
{ first.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); first.TryCommit().ShouldBeTrue(); }
fixture.Clock.Advance(TimeSpan.FromSeconds(11));
var next = request with { Filter = "other", RequestStartedTimestamp = fixture.Clock.GetTimestamp() };
using var second = await resolver.PreparePageAsync(next, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
second.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready);
second.TryCommit().ShouldBeTrue();
}
private static async Task DrainAsync(Task<IProjectedPreparedPage>? task)
{
if (task is null) return;
try { (await task.WaitAsync(TimeSpan.FromSeconds(5))).Dispose(); }
catch (Exception ex) when (ex is OperationCanceledException or TimeoutException or InvalidOperationException) { }
}
private static RemoteNamespaceResolver CreateResolver(LocalDataFixture fixture, IGrpcDataAdapterConnectionSource source, out ProjectedBrowseRequest request, int? maximumDepth = null, int? maximumNodes = null, Func<CancellationToken, Task>? beforeFetch = null)
{
var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock);
var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy);
var resolver = new RemoteNamespaceResolver(cache, new BrowseContinuationRegistry(8, fixture.Clock), source, policy, 4, 1, beforeFetch);
var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc);
request = Request(fixture.Clock) with { Caller = caller };
var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mapping", ClusterId = "cluster", DataConnectionId = "connection",
Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, BranchName = "branch", RemoteRootEntityId = "root",
RemoteNamespaceUri = "urn:raw", RemoteIdentifierKind = "string", RemoteIdentifier = "plant", AllowedOperations = DataOperations.Browse };
if (maximumDepth is { } depth) mapping.MaxProjectionDepth = depth;
if (maximumNodes is { } nodes) mapping.MaxProjectionNodes = nodes;
resolver.ApplyMappings([new ProjectedMappingBinding(mapping, request.Parent,
new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch"] },
["folder"], fixture.Activation.CaptureAuthority(), (_, _) => false)]);
return resolver;
}
private sealed class FakeProjectionSource(TimeProvider clock, ServingIdentity serving, bool preserveGeneration = false) : IGrpcDataAdapterConnectionSource
{
public FakeProjectionConnection Connection { get; } = new(clock, !preserveGeneration && serving.ServingGeneration == 0 ? serving with { ServingGeneration = 1 } : serving);
public TaskCompletionSource LeaseDisposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new FakeProjectionLease(Connection, () => LeaseDisposed.TrySetResult()));
}
private sealed class FakeProjectionLease(IDataConnection connection, Action released) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() { released(); return ValueTask.CompletedTask; }
}
private sealed class FakeProjectionConnection(TimeProvider clock, ServingIdentity serving) : IDataConnection
{
public DataTarget Target => new(DataTargetMode.Node, "origin", "remote");
public TimeProvider Clock => clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{
var root = request.Views[0] with { Subject = "origin/root" };
var metadata = new DataMetadata(root, "root", "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: serving);
return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>([new("0", DataItemStatus.Good, metadata, null)]);
}
public bool BlockBrowse { get; set; }
public bool IgnoreCancellation { get; set; }
public bool DuplicateSecondPage { get; set; }
public bool DistinctSecondPage { get; set; }
public bool DistinctFiltered { get; set; }
public TaskCompletionSource BrowseEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource ReleaseBrowse { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _browseCalls;
public int BrowseCalls => Volatile.Read(ref _browseCalls);
public async Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _browseCalls); BrowseEntered.TrySetResult();
if (BlockBrowse) await ReleaseBrowse.Task.WaitAsync(TimeSpan.FromSeconds(5), IgnoreCancellation ? CancellationToken.None : cancellationToken);
var id = ((DuplicateSecondPage || DistinctSecondPage) && request.Continuation is not null || DistinctFiltered && request.Filter is not null) ? "plant/other-child" : "plant/child";
var child = new DataView(new DataAddress("origin", "urn:raw", "string", id), DataRealm.Raw, null, 0, "origin/child");
var metadata = new DataMetadata(child, (DistinctSecondPage && request.Continuation is not null || DistinctFiltered && request.Filter is not null) ? "other" : "child", "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: serving);
var continuation = (DuplicateSecondPage || DistinctSecondPage) && request.Continuation is null ? "peer-next" : null;
return new DataBrowseBranch(request.Parent, DataItemStatus.Good, [metadata], continuation is null, continuation, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), serving);
}
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => throw new NotSupportedException();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private static ProjectedNodeProof ParentProof(LocalDataFixture fixture, ProjectedBrowseRequest request,
IDataAuthorizationLease lease, IDataMappedCatalogAuthority local, long generation = 1, bool forbidden = false)
{
var view = request.Parent;
var scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = [forbidden ? "Forbidden" : "Plant"] };
var subject = new MappedNamespaceSubject(view, scope, ["folder"], lease.Serving, DataOperations.Browse);
var resolver = new MappedSubjectResolver([subject], fixture.Serving.CatalogEpoch, local);
var metadata = new DataMetadata(view, "branch", "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: lease.Serving);
var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/plant" } };
return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, lease, generation, origin);
}
private static ProjectedBrowseRequest Request(TimeProvider clock) => new("mapping",
new DataView(new DataAddress("origin", "urn:raw", "string", "plant"), DataRealm.Raw, "mapping", 1, "local/anchor"),
null, null, new DataCallerIdentity("peer", "key", "credential", null),
new DataBudget(TimeSpan.FromSeconds(3), 20, 10000), clock.GetTimestamp());
}
@@ -20,6 +20,8 @@ public sealed class GrpcDataLocalConnectionTests
await using var connection = fixture.Services.Create(context, new(DataTargetMode.Node, "cluster", "node-a"));
var budget = LocalDataFixture.Budget with { MaxItems = 1 };
var branch = await connection.BrowseAsync(new(fixture.Root, null, null, budget), TestContext.Current.CancellationToken);
branch.Serving.ShouldNotBeNull();
branch.Items.ShouldAllBe(x => x.Serving == branch.Serving);
branch.Status.ShouldBe(DataItemStatus.Good);
branch.Lease!.Duration.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(1));
branch.Continuation.ShouldNotBeNull();
@@ -127,15 +129,16 @@ internal sealed class LocalDataFixture : IDisposable
internal LocalDataFixture(int additionalRawNodes = 0,
Func<DataAuthenticatedContext, IDataSubscriptionService>? subscriptions = null,
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null,
bool advanceAuthority = false, string role = "Primary")
bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false)
{
Serving = Serving with { Role = role };
Serving = Serving with { Role = role, ServingGeneration = servingGeneration };
Hub = HubTest.Create(clock: Clock, bytes: 1_000_000);
Hub.TryBind(Ticket).ShouldBeTrue();
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
Authority.Apply("cluster", "first", [key],
[new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder,
ScopeId = "folder", PermissionFlags = NodePermissions.ReadOnly }],
[new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer",
ScopeKind = nestedUnsCatalog ? NodeAclScopeKind.Cluster : NodeAclScopeKind.RawFolder,
ScopeId = nestedUnsCatalog ? null : "folder", PermissionFlags = NodePermissions.ReadOnly }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
if (advanceAuthority)
{
@@ -153,10 +156,24 @@ internal sealed class LocalDataFixture : IDisposable
var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false);
var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false);
var unsMetadata = rawMetadata with { View = Uns };
var folder = Root with { Address = Root.Address with { Identifier = "Plant/Driver" }, Subject = "Plant/Driver" };
var unsRoot = Uns with { Address = Uns.Address with { Identifier = "Area" }, Subject = "Area" };
var nodes = new List<LocalDataNode>
{new("RawFolder", "folder", rootMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant"] }, null, null),
new("RawTag", "tag", rawMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed"] }, Root, Ticket.Key),
new("UnsTagReference", "reference", unsMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area", "Line", "Equipment", "Speed"] }, null, Ticket.Key)};
new("RawTag", "tag", rawMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed"] }, nestedCatalog ? folder : Root, Ticket.Key),
new("UnsTagReference", "reference", unsMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area", "Line", "Equipment", "Speed"] }, nestedUnsCatalog ? unsRoot : null, Ticket.Key)};
if (nestedUnsCatalog)
nodes.Add(new("UnsArea", "area", rootMetadata with { View = unsRoot, BrowseName = "Area" },
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area"] }, null, null));
if (nestedCatalog)
{
nodes.Add(new("RawFolder", "nested-folder", rootMetadata with { View = folder, BrowseName = "Driver" },
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver"] }, Root, null));
var array = Raw with { Address = Raw.Address with { Identifier = "Plant/Driver/Array" }, Subject = "Plant/Driver/Array" };
nodes.Add(new("RawTag", "array", rawMetadata with { View = array, BrowseName = "Array", ValueKind = DataValueKind.Array,
ValueRank = 1, Dimensions = [3], ArrayElementKind = DataValueKind.UInt8 },
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Array"] }, folder, Ticket.Key));
}
for (var i = 0; i < additionalRawNodes; i++)
{
var view = Raw with { Address = Raw.Address with { Identifier = Raw.Address.Identifier + i }, Subject = Raw.Subject + i };
@@ -165,7 +182,7 @@ internal sealed class LocalDataFixture : IDisposable
}
Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes,
[new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations },
new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "UnsTagReference", RootEntityId = "reference", PrincipalId = "peer", AllowedOperations = operations }]);
new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]);
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits);
Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority,
@@ -0,0 +1,501 @@
using Opc.Ua;
using System.Threading.Channels;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataProjectedAccessTests
{
[Fact]
public void Acquisition_pins_the_exact_materialized_origin_and_disposal_fences_it()
{
using var fixture = new AccessFixture();
using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
demand.ShouldNotBeNull().OriginView.ShouldBe(fixture.Proof.OriginMetadata.View);
demand.MaximumSampleAge.ShouldBe(TimeSpan.FromSeconds(30));
access.HasLiveDemand(DataRealm.Raw, fixture.Proof.LocalIdentifier).ShouldBeTrue();
demand.Serving.ShouldBe(fixture.Proof.Lease.Serving);
demand.ProjectionGeneration.ShouldBe(fixture.Proof.Generation);
fixture.Pins.ShouldBe(1);
demand.IsValid.ShouldBeTrue();
demand.Dispose();
demand.IsValid.ShouldBeFalse();
fixture.Pins.ShouldBe(0);
access.HasLiveDemand(DataRealm.Raw, fixture.Proof.LocalIdentifier).ShouldBeFalse();
}
[Fact]
public void Changed_materialization_or_revoked_proof_cannot_be_acquired_or_stay_live()
{
using var fixture = new AccessFixture(); using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
fixture.Current = false;
demand.ShouldNotBeNull().IsValid.ShouldBeFalse();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
demand.Dispose();
fixture.Current = true;
fixture.Definition = fixture.Definition with { ProjectionGeneration = 2 };
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
}
[Fact]
public void Demand_admission_is_bounded_and_recovered_when_idle_demand_is_disposed()
{
using var fixture = new AccessFixture(); using var access = fixture.Create(maxDemands: 1);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
first.ShouldNotBeNull().Dispose();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var next).ShouldBeTrue();
next.ShouldNotBeNull().Dispose();
}
[Fact]
public void Demand_pins_sdk_incarnation_until_disposal_and_force_retirement_fences_it()
{
using var fixture = new AccessFixture(); using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
fixture.Definition.Lifetime.TryRetire().ShouldBeFalse();
fixture.Definition.Lifetime.ForceRetire();
demand.ShouldNotBeNull().IsValid.ShouldBeFalse();
demand.Dispose();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
}
[Fact]
public void Browse_demand_uses_the_original_caller_and_live_proof()
{
using var fixture = new AccessFixture(); using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Browse, out var demand).ShouldBeTrue();
demand.ShouldNotBeNull().IsValid.ShouldBeTrue();
fixture.Current = false;
demand.IsValid.ShouldBeFalse();
demand.Dispose();
}
[Fact]
public void Missing_freshness_policy_never_authorizes_terminal_read()
{
using var fixture = new AccessFixture(); fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.Zero };
using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
}
[Fact(Timeout = 30000)]
public async Task Read_source_pins_sdk_incarnation_until_mapping_invalidation_retires_it()
{
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
fixture.Publish(7);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Definition.Lifetime.TryRetire().ShouldBeFalse();
fixture.InvalidateMapping();
await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
update.SourceProof.IsValid.ShouldBeFalse();
fixture.Definition.Lifetime.TryRetire().ShouldBeTrue();
}
[Fact(Timeout = 30000)]
public async Task Invalidation_during_source_attachment_does_not_strand_its_pins()
{
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
fixture.BeforeBind = () => fixture.InvalidateMapping();
fixture.Publish(7);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
fixture.Definition.Lifetime.TryRetire().ShouldBeTrue();
fixture.Published.Task.IsCompleted.ShouldBeFalse();
}
[Fact(Timeout = 30000)]
public async Task Mapping_invalidation_never_waits_for_the_publication_lock()
{
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
fixture.Publish(7);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var field = typeof(ProjectedDataAccess).GetField("_sync", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
using var release = new ManualResetEventSlim();
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var token = TestContext.Current.CancellationToken;
var publication = Task.Run(() =>
{
lock (field.GetValue(access)!) { entered.TrySetResult(); release.Wait(TimeSpan.FromSeconds(10), token).ShouldBeTrue(); }
}, token);
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), token);
try { await Task.Run(() => fixture.InvalidateMapping(), token).WaitAsync(TimeSpan.FromSeconds(2), token); }
finally { release.Set(); await publication; }
await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
[Fact(Timeout = 30000)]
public async Task Paused_source_retirement_does_not_queue_unowned_mapping_history()
{
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
using var release = new ManualResetEventSlim();
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
access.BeforeSourceRetirementForTests = () => { entered.TrySetResult(); release.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); };
fixture.Publish(7);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.InvalidateMapping();
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
try
{
for (var i = 0; i < 10000; i++) fixture.InvalidateMapping("historical-" + i);
access.PendingSourceRetirementsForTests.ShouldBe(1, "only the owned source bucket can require retirement work");
}
finally { release.Set(); await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
}
[Fact(Timeout = 30000)]
public async Task Read_without_subscribe_permission_preserves_origin_age_timestamps_and_source_proof()
{
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
fixture.Publish(42);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
update.IsCompleteSnapshot.ShouldBeTrue();
update.Snapshot.Value.ShouldBe(42);
update.Snapshot.StatusCode.ShouldBe(0x00000400u);
update.Snapshot.SourceTimestampUtc.ShouldBeNull();
update.Snapshot.ServerTimestampUtc.ShouldNotBeNull();
update.OriginAgeBounds.Upper.ShouldNotBeNull();
update.SourceProof.IsValid.ShouldBeTrue();
update.Route.Serving.ShouldBe(fixture.Proof.Lease.Serving);
update.Route.ProjectionGeneration.ShouldBe(fixture.Proof.Generation);
fixture.Current = false;
update.SourceProof.IsValid.ShouldBeFalse();
}
[Fact(Timeout = 30000)]
public async Task Renewed_metadata_replaces_expired_source_without_reviving_old_publication()
{
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
fixture.Publish(42);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
access.ScheduleRead(first!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
var old = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Renew();
old.SourceProof.IsValid.ShouldBeFalse();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue();
access.ScheduleRead(second!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
var fresh = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fresh.SourceProof.IsValid.ShouldBeTrue();
fresh.Route.PublicationId.ShouldNotBe(old.Route.PublicationId);
old.SourceProof.IsValid.ShouldBeFalse();
}
[Fact(Timeout = 30000)]
public async Task Strict_write_dispatch_uses_exact_origin_and_preserves_unknown_without_publishing_value()
{
using var fixture = new AccessFixture(writable: true); using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
var result = await access.WriteAsync(demand!, 42, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
var sent = fixture.SentWrite.ShouldNotBeNull().Items.ShouldHaveSingleItem();
sent.View.ShouldBe(fixture.Proof.OriginMetadata.View);
sent.ExpectedCatalogRevision.ShouldBe(fixture.Proof.OriginMetadata.CatalogRevision);
sent.ExpectedServingIncarnation.ShouldBe(fixture.Proof.Lease.Serving.Incarnation);
sent.ExpectedServingGeneration.ShouldBe(fixture.Proof.Lease.Serving.ServingGeneration);
sent.OperationId.ShouldNotBeNullOrWhiteSpace();
fixture.Published.Task.IsCompleted.ShouldBeFalse();
demand!.Dispose();
}
[Fact(Timeout = 30000)]
public async Task Local_primary_generation_change_before_dispatch_rejects_write_even_after_role_returns()
{
using var fixture = new AccessFixture(writable: true) { BlockAcquire = true }; using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
try
{
var task = access.WriteAsync(demand!, 42, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
await fixture.AcquireEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.RoleGeneration = 2; fixture.RoleAllowed = false;
fixture.RoleGeneration = 3; fixture.RoleAllowed = true;
fixture.ReleaseAcquire.TrySetResult();
var outcome = await task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
fixture.SentWrite.ShouldBeNull();
}
finally { fixture.ReleaseAcquire.TrySetResult(); demand?.Dispose(); }
}
[Fact(Timeout = 30000)]
public async Task Compatible_distinct_views_share_stream_and_last_demand_closes_physical_owner()
{
using var fixture = new AccessFixture(streams: true); using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue();
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue();
try
{
access.StartSubscription(first!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
access.StartSubscription(second!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.StreamOpens.ShouldBe(1);
first!.Dispose();
await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.StreamClosed.Task.IsCompleted.ShouldBeFalse();
second!.Dispose();
await fixture.StreamClosed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
finally { first?.Dispose(); second?.Dispose(); }
}
[Fact(Timeout = 30000)]
public async Task Subscribe_only_demand_can_request_a_fresh_snapshot_without_read_permission()
{
using var fixture = new AccessFixture(streams: true, subscribeOnly: true); using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue();
try
{
access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
await fixture.FirstStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
access.RequestFreshSnapshot(demand!).ShouldBeTrue();
await fixture.SecondStreamOpened.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.StreamClosed.Task.IsCompleted.ShouldBeTrue();
demand!.IsValid.ShouldBeTrue();
}
finally { demand?.Dispose(); }
}
[Fact]
public void Array_metadata_admission_uses_structural_dimensions_not_list_identity()
{
using var fixture = new AccessFixture(array: true); using var access = fixture.Create();
fixture.Definition = fixture.Definition with { Metadata = fixture.Definition.Metadata with { Dimensions = new[] { 3 } } };
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
demand.ShouldNotBeNull().Dispose();
}
[Fact(Timeout = 30000)]
public async Task Array_write_preserves_owned_shape_and_value()
{
using var fixture = new AccessFixture(writable: true, array: true); using var access = fixture.Create();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
var input = new[] { 8, 9, 10 };
var result = await access.WriteAsync(demand!, input, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
input[0] = 99;
fixture.CapturedArray.ShouldBe(new object[] { 8, 9, 10 });
demand!.Dispose();
}
[Fact(Timeout = 30000)]
public async Task Array_read_and_write_preserve_owned_one_dimensional_values()
{
using var fixture = new AccessFixture(writable: true, array: true); using var access = fixture.Create();
var original = new[] { 2, 4, 6 }; fixture.ReadElements = original;
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var read).ShouldBeTrue();
access.ScheduleRead(read!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
original[0] = 99;
update.Snapshot.Value.ShouldBeOfType<int[]>().ShouldBe(new[] { 2, 4, 6 });
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var write).ShouldBeTrue();
var written = new[] { 8, 9, 10 };
var result = await access.WriteAsync(write!, written, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
written[0] = 100;
fixture.CapturedArray.ShouldBe(new object[] { 8, 9, 10 });
write!.Dispose();
}
[Fact(Timeout = 30000)]
public async Task Array_subscription_snapshot_is_published_as_an_owned_typed_array()
{
using var fixture = new AccessFixture(streams: true, array: true); using var access = fixture.Create();
fixture.ReadElements = [2, 4, 6];
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue();
try
{
access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
update.IsCompleteSnapshot.ShouldBeTrue();
update.Snapshot.Value.ShouldBeOfType<int[]>().ShouldBe(new[] { 2, 4, 6 });
}
finally { demand?.Dispose(); }
}
private sealed class AccessFixture : IFederatedProjectionCatalog, IProjectedNodeLookup, IGrpcDataAdapterConnectionSource, IProjectedValuePublisher, IDisposable
{
private readonly LocalDataFixture _local = new(servingGeneration: 1);
private readonly DataOperationPolicy _policy;
internal readonly NodeId NodeId = new("projected", 2);
internal readonly NodeId SecondNodeId = new("projected-two", 2);
internal ProjectedNodeProof? SecondProof;
internal ProjectedVariableDefinition? SecondDefinition;
internal int StreamOpens;
internal readonly TaskCompletionSource FirstStreamItem = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource SecondStreamOpened = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource TwoStreamItems = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource ItemRemoved = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource StreamClosed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly bool _streams;
private readonly bool _array;
internal int[] ReadElements = [2, 4, 6];
internal object[]? CapturedArray;
internal readonly RoleCarryingUserIdentity Caller;
internal ProjectedNodeProof Proof;
internal ProjectedVariableDefinition Definition;
internal bool Current = true;
internal int Pins;
internal TaskCompletionSource<ProjectedValueUpdate> Published = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal void Renew()
{
var lease = new MetadataAuthorityLease(_local.Serving, new(1, 1, TimeSpan.FromSeconds(15)), _local.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, _local.Clock);
Proof = Proof with { Lease = lease };
Definition = Definition with { AuthorityIsCurrent = () => Current };
Published = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
internal void Publish(int value) => _local.Publish(value);
internal WriteBatch? SentWrite;
internal bool BlockAcquire, RoleAllowed = true;
internal long RoleGeneration = 1;
internal readonly TaskCompletionSource AcquireEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource ReleaseAcquire = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal AccessFixture(bool readOnly = false, bool writable = false, bool streams = false, bool subscribeOnly = false, bool array = false)
{
_streams = streams; _array = array;
var authority = _local.Authority;
if (writable)
{
authority = new DataPlaneAuthorityState();
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
authority.Apply("cluster", "first", [key], [new NodeAcl { NodeAclId = "write", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "folder", PermissionFlags = NodePermissions.Operator }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
}
_policy = new(authority, new TriePermissionEvaluator(authority.Tries, _local.Clock), _local.Clock);
Caller = new(new AnonymousIdentityToken(), [], _local.Context.PrincipalId, _local.Context.ApiKeyId, _local.Context.CredentialVersion, _local.Context.CredentialExpiresUtc);
var origin = _local.Raw;
var mapped = origin with { MappingId = "mapping", MappingRevision = 1, Subject = "Plant/branch/Speed" };
var serving = _local.Serving;
var operations = subscribeOnly ? DataOperations.Subscribe : readOnly ? DataOperations.Read : DataOperations.Browse | DataOperations.Read | DataOperations.Subscribe | (writable ? DataOperations.Write : DataOperations.None);
var subject = new MappedNamespaceSubject(mapped, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch", "Speed"] }, ["folder"], serving, operations, writable);
var metadata = new DataMetadata(mapped, "Speed", "Variable", DataValueKind.Int32, -1, [], writable, operations, 1, null, null, false, Serving: serving);
if (array) metadata = metadata with { ValueKind = DataValueKind.Array, ValueRank = 1, Dimensions = [3], ArrayElementKind = DataValueKind.Int32 };
var lease = new MetadataAuthorityLease(serving, new(1, 1, TimeSpan.FromSeconds(15)), _local.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, _local.Clock);
Proof = new(ProjectedDataIds.Identifier("mapping", origin.Address), metadata, subject, new([subject], 1, _local.Activation.CaptureAuthority()), lease, 1, metadata with { View = origin }, TimeSpan.FromSeconds(30));
Definition = new(DataRealm.Raw, Proof.LocalIdentifier, new NodeId("parent", 2), metadata, 1, () => Current);
if (streams)
{
var secondOrigin = origin with { Address = origin.Address with { Identifier = origin.Address.Identifier + "2" }, Subject = origin.Subject + "2" };
var secondView = mapped with { Address = secondOrigin.Address, Subject = mapped.Subject + "2" };
var secondSubject = subject with { View = secondView, Scope = subject.Scope with { Segments = ["Plant", "branch", "Speed2"] } };
var secondMetadata = metadata with { View = secondView, BrowseName = "Speed2" };
SecondProof = new(ProjectedDataIds.Identifier("mapping", secondOrigin.Address), secondMetadata, secondSubject, new([secondSubject], 1, _local.Activation.CaptureAuthority()), lease, 1, secondMetadata with { View = secondOrigin }, TimeSpan.FromSeconds(30));
SecondDefinition = new(DataRealm.Raw, SecondProof.LocalIdentifier, new NodeId("parent", 2), secondMetadata, 1, () => Current);
}
}
internal ProjectedDataAccess Create(int maxDemands = 4) => new(this, this, this, _ => "link", _policy, this, _local.Clock, new(maxDemands, 4, 2000000, 2), () => (RoleAllowed, RoleGeneration));
public TimeProvider Clock => _local.Clock;
public event Action<string, long>? Invalidated;
internal readonly TaskCompletionSource ConnectionDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource NoPins = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal void InvalidateMapping(string mapping = "mapping") { if (mapping == "mapping") Current = false; Invalidated?.Invoke(mapping, 2); }
public bool TryResolveProjected(DataRealm realm, string id, out ProjectedNodeProof? proof) { proof = Current && realm == DataRealm.Raw ? id == Proof.LocalIdentifier ? Proof : id == SecondProof?.LocalIdentifier ? SecondProof : null : null; return proof is not null; }
public bool TryPinProjected(DataRealm realm, string id, out IDisposable? pin) { if (!Current || id != Proof.LocalIdentifier && id != SecondProof?.LocalIdentifier) { pin = null; return false; } Pins++; pin = new Pin(this); return true; }
private sealed class Pin(AccessFixture owner) : IDisposable { private int _done; public void Dispose() { if (Interlocked.Exchange(ref _done, 1) == 0 && Interlocked.Decrement(ref owner.Pins) == 0) owner.NoPins.TrySetResult(); } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => throw new NotSupportedException();
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) { definition = nodeId == NodeId ? Definition : nodeId == SecondNodeId ? SecondDefinition : null; return definition is not null; }
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) { nodeId = NodeId; return true; }
public async ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
AcquireEntered.TrySetResult();
if (BlockAcquire) await ReleaseAcquire.Task.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
return new ConnectionLease(new TestConnection(_local.Connection(), this), this);
}
private sealed class TestConnection(IDataConnection inner, AccessFixture owner) : IDataConnection
{
public DataTarget Target => inner.Target;
public TimeProvider Clock => inner.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken);
public Task<IReadOnlyList<ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult>> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken)
{
if (!owner._array) return inner.ReadAsync(request, cancellationToken);
var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast<object>().ToArray(), [owner.ReadElements.Length]);
var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), owner.Proof.Lease.Serving, 1);
return Task.FromResult<IReadOnlyList<ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult>>([new(request.Items[0].CorrelationId, DataItemStatus.Good, DataReadiness.Ready, TimeSpan.Zero, sample, null, AgeBounds: new(TimeSpan.Zero, TimeSpan.Zero))]);
}
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{
owner.SentWrite = request;
if (request.Items[0].Value.Kind == DataValueKind.Array) owner.CapturedArray = request.Items[0].Value.GetArray().ToArray();
return Task.FromResult<IReadOnlyList<WriteItemResult>>([new(request.Items[0].CorrelationId, new(DataWriteState.OutcomeUnknown, StatusCodes.Bad.Code, null))]);
}
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
if (!owner._streams) return inner.SubscribeAsync(cancellationToken);
if (Interlocked.Increment(ref owner.StreamOpens) == 2) owner.SecondStreamOpened.TrySetResult();
return Task.FromResult<IDataSubscription>(new TestStream(owner, owner.Proof.Lease.Serving));
}
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
private sealed class TestStream(AccessFixture owner, ServingIdentity serving) : IDataSubscription, IDataSubscriptionProvenance
{
private readonly Channel<DataSubscriptionFrame> _frames = Channel.CreateUnbounded<DataSubscriptionFrame>();
private long _sequence; private ulong _handle; private int _items;
private readonly Dictionary<DataItemHandle, string> _ids = new();
public ServingIdentity Serving => serving;
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
IReadOnlyList<DataSubscriptionItem> items = command switch { OpenSubscription open => open.Items, AddSubscriptionItems add => add.Items, _ => [] };
var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good,
new DataItemHandle(command.SubscriptionId, command.StreamEpoch, ++_handle, 1), item.Settings, null)).ToArray();
foreach (var ack in acks) if (ack.Handle is not null) _ids[ack.Handle] = ack.ClientItemId;
if (command is RemoveSubscriptionItems remove)
acks = remove.Items.Select(handle => new DataSubscriptionItemAck(_ids[handle], DataItemStatus.Good, handle, null, null)).ToArray();
_frames.Writer.TryWrite(new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++_sequence, command.CommandId, acks));
if (items.Count > 0)
{
_items += items.Count; owner.FirstStreamItem.TrySetResult(); if (_items >= 2) owner.TwoStreamItems.TrySetResult();
_frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));
if (owner._array && acks.Length > 0)
{
var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast<object>().ToArray(), [owner.ReadElements.Length]);
var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), serving, 1);
_frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true,
[new DataSubscriptionValue(acks[0].Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)]));
}
_frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));
}
if (command is RemoveSubscriptionItems) owner.ItemRemoved.TrySetResult();
return Task.CompletedTask;
}
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); owner.StreamClosed.TrySetResult(); return ValueTask.CompletedTask; }
}
private sealed class ConnectionLease(IDataConnection connection, AccessFixture owner) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public async ValueTask DisposeAsync() { await connection.DisposeAsync(); owner.ConnectionDisposed.TrySetResult(); }
}
internal Action? BeforeBind;
public bool TryBind(ProjectedValueRoute route) { BeforeBind?.Invoke(); return true; }
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates) { Published.TrySetResult(updates[0]); return true; }
public void Retire(ProjectedValueRoute route) { }
public void Dispose() => _local.Dispose();
}
}
@@ -0,0 +1,85 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataProjectedRouteTests
{
[Fact]
public void Routes_use_exact_origin_metadata_and_keep_original_authority_live()
{
var catalog = new Catalog();
var allowed = true;
string? connection = "link";
var source = new ProjectedAdapterRouteSource(catalog, _ => connection, "link", _ => allowed);
source.TryResolve(catalog.Reference, out var route).ShouldBeTrue();
route.ShouldNotBeNull();
route.View.ShouldBe(catalog.Proof.OriginMetadata.View);
route.View.Subject.ShouldBe("Original/Value");
route.View.MappingId.ShouldBeNull();
route.Lease.IsValid.ShouldBeTrue();
allowed = false;
route.Lease.IsValid.ShouldBeFalse();
source.TryResolve(catalog.Reference, out _).ShouldBeFalse();
allowed = true;
connection = "other-link";
route.Lease.IsValid.ShouldBeFalse();
source.TryResolve(catalog.Reference, out _).ShouldBeFalse();
connection = "link";
catalog.Proof = catalog.Proof with { Generation = 2 };
route.Lease.IsValid.ShouldBeFalse();
source.TryResolve(catalog.Reference, out var replacement).ShouldBeTrue();
replacement.ShouldNotBeNull().ProjectionGeneration.ShouldBe(2);
catalog.Authority.Active = false;
replacement.Lease.IsValid.ShouldBeFalse();
}
[Fact]
public void Ordinary_paths_and_another_realm_cannot_alias_a_projected_route()
{
var catalog = new Catalog();
var source = new ProjectedAdapterRouteSource(catalog, _ => "link", "link", _ => true);
source.TryResolve("Original/Value", out _).ShouldBeFalse();
source.TryResolve(ProjectedDataIds.DependencyReference(DataRealm.Uns, catalog.Proof.LocalIdentifier), out _).ShouldBeFalse();
}
private sealed class Authority : IDataMappedCatalogAuthority
{
public bool Active = true;
public bool IsActive => Active;
public long CatalogEpoch => 1;
public long AuthorityEpoch => 1;
}
private sealed class Catalog : IFederatedProjectionCatalog
{
internal readonly Authority Authority = new();
internal ProjectedNodeProof Proof;
internal string Reference => ProjectedDataIds.DependencyReference(DataRealm.Raw, Proof.LocalIdentifier);
public Catalog()
{
var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1);
var origin = new DataView(new("source", "urn:origin", "string", "Original/Value"), DataRealm.Raw, null, 0, "Original/Value");
var mapped = origin with { MappingId = "mapping", MappingRevision = 1, Subject = "Local/Mount/Renamed" };
var subject = new MappedNamespaceSubject(mapped,
new() { ClusterId = "local", Kind = NodeHierarchyKind.Raw, Segments = ["Local", "Mount", "Renamed"] },
["folder"], serving, DataOperations.Read | DataOperations.Subscribe);
var metadata = new DataMetadata(mapped, "Renamed", "Variable", DataValueKind.Int32, -1, [], false,
DataOperations.Read | DataOperations.Subscribe, 1, null, null, false, Serving: serving);
var lease = new MetadataAuthorityLease(serving, new(1, 1, TimeSpan.FromSeconds(15)),
Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, Clock);
Proof = new(ProjectedDataIds.Identifier("mapping", origin.Address), metadata, subject,
new([subject], 1, Authority), lease, 1, metadata with { View = origin });
}
public TimeProvider Clock => TimeProvider.System;
public event Action<string, long>? Invalidated { add { } remove { } }
public bool TryResolveProjected(DataRealm realm, string id, out ProjectedNodeProof? proof)
{ proof = realm == DataRealm.Raw && id == Proof.LocalIdentifier ? Proof : null; return proof is not null; }
public bool TryPinProjected(DataRealm realm, string id, out IDisposable? pin) { pin = null; return false; }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => throw new NotSupportedException();
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken token) => throw new NotSupportedException();
}
}
@@ -0,0 +1,188 @@
using Opc.Ua;
using Shouldly;
using Xunit;
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.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public sealed class GrpcDataProjectionApplierTests
{
[Fact(Timeout = 15000)]
public async Task Cursor_is_committed_only_by_successful_atomic_application()
{
var catalog = new Catalog();
var sink = new Sink();
using var applier = new ProjectedNamespaceApplier(catalog, sink, 2);
var request = Request();
sink.Accept = false;
(await applier.ApplyPageAsync(request, new NodeId("parent", 2), TestContext.Current.CancellationToken)).ShouldBeFalse();
catalog.LastPage.ShouldNotBeNull();
catalog.LastPage.Commits.ShouldBe(0);
catalog.LastPage.Disposed.ShouldBeTrue();
sink.Accept = true;
(await applier.ApplyPageAsync(request, new NodeId("parent", 2), TestContext.Current.CancellationToken)).ShouldBeTrue();
catalog.LastPage.ShouldNotBeNull();
catalog.LastPage.Commits.ShouldBe(1);
catalog.LastPage.Disposed.ShouldBeTrue();
}
[Fact(Timeout = 15000)]
public async Task Authority_expiring_before_application_never_commits_the_cursor()
{
var catalog = new Catalog();
var sink = new Sink { BeforeCommit = () => catalog.Lease.Valid = false };
using var applier = new ProjectedNamespaceApplier(catalog, sink, 2);
(await applier.ApplyPageAsync(Request(), new NodeId("parent", 2), TestContext.Current.CancellationToken)).ShouldBeFalse();
catalog.LastPage.ShouldNotBeNull();
catalog.LastPage.Commits.ShouldBe(0);
catalog.LastPage.Disposed.ShouldBeTrue();
}
[Fact]
public async Task Invalid_continuation_is_preserved_from_preparation_without_cursor_commit()
{
var catalog = new InvalidCatalog();
using var applier = new ProjectedNamespaceApplier(catalog, new Sink(), 2);
var status = await applier.ApplyPageResultAsync(Request(), new NodeId("parent", 2), TestContext.Current.CancellationToken);
status.ShouldBe(ProjectionPageStatus.InvalidContinuation);
}
[Fact(Timeout = 15000)]
[Trait("Phase", "P08Unit")]
public async Task Materialized_authority_checks_only_its_own_item_and_remains_valid_after_prepare_disposal()
{
var catalog = new GuardCatalog();
var sink = new GuardSink();
using var applier = new ProjectedNamespaceApplier(catalog, sink, 1);
(await applier.ApplyPageAsync(Request(), new NodeId("parent", 2), TestContext.Current.CancellationToken)).ShouldBeTrue();
catalog.Page.Disposed.ShouldBeTrue();
sink.Nodes.Count.ShouldBe(12);
foreach (var lease in catalog.Leases) lease.Checks = 0;
for (var i = 0; i < 50; i++) sink.Nodes[0].AuthorityIsCurrent().ShouldBeTrue();
catalog.Leases.Skip(1).Sum(x => x.Checks).ShouldBe(0, "checking one retained definition must not rescan its page");
var retained = sink.Nodes[0].AuthorityIsCurrent.Target.ShouldBeAssignableTo<IProjectedRetainedAuthority>();
retained!.RetainedBytes.ShouldBeGreaterThan(0);
catalog.Leases[0].Valid = false;
sink.Nodes[0].AuthorityIsCurrent().ShouldBeFalse();
sink.Nodes[1].AuthorityIsCurrent().ShouldBeTrue();
}
private sealed class CountingLease : IDataAuthorizationLease
{
public int Checks;
public bool Valid = true;
public bool IsValid { get { Checks++; return Valid; } }
public ServingIdentity Serving { get; } = new("node", "boot", "Primary", 1, 1, 1);
}
private sealed class GuardCatalog : IFederatedProjectionCatalog
{
public readonly CountingLease[] Leases = Enumerable.Range(0, 12).Select(_ => new CountingLease()).ToArray();
public readonly GuardPage Page;
public GuardCatalog()
{
var authority = new Authority();
ProjectedNodeProof Proof(int i)
{
var view = new DataView(new("origin", "urn:raw", "string", "child" + i), DataRealm.Raw, "mapping", 1, "Plant/Mount/child" + i);
var subject = new MappedNamespaceSubject(view,
new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Mount", "child" + i] },
["folder"], Leases[i].Serving, DataOperations.Browse);
var resolver = new MappedSubjectResolver([subject], 1, authority);
var metadata = new DataMetadata(view, "child" + i, "Tag", DataValueKind.Int32, -1, [], false,
DataOperations.Browse, 1, null, null, false, Serving: Leases[i].Serving);
var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/child" + i } };
return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, Leases[i], 1, origin);
}
var items = Enumerable.Range(0, 12).Select(Proof).ToArray();
Page = new GuardPage(new(ProjectionPageStatus.Ready, items, true, null, 1, Leases[0], authority));
}
public TimeProvider Clock => TimeProvider.System;
public event Action<string, long>? Invalidated { add { } remove { } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => Page.Snapshot;
public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => new PageGuard();
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => Task.FromResult<IProjectedPreparedPage>(Page);
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; }
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; }
private sealed class PageGuard : IProjectedPageGuard { public bool IsCurrent => true; public long RetainedBytes => 64; }
}
private sealed class GuardPage(ProjectedParentSnapshot snapshot) : IProjectedPreparedPage
{
public bool Disposed;
public ProjectedParentSnapshot Snapshot => snapshot;
public bool TryCommit() => true;
public void Dispose() => Disposed = true;
}
private sealed class GuardSink : IProjectedNamespacePageSink
{
public IReadOnlyList<ProjectedVariableDefinition> Nodes = [];
public bool TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit)
{ Nodes = nodes; return commit(); }
public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => false;
}
private sealed class InvalidCatalog : IFederatedProjectionCatalog
{
public TimeProvider Clock => TimeProvider.System;
public event Action<string, long>? Invalidated { add { } remove { } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => new(ProjectionPageStatus.Pending, [], false, null, 0);
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => Task.FromResult<IProjectedPreparedPage>(new InvalidPage());
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; }
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; }
private sealed class InvalidPage : IProjectedPreparedPage
{
public ProjectedParentSnapshot Snapshot => new(ProjectionPageStatus.InvalidContinuation, [], false, null, 0);
public bool TryCommit() => throw new InvalidOperationException("Invalid continuation must not commit.");
public void Dispose() { }
}
}
private static ProjectedBrowseRequest Request() => new("mapping",
new(new("origin", "urn:raw", "string", "root"), DataRealm.Raw, "mapping", 1, "Plant/Mount"),
null, "opaque-cursor", new("reader", "key", "version", null), new(TimeSpan.FromSeconds(5), 16, 4096), TimeProvider.System.GetTimestamp());
private sealed class Lease : IDataAuthorizationLease
{
public bool Valid = true;
public bool IsValid => Valid;
public ServingIdentity Serving { get; } = new("node", "boot", "Primary", 1, 1, 1);
}
private sealed class Authority : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => 1;
public bool IsActive => true;
}
private sealed class Page(Lease lease) : IProjectedPreparedPage
{
public int Commits;
public bool Disposed;
public ProjectedParentSnapshot Snapshot { get; } = new(ProjectionPageStatus.Ready, [], true, null, 1, lease, new Authority());
public bool TryCommit() { Commits++; return true; }
public void Dispose() => Disposed = true;
}
private sealed class Sink : IProjectedNamespacePageSink
{
public bool Accept = true;
public Action? BeforeCommit;
public bool TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit)
{ if (!Accept) return false; BeforeCommit?.Invoke(); return commit(); }
public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => false;
}
private sealed class Catalog : IFederatedProjectionCatalog
{
public Lease Lease { get; } = new();
public Page? LastPage;
public TimeProvider Clock => TimeProvider.System;
public event Action<string, long>? Invalidated { add { } remove { } }
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => new(ProjectionPageStatus.Pending, [], false, null, 0);
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{ LastPage = new Page(Lease); return Task.FromResult<IProjectedPreparedPage>(LastPage); }
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; }
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; }
}
}
@@ -1,3 +1,8 @@
using System.Buffers.Binary;
using System.Net;
using Google.Protobuf;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
@@ -153,6 +158,98 @@ public sealed class GrpcDataWriteAdmissionTests
route.Dispatched.Order().ShouldBe(["failed", "ok"]);
}
[Fact]
public async Task Executor_rejects_a_stale_generation_before_route_or_registry_claim()
{
using var fixture = new LocalDataFixture();
var route = new RecordingRoute(fixture.Raw);
var executor = CreateExecutor(fixture, route);
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5), fixture.Serving.ServingGeneration + 1);
var stale = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
stale.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
route.Dispatched.ShouldBeEmpty();
var valid = await executor.WriteAsync(new([item with { ExpectedServingGeneration = null }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
valid.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
}
[Fact]
public async Task Duplicate_operation_cannot_change_generation_presence()
{
using var fixture = new LocalDataFixture(servingGeneration: 1);
var route = new RecordingRoute(fixture.Raw);
var executor = CreateExecutor(fixture, route);
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5), 1);
var first = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
first.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
var changed = await executor.WriteAsync(new([item with { CorrelationId = "two", ExpectedServingGeneration = null }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
changed.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
route.Dispatched.ShouldBe(["same-operation"]);
}
[Fact]
public async Task Same_operation_after_role_aba_returns_unknown_instead_of_retryable_rejection()
{
using var fixture = new LocalDataFixture(servingGeneration: 1);
var serving = fixture.Serving;
var catalog = fixture.Catalog;
var route = new RecordingRoute(fixture.Raw);
var executor = CreateExecutor(fixture, route, catalogSource: () => catalog, servingSource: () => serving);
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1, serving.Incarnation, TimeSpan.FromSeconds(5), 1);
var first = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
first.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
serving = serving with { ServingGeneration = 3 };
catalog = catalog.WithServingRole(serving);
var afterAba = await executor.WriteAsync(new([item with { ExpectedServingGeneration = 3 }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
afterAba.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
route.Dispatched.ShouldBe(["same-operation"]);
}
[Fact]
public async Task Legacy_client_does_not_fail_over_a_real_executor_conflict_after_role_aba()
{
using var fixture = new LocalDataFixture(servingGeneration: 1);
var serving = fixture.Serving;
var catalog = fixture.Catalog;
var route = new RecordingRoute(fixture.Raw);
var executor = CreateExecutor(fixture, route, catalogSource: () => catalog, servingSource: () => serving);
var first = new ExecutorWireHandler(() => serving, fixture.Raw, executor);
var second = new ExecutorWireHandler(() => serving with { NodeId = "node-b" }, fixture.Raw, null);
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "cluster", null),
[new Uri("https://a.test"), new Uri("https://b.test")], new ExecutorWireSecurity(first, second), manager.Acquire("link"),
1_000_000, 2, eligibleNodeIds: new HashSet<string> { "node-a", "node-b" });
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1, serving.Incarnation, TimeSpan.FromSeconds(5));
var original = await connection.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
original.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
serving = serving with { ServingGeneration = 3 };
catalog = catalog.WithServingRole(serving);
var repeated = await connection.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
repeated.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
route.Dispatched.ShouldBe(["same-operation"]);
first.Writes.ShouldBe(2); second.Writes.ShouldBe(0);
}
[Fact]
public async Task Strict_write_rejects_a_different_view_shape_before_dispatch()
{
using var fixture = new LocalDataFixture(servingGeneration: 1);
var route = new RecordingRoute(fixture.Raw);
var executor = CreateExecutor(fixture, route);
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
var item = new WriteItem("one", "operation", fixture.Raw with { Subject = "forged" }, value, 1,
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5), 1);
var result = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
route.Dispatched.ShouldBeEmpty();
}
[Fact]
public async Task Executor_joins_concurrent_duplicate_with_a_different_remaining_budget()
{
@@ -229,7 +326,7 @@ public sealed class GrpcDataWriteAdmissionTests
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
one.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
two.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
two.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
route.Dispatched.ShouldBe(["same-id"]);
}
@@ -300,7 +397,8 @@ public sealed class GrpcDataWriteAdmissionTests
}
private static DataWriteExecutor CreateExecutor(LocalDataFixture fixture, IDataWriteRoute route,
DataAuthenticatedContext? context = null, LocalExportCatalog? catalog = null)
DataAuthenticatedContext? context = null, LocalExportCatalog? catalog = null,
Func<LocalExportCatalog>? catalogSource = null, Func<ServingIdentity>? servingSource = null)
{
var authority = new DataPlaneAuthorityState();
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
@@ -312,11 +410,64 @@ public sealed class GrpcDataWriteAdmissionTests
var registry = new WriteOperationRegistry(fixture.Serving.Incarnation, 16, 16_384, TimeSpan.FromMinutes(1), fixture.Clock);
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilitiesProvider("cluster", () => fixture.Serving, () => true, limits);
return new DataWriteExecutor(context ?? fixture.Context, () => catalog ?? fixture.Catalog, policy, capabilities, route,
var capabilities = new DataCapabilitiesProvider("cluster", servingSource ?? (() => fixture.Serving), () => true, limits);
return new DataWriteExecutor(context ?? fixture.Context, catalogSource ?? (() => catalog ?? fixture.Catalog), policy, capabilities, route,
registry, new WriteValueBudget(16_384), fixture.Clock, new DriverWriteBounds(TimeSpan.FromMilliseconds(100)));
}
private sealed class ExecutorWireSecurity(ExecutorWireHandler first, ExecutorWireHandler second) : IDataConnectionSecurityProvider
{
public event Action<string>? Changed { add { } remove { } }
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca", "key", () => endpoint.Host == "a.test" ? first : second));
}
private sealed class ExecutorWireHandler(Func<ServingIdentity> current, DataView view, DataWriteExecutor? executor) : HttpMessageHandler
{
public int Writes { get; private set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var serving = current();
IMessage message;
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
{
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, serving, DataReadiness.Ready,
DataOperations.Read | DataOperations.Metadata | DataOperations.Write, new HashSet<DataValueKind> { DataValueKind.Int32 },
limits, false, 0, "cluster", false, true, true));
}
else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal))
{
var metadata = new DataMetadata(view, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Write, 1, null, null, false);
var response = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]);
response.Serving = DataProtoMapper.EncodeServing(serving); message = response;
}
else
{
Writes++;
var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
var wire = W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray());
var batch = DataProtoMapper.DecodeWriteRequest(wire, 100, 1_000_000);
try
{
var outcomes = executor is null ? batch.Items.Select(x => new WriteItemResult(x.CorrelationId,
new(DataWriteState.DriverConfirmedSuccess, 0, null))).ToArray() :
await executor.WriteAsync(batch, cancellationToken);
var response = DataProtoMapper.EncodeWriteResponse(outcomes);
response.Serving = DataProtoMapper.EncodeServing(serving); message = response;
}
finally { foreach (var item in batch.Items) item.Value.Dispose(); }
}
var payload = message.ToByteArray();
var framed = new byte[payload.Length + 5];
BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length);
payload.CopyTo(framed, 5);
var http = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) };
http.Content.Headers.ContentType = new("application/grpc");
http.TrailingHeaders.Add("grpc-status", "0");
return http;
}
}
private sealed class RecordingRoute(DataView view, DataView? alternate = null) : IDataWriteRoute
{
private readonly System.Collections.Concurrent.ConcurrentQueue<string> _dispatched = new();
@@ -70,6 +70,35 @@ public sealed class ContinuousHistorizationRecorderAppendPipelineTests : TestKit
outbox.AppendBatchCalls.ShouldBeLessThan(6, "the bursts waiting behind the slow append share its successor's commit");
}
[Fact(Timeout = 20000)]
public async Task Projected_input_revoked_while_waiting_for_append_capacity_is_not_admitted()
{
var log = new EventLog();
var outbox = new LoggingOutbox(log) { AppendGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) };
var rec = Start(outbox, new LoggingPassWriter(log), maxAppendsInFlight: 1);
rec.Tell(Burst(1));
await outbox.AppendEntered.Task.WaitAsync(Wait, TestContext.Current.CancellationToken);
rec.Tell(Burst(1, 1));
await AwaitAssertAsync(async () => (await StatusAsync(rec)).PendingAppends.ShouldBe(2), Wait, cancellationToken: TestContext.Current.CancellationToken);
var proof = new ProjectedGate();
rec.Tell(new VirtualTagActor.DependencyValueBatch([new("A", 2d, T0.AddSeconds(2), PublicationProof: proof)]));
var status = StatusAsync(rec, Wait);
await Task.Delay(300, TestContext.Current.CancellationToken);
status.IsCompleted.ShouldBeFalse();
proof.Invalidate();
outbox.AppendGate.SetResult();
await status;
await AwaitAssertAsync(() => outbox.Appended.Count.ShouldBe(2), Wait, cancellationToken: TestContext.Current.CancellationToken);
outbox.Appended.Select(x => x.Value.Number).ShouldBe([0d, 1d]);
}
private sealed class ProjectedGate : ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof
{
private int _valid = 1;
public bool IsValid => Volatile.Read(ref _valid) != 0;
public TimeProvider Clock => TimeProvider.System;
public void Invalidate() => Interlocked.Exchange(ref _valid, 0);
}
[Fact]
public async Task A_full_append_queue_backpressures_the_mailbox_and_loses_nothing()
{
@@ -37,6 +37,80 @@ public sealed class DependencyMuxTagUpstreamSourceTests
seen.ShouldBe(new[] { "old/renamed" });
}
[Fact]
public void Projected_evidence_belongs_to_exact_snapshot_and_later_sample_cannot_revive_it()
{
var src = new DependencyMuxTagUpstreamSource();
var firstProof = new ProjectedProof(); var secondProof = new ProjectedProof();
var sample = Good(1, DateTime.UtcNow);
src.Push("path", sample, firstProof);
var first = src.ReadTag("path");
var evidence = src.CaptureEvidence(first).ShouldNotBeNull();
evidence.IsValid.ShouldBeTrue();
src.Push("path", sample, secondProof);
var second = src.ReadTag("path");
second.ShouldNotBeSameAs(first);
firstProof.Invalidate();
evidence.IsValid.ShouldBeFalse();
src.CaptureEvidence(second).ShouldNotBeNull().IsValid.ShouldBeTrue();
src.CaptureEvidence(sample).ShouldBeNull();
}
[Fact]
public void Retained_projected_evaluation_payload_stays_charged_until_physical_release()
{
var src = new DependencyMuxTagUpstreamSource(maximumProjectedBytes: 1600);
var proof = new ProjectedProof();
src.Push("path", Good(new byte[600], DateTime.UtcNow), proof);
var firstSnapshot = src.ReadTag("path");
var first = src.CaptureEvidence(firstSnapshot).ShouldBeAssignableTo<ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.IAlarmInputPhysicalEvidence>();
first!.TryRetainPhysical(firstSnapshot, out var held).ShouldBeTrue();
src.Push("path", Good(new byte[600], DateTime.UtcNow), proof);
var secondSnapshot = src.ReadTag("path");
var second = src.CaptureEvidence(secondSnapshot).ShouldBeAssignableTo<ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.IAlarmInputPhysicalEvidence>();
second!.TryRetainPhysical(secondSnapshot, out _).ShouldBeFalse();
held.ShouldNotBeNull().Dispose();
second!.TryRetainPhysical(secondSnapshot, out var fresh).ShouldBeTrue();
fresh.ShouldNotBeNull().Dispose();
}
[Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public void Replaced_upstreams_share_the_process_physical_budget_until_each_run_releases()
{
var leases = new List<IDisposable>();
var payload = new byte[3 * 1024 * 1024];
static bool Retain(byte[] value, out IDisposable? lease)
{
var source = new DependencyMuxTagUpstreamSource();
source.Push("path", Good(value, DateTime.UtcNow), new ProjectedProof());
var snapshot = source.ReadTag("path");
var evidence = source.CaptureEvidence(snapshot).ShouldBeAssignableTo<ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.IAlarmInputPhysicalEvidence>();
return evidence!.TryRetainPhysical(snapshot, out lease);
}
try
{
for (var i = 0; i < 5; i++)
{
Retain(payload, out var held).ShouldBeTrue();
leases.Add(held.ShouldNotBeNull());
}
Retain(payload, out var rejected).ShouldBeFalse();
rejected.ShouldBeNull();
leases[0].Dispose();
Retain(payload, out var replacement).ShouldBeTrue();
leases.Add(replacement.ShouldNotBeNull());
Retain(payload, out rejected).ShouldBeFalse();
rejected.ShouldBeNull();
}
finally { foreach (var lease in leases) lease.Dispose(); }
}
private sealed class ProjectedProof : ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof
{
private int _valid = 1;
public bool IsValid => Volatile.Read(ref _valid) != 0;
public TimeProvider Clock => TimeProvider.System;
public void Invalidate() => Interlocked.Exchange(ref _valid, 0);
}
[Fact]
public void Push_then_ReadTag_returns_the_pushed_snapshot()
{
@@ -46,6 +46,27 @@ public sealed class ScriptedAlarmHostActorTests : RuntimeActorTestBase
/// </remarks>
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
[Fact]
public void A_delayed_engine_emission_with_revoked_original_evidence_is_not_published()
{
var publish = CreateTestProbe(); var mux = CreateTestProbe();
var (host, _) = Spawn(publish, mux);
var evidence = new TestEvidence();
var emission = new ScriptedAlarmEvent("alarm", "Plant", "Alarm", AlarmKind.AlarmCondition,
ZB.MOM.WW.OtOpcUa.Core.Abstractions.AlarmSeverity.High, "message",
AlarmConditionState.Fresh("alarm", DateTime.UtcNow), EmissionKind.QualityChanged, DateTime.UtcNow)
{ InputEvidence = evidence };
var type = typeof(ScriptedAlarmHostActor).GetNestedType("EngineEmission", System.Reflection.BindingFlags.NonPublic).ShouldNotBeNull();
var message = Activator.CreateInstance(type, emission).ShouldNotBeNull();
evidence.Valid = false;
host.Tell(message);
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(250), TestContext.Current.CancellationToken);
evidence.Valid = true;
host.Tell(message);
publish.ExpectMsg<OpcUaPublishActor.AlarmQualityUpdate>(Timeout, cancellationToken: TestContext.Current.CancellationToken);
}
private sealed class TestEvidence : IAlarmInputEvidence { public bool Valid = true; public bool IsValid => Valid; }
/// <summary>Plan whose predicate compares the single tag "M.T" against 90 — enabled by default.</summary>
private static EquipmentScriptedAlarmPlan Plan(
string id = "alm-1",
@@ -3,6 +3,7 @@ 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.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
@@ -24,6 +25,89 @@ public sealed class DependencyConsumerMuxAdapterTests : RuntimeActorTestBase
private const string TagA = "Plant/Modbus/dev1/a";
private const string TagB = "Plant/Modbus/dev1/b";
[Theory(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
[InlineData(false)]
[InlineData(true)]
public void Revoked_projected_proof_is_bad_at_the_actual_consumer_callback(bool batch)
{
var (consumer, adapter) = Spawn();
var message = new VirtualTagActor.DependencyValueChanged(TagA, 42, DateTime.UtcNow, OpcUaStatus.Good, new RevokedProof());
adapter.Tell(batch ? (object)new VirtualTagActor.DependencyValueBatch([message]) : message);
AwaitCondition(() => consumer.Received.Count == 1, PresenceBudget, TestContext.Current.CancellationToken);
consumer.Received[0].Value.ShouldBeNull();
consumer.Received[0].StatusCode.ShouldBe(OpcUaStatus.BadNoCommunication);
}
[Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public void Valid_projected_sample_keeps_its_exact_proof_at_the_consumer_boundary()
{
var consumer = new ProjectedConsumer();
var mux = CreateTestProbe();
var adapter = Sys.ActorOf(DependencyConsumerMuxAdapter.Props(consumer, mux.Ref));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var proof = new MutableProof();
adapter.Tell(new VirtualTagActor.DependencyValueChanged(TagA, 42, DateTime.UtcNow, OpcUaStatus.Good, proof));
AwaitCondition(() => Volatile.Read(ref consumer.Proof) is not null, PresenceBudget, TestContext.Current.CancellationToken);
consumer.Proof.ShouldBeSameAs(proof);
proof.Valid = false;
consumer.Proof!.IsValid.ShouldBeFalse();
}
[Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public void Revoked_projected_sample_preserves_classification_with_a_bad_empty_value()
{
var consumer = new ProjectedConsumer();
var mux = CreateTestProbe();
var adapter = Sys.ActorOf(DependencyConsumerMuxAdapter.Props(consumer, mux.Ref));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var proof = new RevokedProof();
adapter.Tell(new VirtualTagActor.DependencyValueChanged(TagA, 42, DateTime.UtcNow, OpcUaStatus.Good, proof));
AwaitCondition(() => Volatile.Read(ref consumer.Proof) is not null, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
consumer.Proof.ShouldBeSameAs(proof);
consumer.Value.ShouldBeNull();
consumer.Status.ShouldBe(OpcUaStatus.BadNoCommunication);
}
[Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public void Valid_projected_sample_is_not_delivered_as_good_to_a_legacy_consumer()
{
var (consumer, adapter) = Spawn();
adapter.Tell(new VirtualTagActor.DependencyValueChanged(TagA, 42, DateTime.UtcNow, OpcUaStatus.Good, new MutableProof()));
AwaitCondition(() => consumer.Received.Count == 1, PresenceBudget, TestContext.Current.CancellationToken);
consumer.Received[0].Value.ShouldBeNull();
consumer.Received[0].StatusCode.ShouldBe(OpcUaStatus.BadNoCommunication);
}
private sealed class MutableProof : IProjectedSamplePublicationProof
{
public bool Valid = true;
public bool IsValid => Valid;
public TimeProvider Clock => TimeProvider.System;
public void Invalidate() => Valid = false;
}
private sealed class ProjectedConsumer : IDependencyConsumer, IProjectedDependencyConsumer
{
public IReadOnlyCollection<string> DependencyRefs => [TagA];
public IProjectedSamplePublicationProof? Proof;
public object? Value;
public uint Status;
public void OnDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc) { }
public void OnProjectedDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc, IProjectedSamplePublicationProof proof)
{
Value = value;
Status = statusCode;
Volatile.Write(ref Proof, proof);
}
}
private sealed class RevokedProof : IProjectedSamplePublicationProof
{
public bool IsValid => false;
public TimeProvider Clock => TimeProvider.System;
public void Invalidate() { }
}
/// <summary>Single delivery: the status code reaches the consumer verbatim, sub-code and all.</summary>
[Fact]
public void A_single_dependency_value_carries_its_status_code_to_the_consumer()
@@ -148,6 +148,87 @@ one-thread-dispatcher {
recovered.Value.ShouldBe(5);
}
[Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public void Projected_input_is_not_passed_to_an_evaluator_without_physical_ownership_support()
{
var parent = CreateTestProbe();
var evaluator = new ManualEvaluator();
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-projected", "expr", evaluator: evaluator,
dependencyRefs: ["a"]), TestContext.Current.CancellationToken);
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, DateTime.UtcNow, OpcUaStatus.Good, new LiveProof()));
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken)
.StatusCode.ShouldNotBe(OpcUaStatus.Good);
evaluator.Calls.ShouldBeEmpty();
}
[Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public void Revocation_during_projected_evaluation_prevents_good_acceptance()
{
var parent = CreateTestProbe();
var evaluator = new ProjectedManualEvaluator();
var proof = new LiveProof();
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-revoked", "expr", evaluator: evaluator,
dependencyRefs: ["a"]), TestContext.Current.CancellationToken);
try
{
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, DateTime.UtcNow, OpcUaStatus.Good, proof));
AwaitCondition(() => evaluator.Started, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
proof.Invalidate();
evaluator.Complete();
var accepted = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
accepted.StatusCode.ShouldBe(OpcUaStatus.BadNoCommunication);
}
finally { evaluator.Complete(); }
}
[Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
public void Throwing_projected_proof_fails_closed_without_restarting_the_actor()
{
var parent = CreateTestProbe();
var evaluator = new ManualEvaluator();
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-proof-error", "expr", evaluator: evaluator,
dependencyRefs: ["a"]), TestContext.Current.CancellationToken);
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, DateTime.UtcNow, OpcUaStatus.Good, new ThrowingProof()));
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken)
.StatusCode.ShouldBe(OpcUaStatus.BadNoCommunication);
evaluator.Calls.ShouldBeEmpty();
}
private sealed class ThrowingProof : ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof
{
public bool IsValid => throw new InvalidOperationException("source retired");
public TimeProvider Clock => TimeProvider.System;
public void Invalidate() { }
}
private sealed class ProjectedManualEvaluator : IProjectedVirtualTagEvaluator
{
private readonly TaskCompletionSource<VirtualTagEvalResult> _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
private IDisposable? _lease;
public bool Started => Volatile.Read(ref _lease) is not null;
public VirtualTagEvalResult Evaluate(string id, string expression, IReadOnlyDictionary<string, object?> dependencies)
=> throw new InvalidOperationException("legacy evaluation is not permitted");
public Task<VirtualTagEvalResult> EvaluateProjectedAsync(string id, string expression,
IReadOnlyDictionary<string, DataValueSnapshot> dependencies, IDisposable physicalLease)
{
Volatile.Write(ref _lease, physicalLease);
return _completion.Task;
}
public void Complete()
{
Interlocked.Exchange(ref _lease, null)?.Dispose();
_completion.TrySetResult(VirtualTagEvalResult.Ok(1));
}
}
private sealed class LiveProof : ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof
{
private int _valid = 1;
public bool IsValid => Volatile.Read(ref _valid) == 1;
public TimeProvider Clock => TimeProvider.System;
public void Invalidate() => Interlocked.Exchange(ref _valid, 0);
}
/// <summary>Models the Roslyn evaluator: the blocking overload parks its caller until the script returns (what
/// the actor used to call), the async one returns an incomplete task (what it calls now).</summary>
private sealed class GatedEvaluator(object value) : IVirtualTagEvaluator
@@ -46,6 +46,30 @@ public sealed class WorkerSoftClockTests
return worker;
}
[Fact]
public async Task Physical_lease_stays_charged_through_transport_timeout_until_worker_actually_answers()
{
var timeout = TimeSpan.FromMilliseconds(150);
await using var runner = Runner(TimeSpan.FromMilliseconds(300));
var worker = await WarmAsync(runner, "physical");
var lease = new PhysicalLease();
ScriptRunOutcome outcome;
using (ProcessFreezer.Freeze(worker.Pid))
{
outcome = await runner.RunAsync(Scripts.Vt("physical", Trivial, timeout) with { PhysicalLease = lease }, Ct)
.WaitAsync(TimeSpan.FromSeconds(10), Ct);
outcome.Status.ShouldBe(ScriptRunStatus.Unavailable);
lease.Disposals.ShouldBe(0);
}
await outcome.Recovery.ShouldNotBeNull().WaitAsync(TimeSpan.FromSeconds(10), Ct);
lease.Disposals.ShouldBe(1);
}
private sealed class PhysicalLease : IDisposable
{
private int _disposals; public int Disposals => Volatile.Read(ref _disposals);
public void Dispose() => Interlocked.Increment(ref _disposals);
}
/// <summary>
/// The issue's headline: a worker that cannot be scheduled for longer than T, but shorter than the transport
/// deadline, answers a trivial script with its value. Before #827 the host's clock, started at submit, answered