using System.Security.Cryptography; 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; /// /// A3a (plan §5.4, §5.5): the consumer condition runtime over a scripted origin stream — the per-mapping capacity /// decision before anything is materialised (and the item removed), the snapshot barrier, the host caps, 2,000 conditions /// without MaxProjectionNodes, the version rule (removal bypasses it and forgets the version), the lifetime rule (a /// stream end re-snapshots and never removes; only a complete re-snapshot does), staleness, the mapping gate with a real /// , primary placement from deployed config, and demand with linger. /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")] public sealed class GrpcDataProjectedConditionAccessTests { private const string Connection = "conn-a"; [Fact] public async Task A_total_over_MaxConditions_is_ConditionCapacity_and_its_item_removed_before_materialising_other_mappings_unaffected() { await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 3); await f.WaitAsync(() => stream.Removed.Count == 1); stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the over-limit item is removed, not held open"); f.Sink.Applied.ShouldBeEmpty("nothing is materialised before the barrier"); stream.Begin("map-b", total: 2); stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3)); f.Sink.Applied.ShouldBeEmpty(); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 2); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Complete); f.Sink.Applied.ShouldAllBe(u => u.Placements.All(p => p.MappingId == "map-b")); } [Fact] public async Task Two_thousand_conditions_in_one_mapping_materialise_without_MaxProjectionNodes_and_the_host_cap_rejects_before_materialising() { await using var f = new Fixture(("map-a", DataRealm.Raw, 5000)); f.Mappings.Current[0].Mapping.MaxProjectionNodes = 10; using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 2000); stream.Records("map-a", Enumerable.Range(0, 2000).Select(i => Record(Key("k" + i), 3)).ToArray()); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 2000); f.Sink.Applied.Select(u => u.State.ConditionKey).Distinct().Count().ShouldBe(2000); f.Mappings.Current[0].Mapping.MaxProjectionNodes.ShouldBe(10, "conditions have their own budget"); // Host cap: 1,999 conditions' worth of nodes ⇒ the 2,000-condition mapping is rejected at begin. await using var capped = new Fixture(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 1999 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50)), ("map-a", DataRealm.Raw, 5000)); using var cappedDemand = capped.Access.AcquireEventDemand(null); var cappedStream = await capped.NextStreamAsync(); cappedStream.Ack(); cappedStream.Begin("map-a", total: 2000); await capped.WaitAsync(() => cappedStream.Removed.Count == 1); capped.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); capped.Sink.Applied.ShouldBeEmpty(); } [Fact] public async Task Versions_gate_per_key_but_a_removal_bypasses_the_gate_and_forgets_the_version() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 1); stream.Records("map-a", Record(Key("x"), 5)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); stream.Records("map-a", Record(Key("x"), 4, message: "stale")); // older ⇒ dropped stream.Records("map-a", Record(Key("x"), 5, removed: true)); // removal at the hub watermark (= an applied version) await f.WaitAsync(() => f.Sink.Removed.Count == 1); f.Sink.Applied.ShouldNotContain(u => u.State.Message == "stale"); stream.Records("map-a", Record(Key("x"), 3, message: "re-added")); // the version was forgotten await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Message == "re-added")); } [Fact] public async Task A_stream_end_re_snapshots_without_removing_and_only_a_complete_re_snapshot_removes_staleness_in_between() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var first = await f.NextStreamAsync(); first.Ack(); first.Begin("map-a", total: 2); first.Records("map-a", Record(Key("x"), 3), Record(Key("y"), 3)); first.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 2); first.End(); // an origin deploy ends the stream (A2 S1) var second = await f.NextStreamAsync(); await f.WaitAsync(() => f.Sink.Stale.Count >= 1); // stale timeout (100 ms) passes before the new snapshot completes f.Sink.Removed.ShouldBeEmpty("a stream end is never 'conditions removed'"); second.Ack(); second.Begin("map-a", total: 1); second.Records("map-a", Record(Key("x"), 9)); f.Sink.Removed.ShouldBeEmpty("an incomplete snapshot removes nothing"); second.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Count == 1); f.Sink.Removed.Single().ShouldBe(Key("y")); f.Access.BarriersCompleted(Connection).ShouldBe(2, "one barrier per stream: the first snapshot and the re-snapshot"); } [Fact] public async Task A_mapping_whose_snapshot_times_out_is_Unavailable_the_rest_proceed_and_RefreshRequired_follows() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); f.Mappings.Current[0].Mapping.ConditionSnapshotTimeoutMilliseconds = 300; f.Mappings.Current[1].Mapping.ConditionSnapshotTimeoutMilliseconds = 300; using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-b", total: 1); stream.Records("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); f.Sink.RefreshRequired.ShouldBe(1); } [Fact] public async Task The_primary_placement_comes_from_deployed_config_Raw_first_then_mapping_id_and_SourceName_follows_it() { await using var f = new Fixture(("map-u", DataRealm.Uns, 10), ("map-z", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); // Stream order deliberately the reverse of the deployed order. foreach (var mapping in new[] { "map-u", "map-z", "map-b" }) { stream.Begin(mapping, total: 1); stream.Records(mapping, Record(Key("x"), 3, placement: mapping == "map-u" ? f.UnsPlacement : f.RawPlacement)); stream.Complete(mapping); } await f.WaitAsync(() => f.Sink.Applied.Count == 1); var update = f.Sink.Applied.Single(); update.Placements.Select(p => p.MappingId).ShouldBe(["map-b", "map-z", "map-u"]); update.SourceName.ShouldBe("Plant/map-b/dev1/HR200", "the primary mapping's branch path + the address below the remote root"); update.Placements[0].FolderLocalSubject.ShouldBe("Plant/map-b/dev1"); } [Fact] public async Task The_gate_is_the_mapping_Subscribe_grant_on_the_placement_folder_and_needs_the_condition_bits() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, f.RawPlacement, "Plant/map-a/dev1", "dev1/HR200"); f.Grant(NodePermissions.Browse | NodePermissions.Subscribe); f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeTrue(); f.Access.CanSee(f.Identity("someone-else"), [placement]).ShouldBeFalse(); f.Access.CanSee(null, [placement]).ShouldBeFalse(); f.Grant(NodePermissions.Browse); f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("Subscribe is the visibility permission (not AlarmRead)"); f.Grant(NodePermissions.Browse | NodePermissions.Subscribe); f.Mappings.Current[0].Mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe; f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("a mapping without AlarmSubscribe carries no conditions"); } [Fact] public async Task Demand_opens_the_stream_and_the_linger_closes_it_and_removes_what_it_materialised() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); f.Access.IsRunning(Connection).ShouldBeFalse(); var demand = f.Access.AcquireEventDemand(null)!; var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 1); stream.Records("map-a", Record(Key("x"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); demand.Dispose(); f.Access.IsRunning(Connection).ShouldBeTrue("the linger keeps it open"); await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1); } // --------------------------------------------------------------------------------------------------------------------- internal static string Key(string seed) => Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); private static DataConditionState Record(string key, long version, bool removed = false, string message = "high", DataView? placement = null) { var info = removed ? null : new DataConditionInfo("AlarmConditionType", "HR200", DataConditionSourceKind.Native, [placement ?? Fixture.DefaultRawPlacement], 3); return new DataConditionState(key, version, removed, !removed, info, true, false, true, true, 0, 500, message, 0, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1)); } private sealed class Fixture : IAsyncDisposable { internal static readonly DataView DefaultRawPlacement = new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"), DataRealm.Raw, null, 0, "Plant/dev1/HR200"); public DataView RawPlacement => DefaultRawPlacement; public DataView UnsPlacement { get; } = new(new DataAddress("origin", "https://zb.com/otopcua/uns", "string", "Area/Line/Filler/HR200"), DataRealm.Uns, null, 0, "Area/Line/Filler/HR200"); 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) }; public FakeMappings Mappings { get; } public FakeSink Sink { get; } = new(); public FakeConnections Connections { get; } = new(); public ProjectedConditionAccess Access { get; } public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings) : this(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)), mappings) { } public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) { Grant(NodePermissions.Browse | NodePermissions.Subscribe); Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions)).ToList()); var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System); Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, 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)); private static ProjectedMappingPlacement Placement(string id, DataRealm realm, int maxConditions) { var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = id, DataConnectionId = Connection, Enabled = true, Realm = realm, RemoteRealm = realm, AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe, MaxConditions = maxConditions, ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000, BranchName = id, RemoteNamespaceUri = realm == DataRealm.Raw ? "https://zb.com/otopcua/raw" : "https://zb.com/otopcua/uns", RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "Plant" : "Area", }; var segments = new[] { "Plant", id }; var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", mapping.RemoteIdentifier), realm, id, 1, string.Join('/', segments)); var scope = new NodeScope { ClusterId = "c1", Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = segments }; return new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority()); } public async Task NextStreamAsync() => await Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken); public async Task WaitAsync(Func condition) { var deadline = DateTime.UtcNow.AddSeconds(10); while (!condition()) { if (DateTime.UtcNow > deadline) 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; } internal sealed class FakeMappings(List current) : IProjectedConditionMappings { public IReadOnlyList Current { get; } = current; public event Action? Changed; public void Raise() => Changed?.Invoke(); } internal sealed class FakeSink : IProjectedConditionSink { private readonly object _gate = new(); private readonly List _applied = []; private readonly List _removed = []; private readonly List _stale = []; private int _refresh; public IReadOnlyList Applied { get { lock (_gate) return _applied.ToList(); } } public IReadOnlyList Removed { get { lock (_gate) return _removed.ToList(); } } public IReadOnlyList Stale { get { lock (_gate) return _stale.ToList(); } } public int RefreshRequired => Volatile.Read(ref _refresh); public void ApplyConditions(IReadOnlyList updates) { lock (_gate) _applied.AddRange(updates); } public void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys) { lock (_gate) _removed.AddRange(conditionKeys); } public void MarkConnectionStale(string connectionId) { lock (_gate) _stale.Add(connectionId); } public void RequireRefresh(string connectionId) => Interlocked.Increment(ref _refresh); } internal sealed class FakeConnections : IGrpcDataAdapterConnectionSource { public Channel Streams { get; } = Channel.CreateUnbounded(); public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => 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 { 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) => Task.FromResult>>(request.Views.Select(v => new DataItemResult("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "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 ValueTask DisposeAsync() => ValueTask.CompletedTask; } internal sealed class FakeStream : IDataSubscription { private readonly Channel _frames = Channel.CreateUnbounded(); private readonly TaskCompletionSource _open = new(TaskCreationOptions.RunContinuationsAsynchronously); private long _sequence; public List Removed { get; } = []; public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) { if (command is OpenSubscription open) _open.TrySetResult(open); if (command is RemoveSubscriptionItems remove) lock (Removed) Removed.AddRange(remove.Items); return Task.CompletedTask; } public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); return ValueTask.CompletedTask; } private OpenSubscription Open => _open.Task.Wait(TimeSpan.FromSeconds(10)) ? _open.Task.Result : throw new TimeoutException("no open"); public DataItemHandle HandleOf(string mapping) { var index = Open.Items.Select((x, i) => (x, i)).Single(x => x.x.ClientItemId == mapping).i; return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1); } public void Ack() => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open", Open.Items.Select(x => new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray())); public void Begin(string mapping, int total) => Frame(mapping, true, total, [], false); public void Records(string mapping, params DataConditionState[] records) { foreach (var chunk in records.Chunk(128)) Frame(mapping, false, null, chunk, false); } public void Complete(string mapping) => Frame(mapping, true, null, [], true); public void End() => _frames.Writer.TryComplete(); private void Frame(string mapping, bool snapshot, int? total, IReadOnlyList items, bool complete) => _frames.Writer.TryWrite(new DataSubscriptionConditions(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, HandleOf(mapping), snapshot, total, items, complete)); } }