using System.Collections.Concurrent; using System.Diagnostics; using System.Security.Cryptography; using Opc.Ua; using Opc.Ua.Client; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; using SdkMonitoredItem = Opc.Ua.Client.MonitoredItem; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; /// /// A3b over the wire (plan §5.6): Part 9 methods on an imported condition are claimed by the node manager's /// implementation and dispatched to the origin through the /// port — never under the node manager's Lock, never applied locally (the /// node changes only when the origin's record arrives), gated per local caller, with the EventId checked against this /// consumer's own registry. The port here stands in for the origin (its handler can be stalled, can time out, can join). /// [Trait("Feature", "GrpcData"), Trait("Phase", "A3")] public sealed class ImportedConditionMethodWireTests { private const string Connection = "conn-a"; private const string MappingA = "map-a"; private const string Granted = ServerEventRig.KeyPrincipal; private static readonly string Key1 = KeyOf("cond-1"); private static readonly DataActivationMarker Marker1 = new("inc", 1); [Fact] public async Task A_remote_Acknowledge_reaches_the_origin_once_a_duplicate_joins_and_local_state_changes_only_with_the_origin_record() { var ct = TestContext.Current.CancellationToken; await using var rig = await ServerEventRig.StartAsync("a3b-ack", encrypted: false, ct); var f = Fixture.Install(rig); f.Apply(Update(version: 3, active: true, acked: false)); using var session = await rig.ConnectAsync(anonymous: false, ct); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); f.Port.Handler = async (_, _) => { await release.Task; return Applied(); }; var eventId = f.CurrentEventId(); var first = CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "op ack", ct); await WaitUntilAsync(() => f.Port.Calls.Count == 1); var duplicate = CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "op ack", ct); await WaitUntilAsync(() => rig.Nm.ImportedMethodsJoined == 1); f.Acked().ShouldBeFalse("nothing is applied locally while the origin has not answered"); release.SetResult(); (await first).ShouldBe(StatusCodes.Good); (await duplicate).ShouldBe(StatusCodes.Good, "a duplicate of an in-flight call joins it and gets the same answer"); f.Port.Calls.Count.ShouldBe(1, "the origin is called once"); f.Acked().ShouldBeFalse("Good from the origin is not the confirming record: still unacknowledged locally"); var call = f.Port.Calls.Single(); call.Method.ShouldBe(DataConditionMethods.Acknowledge); call.ConnectionId.ShouldBe(Connection); call.ConditionKey.ShouldBe(Key1); call.Placement.ShouldBe(f.Placements[0], "the primary placement the caller passed the gate on"); call.ExpectedActivation.ShouldBe(Marker1); call.Comment.ShouldBe("op ack"); call.OnBehalfOf.ShouldBe(Granted); call.OperationId.ShouldStartWith("a3-"); call.RemainingBudget.ShouldBeLessThanOrEqualTo(f.Port.Timeout); // The origin's record arrives on the stream: only now does the local node change (positive control). f.Apply(Update(version: 4, active: true, acked: true)); f.Acked().ShouldBeTrue(); // A later call (nothing in flight) is a NEW dispatch with a fresh operation id — no retry, no stale join. (await CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), "note", ct)).ShouldBe(StatusCodes.Good); f.Port.Calls.Count.ShouldBe(2); f.Port.Calls.Select(c => c.OperationId).Distinct().Count().ShouldBe(2); f.Port.Calls.Last().Method.ShouldBe(DataConditionMethods.AddComment); } [Fact] public async Task A_child_method_Call_is_authorized_through_the_condition_and_a_caller_without_the_grant_is_denied_unsent() { var ct = TestContext.Current.CancellationToken; await using var rig = await ServerEventRig.StartAsync("a3b-child", encrypted: false, ct); var f = Fixture.Install(rig); f.Apply(Update(version: 3, active: true, acked: false)); using var allowed = await rig.ConnectAsync(anonymous: false, ct); using var denied = await rig.ConnectAsync(anonymous: true, ct); var ns = (ushort)allowed.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri); var childMethod = new NodeId(ImportedConditionIds.ChildIdentifier(f.Identifier, "Acknowledge"), ns); rig.Nm.FindImportedCondition(Connection, Key1)!.Acknowledge!.NodeId.ShouldBe(childMethod, "the instance-scoped method node (#629)"); (await CallAsync(denied, f.ConditionId(denied), childMethod, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadUserAccessDenied); (await CallAsync(denied, f.ConditionId(denied), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)) .ShouldBe(StatusCodes.BadUserAccessDenied); f.Port.Calls.ShouldBeEmpty("a caller without the grant sends nothing"); f.Port.AuthorizedFor.ShouldContain(("anonymous", DataConditionMethods.Acknowledge), "re-gated per LOCAL caller"); // The grant is per method: AlarmAcknowledge does not authorize Confirm. f.Port.GrantedMethods = DataConditionMethods.Acknowledge | DataConditionMethods.AddComment; f.Apply(Update(version: 4, active: true, acked: false, native: false, message: "scripted")); (await CallAsync(allowed, f.ConditionId(allowed), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(), "c", ct)) .ShouldBe(StatusCodes.BadUserAccessDenied); f.Port.Calls.ShouldBeEmpty(); // Positive control: the granted caller's child Call reaches the origin. (await CallAsync(allowed, f.ConditionId(allowed), childMethod, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good); f.Port.Calls.Single().Method.ShouldBe(DataConditionMethods.Acknowledge); f.Acked().ShouldBeFalse(); } [Fact] public async Task An_unknown_or_superseded_EventId_is_BadEventIdUnknown_and_a_native_Confirm_or_a_shelve_is_BadNotSupported_all_unsent() { var ct = TestContext.Current.CancellationToken; await using var rig = await ServerEventRig.StartAsync("a3b-eventid", encrypted: false, ct); var f = Fixture.Install(rig); f.Apply(Update(version: 3, active: true, acked: false)); using var session = await rig.ConnectAsync(anonymous: false, ct); var id = f.ConditionId(session); var old = f.CurrentEventId(); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, Guid.NewGuid().ToByteArray(), "x", ct)) .ShouldBe(StatusCodes.BadEventIdUnknown); // A new occurrence (Acked true→false bumps the marker at the origin): the old EventId no longer binds. f.Apply(Update(version: 4, active: true, acked: true)); f.Apply(Update(version: 5, active: true, acked: false, marker: new DataActivationMarker("inc", 2), message: "again")); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, old, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown); // Native Confirm has no upstream path; shelving is not imported at all. (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadNotSupported); var shelve = await session.CallAsync(null, [new CallMethodRequest { ObjectId = id, MethodId = MethodIds.AlarmConditionType_ShelvingState_OneShotShelve }], ct); shelve.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadNotSupported.Code); f.Port.Calls.ShouldBeEmpty("every refusal above is local and sends nothing"); // Positive control: the current EventId (new marker) reaches the origin with the CURRENT marker. (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good); f.Port.Calls.Single().ExpectedActivation.ShouldBe(new DataActivationMarker("inc", 2)); } [Fact] public async Task A_resync_with_a_new_marker_re_binds_EventIds_only_when_time_is_unchanged_else_RefreshRequired_and_a_fresh_ackable_EventId() { var ct = TestContext.Current.CancellationToken; await using var rig = await ServerEventRig.StartAsync("a3b-rebind", encrypted: false, ct); var f = Fixture.Install(rig); var t0 = DateTimeOffset.UtcNow.AddMinutes(-1); f.Apply(Update(version: 3, active: true, acked: false, time: t0)); using var session = await rig.ConnectAsync(anonymous: false, ct); var id = f.ConditionId(session); var before = f.CurrentEventId(); // Origin restart, same state, same time ⇒ re-bound (F6): the pre-resync EventId still acknowledges. f.Apply(Update(version: 1, active: true, acked: false, time: t0, marker: new DataActivationMarker("inc-b", 7))); f.CurrentEventId().ShouldBe(before, "no event, no new EventId"); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.Good); f.Port.Calls.Last().ExpectedActivation.ShouldBe(new DataActivationMarker("inc-b", 7)); // Another resync whose time differs (a clear + re-raise may have happened in the gap) ⇒ NOT re-bound. var refresh = rig.Nm.ImportedRefreshRequiredQueued; f.Apply(Update(version: 1, active: true, acked: false, time: t0.AddSeconds(5), marker: new DataActivationMarker("inc-c", 9))); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown); var fresh = f.CurrentEventId(); fresh.ShouldNotBe(before, "a fresh EventId bound to the new marker — what a ConditionRefresh now returns"); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, fresh, "x", ct)).ShouldBe(StatusCodes.Good); f.Port.Calls.Count.ShouldBe(2); f.Port.Calls.Last().ExpectedActivation.ShouldBe(new DataActivationMarker("inc-c", 9)); // RequireRefresh ran (it queues only to items that exist; none here — the counter path is pinned by A3a's tests). rig.Nm.ImportedRefreshRequiredQueued.ShouldBeGreaterThanOrEqualTo(refresh); } /// /// §5.6 step 6 / §9.3 L3 (hard gate): the origin's method handler stalls 5 s. Read, Browse and a data Publish on the /// consumer complete in < 200 ms meanwhile, the node manager's Lock is free, and no acknowledged state is /// observable before the origin's record (positive control: it arrives after release). /// [Fact] public async Task Lock_freedom_a_5s_stalled_origin_method_delays_no_Read_Browse_or_data_Publish_and_applies_nothing_before_the_record() { var ct = TestContext.Current.CancellationToken; await using var rig = await ServerEventRig.StartAsync("a3b-l3", encrypted: false, ct); var f = Fixture.Install(rig); var tag = rig.EnsureRawVariable("l3", "Double", writable: false); rig.Sink.WriteValue(tag, 0.0, 0, DateTime.UtcNow, AddressSpaceRealm.Raw); f.Apply(Update(version: 3, active: true, acked: false)); using var caller = await rig.ConnectAsync(anonymous: false, ct); using var observer = await rig.ConnectAsync(anonymous: false, ct); var tagId = ExpandedNodeId.ToNodeId(ExpandedNodeId.Parse(ServerEventRig.RawNsu(tag)), observer.NamespaceUris); var plant = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var plantId = new NodeId(plant.IdentifierAsString, (ushort)observer.NamespaceUris.GetIndex(V3NodeIds.RawNamespaceUri)); var values = new ConcurrentDictionary(); var subscription = new Subscription(observer.DefaultSubscription) { PublishingInterval = 20 }; observer.AddSubscription(subscription); await subscription.CreateAsync(ct); var item = new SdkMonitoredItem(subscription.DefaultItem) { StartNodeId = tagId, AttributeId = Attributes.Value, SamplingInterval = 0, QueueSize = 100 }; item.Notification += (mi, _) => { var now = Stopwatch.GetTimestamp(); foreach (var v in mi.DequeueValues()) if (v.WrappedValue.TryGetValue(out double d)) values.TryAdd(d, now); }; subscription.AddItem(item); await subscription.ApplyChangesAsync(ct); async Task<(double Read, double Browse, double Publish, double LockWait)> MeasureAsync(double value) { var sw = Stopwatch.StartNew(); (await observer.ReadValueAsync(tagId, ct)).StatusCode.ShouldBe(StatusCodes.Good); var read = sw.Elapsed.TotalMilliseconds; sw.Restart(); var browse = await observer.BrowseAsync(null, null, 0, [new BrowseDescription { NodeId = plantId, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All }], ct); StatusCode.IsGood(browse.Results[0].StatusCode).ShouldBeTrue(); var browseMs = sw.Elapsed.TotalMilliseconds; var written = Stopwatch.GetTimestamp(); rig.Sink.WriteValue(tag, value, 0, DateTime.UtcNow, AddressSpaceRealm.Raw); await WaitUntilAsync(() => values.ContainsKey(value)); var publish = Stopwatch.GetElapsedTime(written, values[value]).TotalMilliseconds; sw.Restart(); var taken = Monitor.TryEnter(rig.Nm.Lock, TimeSpan.FromMilliseconds(200)); var lockWait = sw.Elapsed.TotalMilliseconds; if (taken) Monitor.Exit(rig.Nm.Lock); taken.ShouldBeTrue("the node manager Lock is free while the remote call is in flight"); return (read, browseMs, publish, lockWait); } var baseline = await MeasureAsync(1.0); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); f.Port.Timeout = TimeSpan.FromSeconds(20); f.Port.Handler = async (_, token) => { await Task.WhenAny(release.Task, Task.Delay(TimeSpan.FromSeconds(5), token)); return Applied(); }; var stall = Stopwatch.StartNew(); var ack = CallAsync(caller, f.ConditionId(caller), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "l3", ct); await WaitUntilAsync(() => f.Port.Calls.Count == 1); var during = new List<(double Read, double Browse, double Publish, double LockWait)>(); for (var i = 0; i < 10 && !ack.IsCompleted; i++) { during.Add(await MeasureAsync(100 + i)); f.Acked().ShouldBeFalse("no acknowledged state is observable before the origin's record"); await Task.Delay(200, ct); } ack.IsCompleted.ShouldBeFalse("the measurements ran while the remote call was stalled"); during.Count.ShouldBe(10); (await ack).ShouldBe(StatusCodes.Good); var stalled = stall.Elapsed; f.Acked().ShouldBeFalse(); f.Apply(Update(version: 4, active: true, acked: true)); f.Acked().ShouldBeTrue("positive control: the record applies after release"); var maxRead = during.Max(m => m.Read); var maxBrowse = during.Max(m => m.Browse); var maxPublish = during.Max(m => m.Publish); var maxLock = during.Max(m => m.LockWait); var line = $"L3: stall {stalled.TotalMilliseconds:F0} ms; baseline read {baseline.Read:F1} browse {baseline.Browse:F1} publish {baseline.Publish:F1} lock {baseline.LockWait:F2}; " + $"during (n={during.Count}) max read {maxRead:F1} browse {maxBrowse:F1} publish {maxPublish:F1} lock {maxLock:F2} ms"; TestContext.Current.TestOutputHelper?.WriteLine(line); if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine); stalled.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(4.9)); maxRead.ShouldBeLessThan(200); maxBrowse.ShouldBeLessThan(200); maxPublish.ShouldBeLessThan(200); } [Fact] public async Task One_Call_request_mixing_a_local_condition_and_an_imported_one_runs_the_local_one_through_base_Call_unchanged() { var ct = TestContext.Current.CancellationToken; await using var rig = await ServerEventRig.StartAsync("a3b-mixed", encrypted: false, ct); rig.Enforce(true, [ServerEventRig.Key()], ServerEventRig.ClusterGrant(Granted, "acl-key", NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.MethodCall)); rig.MaterialiseNative(); var routed = 0; rig.Nm.NativeAlarmAckRouter = _ => Interlocked.Increment(ref routed); var f = Fixture.Install(rig); f.Apply(Update(version: 3, active: true, acked: false)); using var session = await rig.ConnectAsync(anonymous: false, ct); var events = new RecordedEvents(); var subscription = await RecordedEvents.SubscribeAsync(session, events, ct); var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server); await subscription.ApplyChangesAsync(ct); rig.Project(true, new AlarmConditionSnapshot(true, false, true, true, AlarmShelvingKind.Unshelved, 700, "local")); await RecordedEvents.WaitUntilAsync(() => events.Has(serverItem, "local")); var localEventId = events.LatestEventId(serverItem, "local"); var response = await session.CallAsync(null, [ new CallMethodRequest { ObjectId = ServerEventRig.ConditionNodeId(session, native: true), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, InputArguments = [new Variant(ByteString.From(localEventId)), new Variant(new LocalizedText("local ack"))] }, new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] }, ], ct); response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the local native ack runs the SDK path (base.Call) unchanged"); response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the imported one is claimed and dispatched"); Volatile.Read(ref routed).ShouldBe(1); f.Port.Calls.Single().Comment.ShouldBe("remote ack"); await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(serverItem, "local").Count >= 2); events.ConditionEvents(serverItem, "local").Last()[RecordedEvents.AckedField].ClrValue()!.ShouldBe(true, "one local ack event (#587)"); f.Acked().ShouldBeFalse("the imported condition did not change locally"); } [Fact] public async Task A_timed_out_call_answers_BadTimeout_OutcomeUnknown_is_BadCommunicationError_and_a_refusal_passes_the_origins_status_nothing_applied() { var ct = TestContext.Current.CancellationToken; await using var rig = await ServerEventRig.StartAsync("a3b-timeout", encrypted: false, ct); var f = Fixture.Install(rig); f.Apply(Update(version: 3, active: true, acked: false)); using var session = await rig.ConnectAsync(anonymous: false, ct); var id = f.ConditionId(session); // ConditionMethodTimeoutMilliseconds = 300 ms; the origin never answers. f.Port.Timeout = TimeSpan.FromMilliseconds(300); var cancelled = false; f.Port.Handler = async (_, token) => { try { await Task.Delay(Timeout.Infinite, token); } catch (OperationCanceledException) { cancelled = true; throw; } return Applied(); }; var sw = Stopwatch.StartNew(); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadTimeout); sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(3), "bounded by the mapping's method timeout (+ grace), not the request's"); await WaitUntilAsync(() => Volatile.Read(ref cancelled)); f.Port.Calls.Count.ShouldBe(1, "dispatched once, never retried"); f.Acked().ShouldBeFalse(); f.Port.Timeout = TimeSpan.FromSeconds(5); f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.OutcomeUnknown, 0x80050000u, "transport failed")); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadCommunicationError); f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadInvalidState.Code, "not Primary")); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadInvalidState); f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "No condition stream")); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadNoCommunication); f.Acked().ShouldBeFalse("no outcome applies anything locally"); } // --------------------------------------------------------------------------------------------------------------------- private static DataConditionMethodResult Applied() => new(DataWriteState.AcceptedUnconfirmed, 0, null); private static string KeyOf(string seed) => Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); private static ImportedConditionUpdate Update(long version, bool active, bool acked, DataActivationMarker? marker = null, string message = "HR200 high", bool native = true, DateTimeOffset? time = null) { var placements = Fixture.DefaultPlacements; var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", "HR200", native ? DataConditionSourceKind.Native : DataConditionSourceKind.Scripted, placements.Select(p => p.Placement).ToArray(), (uint)(native ? DataConditionMethodSets.Native : DataConditionMethodSets.Scripted)); var state = new DataConditionState(Key1, version, false, true, info, active, acked, true, true, 0, 777, message, StatusCodes.Good.Code, null, 0, time ?? DateTimeOffset.UtcNow, active || !acked, marker ?? Marker1); return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote-a/" + placements[0].RelativePath); } /// Calls one method and returns its status (never throws for a Bad result). private static async Task CallAsync(ISession session, NodeId objectId, NodeId methodId, object eventId, string comment, CancellationToken ct) { var bytes = eventId switch { ByteString b => b, byte[] a => ByteString.From(a), _ => throw new ArgumentException(nameof(eventId)) }; var response = await session.CallAsync(null, [new CallMethodRequest { ObjectId = objectId, MethodId = methodId, InputArguments = [new Variant(bytes), new Variant(new LocalizedText(comment))] }], ct); var code = response.Results[0].StatusCode; return StatusCode.IsGood(code) ? StatusCodes.Good : code; } private static async Task WaitUntilAsync(Func condition) { var deadline = DateTime.UtcNow.AddSeconds(15); while (!condition()) { if (DateTime.UtcNow > deadline) condition().ShouldBeTrue("condition not met within 15 s"); await Task.Delay(10); } } /// The fake origin port: a per-principal, per-method gate and a scriptable handler that records each dispatch. internal sealed class FakePort : IProjectedConditionMethods { public HashSet Granted { get; } = new(StringComparer.Ordinal); public DataConditionMethods GrantedMethods { get; set; } = DataConditionMethodSets.All; public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(5); public ConcurrentQueue<(string Principal, DataConditionMethods Method)> AuthorizedFor { get; } = new(); public ConcurrentQueue Calls { get; } = new(); public Func> Handler { get; set; } = (_, _) => Task.FromResult(Applied()); public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList placements, DataConditionMethods method) { AuthorizedFor.Enqueue((caller?.Principal ?? "", method)); return caller is not null && Granted.Contains(caller.Principal) && (GrantedMethods & method) == method ? new ImportedConditionMethodRoute(placements[0], Timeout) : null; } public Task CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken) { Calls.Enqueue(call); return Handler(call, cancellationToken); } } private sealed class Fixture { public required ServerEventRig Rig { get; init; } public required FakePort Port { get; init; } public string Identifier => ImportedConditionIds.Identifier(Connection, Key1); public static IReadOnlyList DefaultPlacements { get; } = [ new(MappingA, DataRealm.Raw, View("Plant/dev1/HR200"), "Plant/remote-a", "dev1/HR200"), ]; public IReadOnlyList Placements => DefaultPlacements; public static Fixture Install(ServerEventRig rig) { var nm = rig.Nm; nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant"); nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, root), parent, "remote-a", "Plant/remote-a", MappingA, 1, () => true), out _).ShouldBeTrue(); var access = new ImportedConditionEventWireTests.FakeConditionAccess(); access.Allowed.Add(Granted); nm.ProjectedConditionAccess = access; var port = new FakePort(); port.Granted.Add(Granted); nm.ProjectedConditionMethods = port; return new Fixture { Rig = rig, Port = port }; } public NodeId ConditionId(ISession session) => new(Identifier, (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri)); public ByteString CurrentEventId() => Rig.Nm.FindImportedCondition(Connection, Key1)!.EventId!.Value; public bool Acked() => Rig.Nm.FindImportedCondition(Connection, Key1)!.AckedState!.Id!.Value; public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]); private static DataView View(string path) => new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path); } }