using System.Threading.Channels;
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
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;
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;
using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
///
/// A3b (plan §5.6): the consumer condition runtime's method port — the per-LOCAL-caller gate with a real
/// (AlarmAcknowledge ⇒ Acknowledge/AddComment, AlarmConfirm ⇒ Confirm, the mapping's own
/// bit, the mapping's ConditionMethodTimeoutMilliseconds), and dispatch: addressed with the serving incarnation of the
/// condition stream the records arrive on; no open stream (connection down) ⇒ BadNoCommunication, nothing sent.
///
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class GrpcDataProjectedConditionMethodTests
{
private const string Connection = "conn-a";
private const uint BadNoCommunication = 0x80310000u;
private static readonly ServingIdentity Serving = new("origin-1", "serving-inc-7", "Primary", 1, 1);
[Fact]
public async Task The_method_gate_is_the_local_callers_alarm_grant_on_the_placement_folder_and_the_mappings_own_bit()
{
await using var f = new Fixture();
var placement = f.Placement();
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe | NodePermissions.AlarmAcknowledge);
var route = f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Acknowledge);
route.ShouldNotBeNull();
route.Placement.ShouldBe(placement);
route.Timeout.ShouldBe(TimeSpan.FromMilliseconds(4321), "the mapping's ConditionMethodTimeoutMilliseconds");
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.AddComment).ShouldNotBeNull();
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Confirm).ShouldBeNull("AlarmAcknowledge is not AlarmConfirm");
f.Access.AuthorizeMethod(f.Identity("someone-else"), [placement], DataConditionMethods.Acknowledge).ShouldBeNull("per local caller");
f.Access.AuthorizeMethod(null, [placement], DataConditionMethods.Acknowledge).ShouldBeNull();
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe);
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Acknowledge)
.ShouldBeNull("seeing a condition (Subscribe) does not authorize acknowledging it");
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm);
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Confirm).ShouldNotBeNull();
f.Mapping.AllowedOperations &= ~DataOperations.AlarmConfirm;
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Confirm)
.ShouldBeNull("the mapping must itself grant the method's bit");
f.Access.AuthorizeMethod(f.Identity("reader"), [placement with { MappingId = "unknown" }], DataConditionMethods.Acknowledge).ShouldBeNull();
}
[Fact]
public async Task With_no_open_condition_stream_a_call_is_BadNoCommunication_and_nothing_is_sent()
{
await using var f = new Fixture();
var result = await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
result.StatusCode.ShouldBe(BadNoCommunication);
f.Connections.Acquired.ShouldBe(0, "the connection is never even leased");
f.Connections.Sent.ShouldBeEmpty();
}
[Fact]
public async Task A_call_goes_through_the_lease_with_the_streams_serving_incarnation_and_a_stream_end_stops_dispatch()
{
await using var f = new Fixture();
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode != BadNoCommunication);
var sent = f.Connections.Sent.Last();
sent.ExpectedServingIncarnation.ShouldBe(Serving.Incarnation, "addressed to the incarnation the records came from");
sent.Placement.ShouldBe(f.Placement().Placement);
sent.Method.ShouldBe(DataConditionMethods.Acknowledge);
sent.ExpectedActivation.ShouldBe(new DataActivationMarker("inc", 3));
sent.OperationId.ShouldBe("op-1");
sent.RemainingBudget.ShouldBe(TimeSpan.FromMilliseconds(900));
sent.OnBehalfOf.ShouldBe("operator");
f.Connections.Result = new(DataWriteState.OutcomeUnknown, 0x80050000u, "transport failed");
(await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown, "passed through");
// The connection goes down: the stream ends and cannot be re-opened.
var before = f.Connections.Sent.Count;
f.Connections.Down = true;
stream.End();
await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode == BadNoCommunication);
var final = f.Connections.Sent.Count;
(final - before).ShouldBeLessThanOrEqualTo(1, "at most the call racing the stream end");
(await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode.ShouldBe(BadNoCommunication);
f.Connections.Sent.Count.ShouldBe(final, "connection down: nothing sent");
}
[Fact]
public async Task A_lease_refusing_the_operation_is_BadUserAccessDenied_unsent()
{
await using var f = new Fixture();
using var demand = f.Access.AcquireEventDemand(null);
await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode != BadNoCommunication);
var sent = f.Connections.Sent.Count;
f.Connections.Refuse = true;
var result = await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
result.StatusCode.ShouldBe(0x801F0000u);
f.Connections.Sent.Count.ShouldBe(sent);
}
[Fact]
public async Task The_condition_item_carries_the_origins_canonical_root_view_learned_from_metadata()
{
// Live a3b-cond-2: a UNS root item built from the address alone (subject = the opaque EquipmentId) was refused Denied.
await using var f = new Fixture(uns: true);
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
var open = await stream.Opened.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
f.Connections.MetadataViews.Single().Subject.ShouldBe("EQ-0001", "metadata is asked as the browse resolver asks it (RemoteRootEntityId)");
open.Items.Single().View.Subject.ShouldBe("area/line/plc", "the item uses the origin's own view of the root");
}
// ---------------------------------------------------------------------------------------------------------------------
private sealed class Fixture : IAsyncDisposable
{
private readonly DataPlaneAuthorityState _state = new();
private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true,
ExpiresUtc = DateTime.UtcNow.AddHours(1) };
private readonly ProjectedMappingPlacement _placement;
public FakeConnections Connections { get; } = new();
public ProjectedConditionAccess Access { get; }
public RemoteNamespaceMapping Mapping => _placement.Mapping;
public Fixture(bool uns = false)
{
Grant(NodePermissions.Browse | NodePermissions.Subscribe);
var mapping = new RemoteNamespaceMapping
{
RemoteNamespaceMappingId = "map-a", DataConnectionId = Connection, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe
| DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm,
MaxConditions = 10, ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000,
ConditionMethodTimeoutMilliseconds = 4321, BranchName = "map-a", RemoteNamespaceUri = "https://zb.com/otopcua/raw",
RemoteIdentifierKind = "string", RemoteIdentifier = "Plant",
};
if (uns)
{
mapping.Realm = mapping.RemoteRealm = DataRealm.Uns;
mapping.RemoteNamespaceUri = "https://zb.com/otopcua/uns";
mapping.RemoteIdentifier = "EQ-0001";
mapping.RemoteRootEntityId = "EQ-0001";
}
var segments = new[] { "Plant", "map-a" };
var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", mapping.RemoteIdentifier), mapping.Realm, "map-a", 1, "Plant/map-a");
var scope = new NodeScope { ClusterId = "c1", Kind = uns ? NodeHierarchyKind.Uns : NodeHierarchyKind.Raw, Segments = segments };
_placement = new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority());
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
Access = new ProjectedConditionAccess(new GrpcDataProjectedConditionAccessTests.FakeMappings([_placement]), Connections, policy,
() => new GrpcDataProjectedConditionAccessTests.FakeSink(), TimeProvider.System,
new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)), NullLogger.Instance);
}
public void Grant(NodePermissions permissions) =>
_state.Apply("c1", "rev-" + (int)permissions, [_key],
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder,
ScopeId = "folder", PermissionFlags = permissions }],
new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
public RoleCarryingUserIdentity Identity(string principal) => new(new UserNameIdentityToken { UserName = "apikey" }, [], principal,
_key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5));
public ImportedConditionPlacement Placement() =>
new("map-a", DataRealm.Raw, new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"),
DataRealm.Raw, null, 0, "Plant/dev1/HR200"), "Plant/map-a/dev1", "dev1/HR200");
public ImportedConditionMethodCall Call() => new(Connection, "key", Placement(), DataConditionMethods.Acknowledge,
new DataActivationMarker("inc", 3), "c", "op-1", TimeSpan.FromMilliseconds(900), "operator");
public async Task WaitAsync(Func> condition)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!await condition())
{
if (DateTime.UtcNow > deadline) (await condition()).ShouldBeTrue("condition not met within 10 s");
await Task.Delay(20, TestContext.Current.CancellationToken);
}
}
public ValueTask DisposeAsync() { Access.Dispose(); return ValueTask.CompletedTask; }
}
private sealed class ActiveAuthority : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => 1;
public bool IsActive => true;
}
private sealed class FakeConnections : IGrpcDataAdapterConnectionSource
{
private int _acquired;
public Channel Streams { get; } = Channel.CreateUnbounded();
public List Sent { get; } = [];
public List MetadataViews { get; } = [];
public DataConditionMethodResult Result { get; set; } = new(DataWriteState.AcceptedUnconfirmed, 0, null);
public bool Refuse { get; set; }
public volatile bool Down;
public int Acquired => Volatile.Read(ref _acquired);
public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _acquired);
if (Down) return ValueTask.FromResult(null);
return ValueTask.FromResult(new Lease(new FakeConnection(this)));
}
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
private sealed class FakeConnection(FakeConnections owner) : IDataConnection, IDataConditionMethodService
{
public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null);
public TimeProvider Clock => TimeProvider.System;
public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{
lock (owner.MetadataViews) owner.MetadataViews.AddRange(request.Views);
// The origin answers with ITS canonical view of the root (subject = its browse path, not the opaque id).
return Task.FromResult>>(request.Views.Select(v => new DataItemResult("0",
DataItemStatus.Good, new DataMetadata(v with { Subject = "area/line/plc" }, "plc", "Folder", DataValueKind.Null, -1, [], false,
DataOperations.Browse, 1, null, null, false), null)).ToArray());
}
public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task SubscribeAsync(CancellationToken cancellationToken)
{
var stream = new FakeStream();
owner.Streams.Writer.TryWrite(stream);
return Task.FromResult(stream);
}
public Task CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken)
{
if (owner.Refuse) throw new UnauthorizedAccessException("Operation is not enabled for this connection.");
lock (owner.Sent) owner.Sent.Add(request);
return Task.FromResult(owner.Result);
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
/// A stream that carries the serving identity it was established with (as the production one does) and no frames.
private sealed class FakeStream : IDataSubscription, IDataSubscriptionProvenance
{
private readonly Channel _frames = Channel.CreateUnbounded();
public ServingIdentity Serving => GrpcDataProjectedConditionMethodTests.Serving;
public TaskCompletionSource Opened { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
if (command is OpenSubscription open) Opened.TrySetResult(open);
return Task.CompletedTask;
}
public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
public void End() => _frames.Writer.TryComplete();
public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
}
}