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.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using SdkMonitoredItem = Opc.Ua.Client.MonitoredItem;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
///
/// A3a over the wire (plan §5.2–§5.5): imported conditions materialised by the consumer's registry in the
/// mapped/conditions namespace reach a projected placement folder and the Server object (i=2253) as exactly
/// one event per origin transition, carry the §5.2 identity fields, are gated by the mapping gate with ACLs OFF (A3-SEC),
/// keep their ConditionId when placements change (N4), wire/unwire notifiers lazily and symmetrically (N7), and never
/// tell a client "known inactive" on staleness (T2). Every absence assertion follows a must-arrive sentinel.
///
[Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class ImportedConditionEventWireTests
{
private const string Connection = "conn-a";
private const string MappingA = "map-a";
private const string MappingB = "map-b";
private const string Granted = ServerEventRig.KeyPrincipal;
private static readonly string Key1 = KeyOf("cond-1");
private static readonly string Key2 = KeyOf("cond-2");
// Select clauses: EventId, SourceNode, SourceName, Message, Severity, ConditionName, ActiveState/Id, AckedState/Id,
// Quality, ConditionId (ConditionType NodeId attribute), EventType.
private const int EventIdF = 0, SourceNodeF = 1, SourceNameF = 2, MessageF = 3, SeverityF = 4, ConditionNameF = 5,
ActiveF = 6, AckedF = 7, QualityF = 8, ConditionIdF = 9, EventTypeF = 10;
[Fact]
public async Task Exactly_one_event_per_origin_transition_at_both_placement_folders_and_the_Server_object_with_identity_fields()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-once", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
using var session = await rig.ConnectAsync(anonymous: false, ct);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
var device = AddItem(subscription, f.DeviceFolder);
var anchor = AddItem(subscription, f.Anchor);
await subscription.ApplyChangesAsync(ct);
new[] { server, device, anchor }.ShouldAllBe(i => StatusCode.IsGood(i.Status.Error == null ? StatusCodes.Good : i.Status.Error.StatusCode));
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "acked"));
f.Apply(Update(Key1, version: 5, active: false, acked: true, f.TwoPlacements(), message: "sentinel"));
await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "sentinel") && events.Of(device).Any(e => Message(e) == "sentinel")
&& events.Of(anchor).Any(e => Message(e) == "sentinel"));
foreach (var item in new[] { server, device, anchor })
{
events.Of(item).Count(e => Message(e) == "acked").ShouldBe(1, $"exactly one event per transition at {item.StartNodeId}");
events.Of(item).Count(e => Message(e) == "sentinel").ShouldBe(1);
}
// §5.2 identity: ConditionId = SourceNode = the opaque (connection, key) id in mapped/conditions; SourceName = the
// primary placement's local display path; Severity verbatim; ConditionName from the origin.
var e0 = events.Of(server).First(e => Message(e) == "acked");
var expectedId = new NodeId(ImportedConditionIds.Identifier(Connection, Key1),
(ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri));
e0[SourceNodeF].GetNodeId().ShouldBe(expectedId);
e0[ConditionIdF].GetNodeId().ShouldBe(expectedId);
e0[SourceNameF].GetString().ShouldBe("Plant/remote-a/dev1/HR200");
e0[SeverityF].GetUInt16().ShouldBe((ushort)777);
e0[ConditionNameF].GetString().ShouldBe("HR200");
e0[AckedF].GetBoolean().ShouldBeTrue();
e0[ActiveF].GetBoolean().ShouldBeTrue();
rig.Nm.ImportedConditionCount.ShouldBe(1);
}
[Fact]
public async Task A3_SEC_with_ACLs_off_a_session_without_the_mapping_grant_receives_nothing_at_i2253_on_a_folder_or_on_refresh()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-sec", encrypted: false, ct);
var f = Fixture.Install(rig, Granted); // the anonymous principal holds no grant; ACL enforcement is OFF in this rig
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var allowed = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var allowedEvents = new Events();
var deniedEvents = new Events();
var allowedSub = await SubscribeAsync(allowed, allowedEvents, ct);
var deniedSub = await SubscribeAsync(denied, deniedEvents, ct);
var allowedServer = AddItem(allowedSub, ObjectIds.Server);
var deniedServer = AddItem(deniedSub, ObjectIds.Server);
var deniedFolder = AddItem(deniedSub, f.DeviceFolder);
await allowedSub.ApplyChangesAsync(ct);
await deniedSub.ApplyChangesAsync(ct);
deniedFolder.Status.Error?.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code,
"a projected notifier admits only a caller who sees a condition wired there");
await allowedSub.ConditionRefreshAsync(ct);
await deniedSub.ConditionRefreshAsync(ct);
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "sentinel"));
await Events.WaitUntilAsync(() => allowedEvents.Of(allowedServer).Any(e => Message(e) == "sentinel"));
// Positive control: the granted session got the refresh replay AND the transition.
allowedEvents.Of(allowedServer).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(2);
// Must-arrive sentinel on the denied session's own subscription (a non-condition event every session receives):
// RefreshStart/End of its own refresh arrived, so its queue was published after the transition.
await Events.WaitUntilAsync(() => deniedEvents.Of(deniedServer).Any(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType));
deniedEvents.Of(deniedServer).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(0, "no imported condition event, live or refreshed");
// Revocation reaches a queued event at publish time: the marker re-checks the gate.
f.Access.Allowed.Clear();
Interlocked.Increment(ref f.Access.Generation); // a revocation moves the authority generation (verdict caches key on it)
f.Apply(Update(Key1, version: 5, active: false, acked: true, f.TwoPlacements(), message: "after-revoke"));
await Task.Delay(500, ct);
allowedEvents.Of(allowedServer).Count(e => Message(e) == "after-revoke").ShouldBe(0);
}
[Fact]
public async Task A_condition_child_Read_is_authorized_through_the_condition_and_methods_are_refused_unapplied()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-child", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
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 id = ImportedConditionIds.Identifier(Connection, Key1);
var child = new NodeId(ImportedConditionIds.ChildIdentifier(id, "ActiveState/Id"), ns);
rig.Nm.FindImportedCondition(Connection, Key1)!.ActiveState!.Id!.NodeId.ShouldBe(child, "children are instance-scoped (#629) in mapped/conditions");
var good = await allowed.ReadValueAsync(child, ct);
StatusCode.IsGood(good.StatusCode).ShouldBeTrue();
good.WrappedValue.GetBoolean().ShouldBeTrue();
var refused = await Should.ThrowAsync(() => denied.ReadValueAsync(child, ct));
refused.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
// A3a: no local apply of a remote method — the condition stays unacknowledged (A3b dispatches to the origin).
var eventId = rig.Nm.FindImportedCondition(Connection, Key1)!.EventId!.Value;
await Should.ThrowAsync(() => allowed.CallAsync(new NodeId(id, ns), MethodIds.AcknowledgeableConditionType_Acknowledge,
ct, eventId, new LocalizedText("x")));
rig.Nm.FindImportedCondition(Connection, Key1)!.AckedState!.Id!.Value.ShouldBeFalse();
}
[Fact]
public async Task Disabling_the_primary_placement_mapping_moves_only_notifiers_and_SourceName_and_a_later_mapping_changes_no_NodeId()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-n4", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
var before = rig.Nm.FindImportedCondition(Connection, Key1)!;
var id = before.NodeId;
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue();
// The primary (dev1, map-a) disappears; only the mapping-B anchor placement remains.
f.Apply(Update(Key1, version: 4, active: true, acked: true, [f.BPlacement()], message: "moved"));
var after = rig.Nm.FindImportedCondition(Connection, Key1)!;
after.NodeId.ShouldBe(id, "ConditionId is keyed on (connection, condition_key) only");
ReferenceEquals(after, before).ShouldBeTrue("the same condition instance");
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("the old placement folder is unwired symmetrically");
rig.Nm.IsImportedNotifierWired(f.AnchorB).ShouldBeTrue();
after.SourceName!.Value.ShouldBe("Plant/remote-b/HR200");
// A second mapping opened later (adds placements back): no NodeId changes.
f.Apply(Update(Key1, version: 5, active: true, acked: true, [.. f.TwoPlacements(), f.BPlacement()], message: "added"));
rig.Nm.FindImportedCondition(Connection, Key1)!.NodeId.ShouldBe(id);
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue();
}
[Fact]
public async Task A_retired_placement_folder_is_unwired_and_a_folder_holding_an_event_item_is_not_retired()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-n7", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var item = AddItem(subscription, f.DeviceFolder);
await subscription.ApplyChangesAsync(ct);
var sink = (IProjectedNamespacePageSink)rig.Nm;
sink.TryRemove(f.DeviceFolder, f.DeviceDefinition).ShouldBeFalse("pinned by the admitted event item");
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue();
subscription.RemoveItem(item);
await subscription.ApplyChangesAsync(ct);
sink.TryRemove(f.DeviceFolder, f.DeviceDefinition).ShouldBeTrue();
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("retirement unwires the notifier");
}
[Fact]
public async Task A_resync_of_unchanged_state_reports_nothing_and_the_next_real_transition_arrives_exactly_once()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-resync", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
var reported = rig.Nm.ImportedEventsReported;
// A re-snapshot after a stream end re-states the same state under new versions (a new epoch): the shared delta gate
// suppresses it.
f.Apply(Update(Key1, version: 10, active: true, acked: false, f.TwoPlacements()));
f.Apply(Update(Key1, version: 11, active: true, acked: false, f.TwoPlacements()));
rig.Nm.ImportedEventsReported.ShouldBe(reported);
// Positive control: a real transition after it must arrive, once.
f.Apply(Update(Key1, version: 12, active: true, acked: true, f.TwoPlacements(), message: "real"));
await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "real"));
events.Of(server).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(1);
}
[Fact]
public async Task Staleness_is_BadNoCommunication_once_per_condition_and_never_known_inactive_and_unknown_records_change_nothing()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-stale", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
f.Apply(Update(Key2, version: 3, active: false, acked: true, f.TwoPlacements(), known: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
// T2: a state-unknown record never states "inactive" — the never-known condition is Uncertain, not Good.
rig.Nm.FindImportedCondition(Connection, Key2)!.Quality!.Value.Code.ShouldBe(StatusCodes.UncertainInitialValue.Code);
f.Apply(Update(Key1, version: 4, active: false, acked: true, f.TwoPlacements(), known: false));
rig.Nm.FindImportedCondition(Connection, Key1)!.ActiveState!.Id!.Value.ShouldBeTrue("an unknown record never changes the last state");
rig.Nm.MarkConnectionStale(Connection);
rig.Nm.MarkConnectionStale(Connection); // idempotent: the delta gate reports the Quality change once
f.Apply(Update(Key1, version: 5, active: true, acked: true, f.TwoPlacements(), message: "sentinel"));
await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "sentinel"));
var stale = events.Of(server).Where(e => e[QualityF].TryGetValue(out StatusCode q) && q.Code == StatusCodes.BadNoCommunication.Code).ToList();
stale.Count.ShouldBe(2, "one BadNoCommunication event per condition");
stale.ShouldContain(e => e[ActiveF].GetBoolean(), "the active condition stays active while stale");
}
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// Review round 1 (a3a-review-round1.md)
// ---------------------------------------------------------------------------------------------------------------------
private static bool IsRefreshRequired(ArrayOf e) => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshRequiredEventType;
[Fact]
public async Task B3_revalidation_keeps_an_admitted_folder_item_and_deleting_a_stood_down_item_releases_its_demand()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-reval", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var folder = AddItem(subscription, f.DeviceFolder);
await subscription.ApplyChangesAsync(ct);
f.Access.Outstanding.ShouldBe(1, "the admitted folder item opened demand");
rig.Nm.RevalidateMonitoredItems(); // the ACL timer tick / a deploy
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "after-revalidation"));
await Events.WaitUntilAsync(() => events.Of(folder).Any(e => Message(e) == "after-revalidation"));
// A revocation stands the item down; the client's later delete must still release the lease.
f.Access.Allowed.Clear();
Interlocked.Increment(ref f.Access.Generation);
rig.Nm.RevalidateMonitoredItems();
subscription.RemoveItem(folder);
await subscription.ApplyChangesAsync(ct);
f.Access.Outstanding.ShouldBe(0, "a stood-down item's delete releases its condition demand");
}
[Fact]
public async Task S1_a_full_rebuild_unwires_and_the_re_created_folder_is_promoted_and_delivers_again()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-rebuild", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue();
rig.Nm.RebuildAddressSpace();
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("the rebuild discarded the folder: its wiring goes with it");
f.Rematerialise(); // the same NodeIds, new FolderState instances
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var folder = AddItem(subscription, f.DeviceFolder);
await subscription.ApplyChangesAsync(ct);
(folder.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.Good.Code, "the new folder is an event notifier again");
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "after-rebuild"));
await Events.WaitUntilAsync(() => events.Of(folder).Any(e => Message(e) == "after-rebuild"));
}
[Fact]
public async Task Deviation3_a_folder_only_client_opens_demand_on_a_projected_folder_with_no_condition_wired_yet()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-folderdemand", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
rig.Nm.ImportedConditionCount.ShouldBe(0, "nothing materialised (after a restart or a linger)");
using var granted = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var events = new Events();
var grantedSub = await SubscribeAsync(granted, events, ct);
var deniedSub = await SubscribeAsync(denied, new Events(), ct);
var grantedItem = AddItem(grantedSub, f.AnchorB);
var deniedItem = AddItem(deniedSub, f.AnchorB);
await grantedSub.ApplyChangesAsync(ct);
await deniedSub.ApplyChangesAsync(ct);
(grantedItem.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.Good.Code);
deniedItem.Status.Error?.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code, "the mapping gate still decides");
f.Access.Outstanding.ShouldBe(1, "the folder-only client opened condition demand");
// The condition that demand brings in is delivered to that folder item.
f.Apply(Update(Key2, version: 3, active: true, acked: false, [f.BPlacement()], message: "arrived"));
await Events.WaitUntilAsync(() => events.Of(grantedItem).Any(e => Message(e) == "arrived"));
}
///
/// A4 F4: on a freshly restarted consumer the projected folders materialise before the mapping's authority is active, so
/// materialisation does not promote them. A folder-first event item once the authority IS active must still be admitted
/// (it opens the demand that brings the conditions in) — it was refused BadNotSupported by the SDK because nothing
/// re-promoted the folder.
///
[Fact]
public async Task F4_a_folder_materialised_before_its_mapping_was_condition_bearing_still_admits_a_folder_first_event_item()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a4-f4-folderfirst", encrypted: false, ct);
var access = new FakeConditionAccess { ConditionBearing = false };
access.Allowed.Add(Granted);
var f = Fixture.Install(rig, access);
using var granted = await rig.ConnectAsync(anonymous: false, ct);
// Control (the defect's precondition): while the mapping is not condition-bearing even a granted caller is refused — by
// the mapping gate, as the real one does (review r2 NIT: BadUserAccessDenied, not the SDK's BadNotSupported).
var early = await SubscribeAsync(granted, new Events(), ct);
var refused = AddItem(early, f.AnchorB);
await early.ApplyChangesAsync(ct);
(refused.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code, "not condition-bearing yet");
access.ConditionBearing = true; // the authority activates after materialisation (first barrier of a restarted consumer)
// Review r2 NIT, negative case: an UNGRANTED caller is refused by the mapping gate before any promotion — the folder's
// EventNotifier is unchanged, so a refusal cannot be used to flip (or probe) notifier state.
using var ungranted = await rig.ConnectAsync(anonymous: true, ct);
var before = EventNotifier(rig, f.AnchorB);
(before & EventNotifiers.SubscribeToEvents).ShouldBe((byte)0, "precondition: not yet promoted");
var deniedSub = await SubscribeAsync(ungranted, new Events(), ct);
var denied = AddItem(deniedSub, f.AnchorB);
await deniedSub.ApplyChangesAsync(ct);
denied.Status.Error?.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
(EventNotifier(rig, f.AnchorB)).ShouldBe(before, "an ungranted caller never promotes the folder");
access.Outstanding.ShouldBe(0, "a refused caller opens no condition demand");
var events = new Events();
var sub = await SubscribeAsync(granted, events, ct);
var item = AddItem(sub, f.AnchorB);
await sub.ApplyChangesAsync(ct);
(item.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.Good.Code, "folder-first item admitted");
access.Outstanding.ShouldBe(1, "the folder-only client opened condition demand");
(EventNotifier(rig, f.AnchorB) & EventNotifiers.SubscribeToEvents).ShouldNotBe((byte)0,
"positive control: the granted caller's admission promoted it");
f.Apply(Update(Key2, version: 3, active: true, acked: false, [f.BPlacement()], message: "arrived-f4"));
await Events.WaitUntilAsync(() => events.Of(item).Any(e => Message(e) == "arrived-f4"));
static byte EventNotifier(ServerEventRig rig, NodeId folder) => rig.Nm.ProjectedFolderEventNotifier(folder).ShouldNotBeNull();
}
[Fact]
public async Task Deviation6_removing_an_imported_condition_sends_RefreshRequired_only_to_the_items_that_could_see_it()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-remove", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
var device = AddItem(subscription, f.DeviceFolder);
var other = AddItem(subscription, f.AnchorB); // map-b: Key1 is never wired here
await subscription.ApplyChangesAsync(ct);
var before = rig.Nm.ImportedRefreshRequiredQueued;
rig.Nm.RemoveConditions(Connection, [Key1]);
rig.Nm.ImportedConditionCount.ShouldBe(0);
await Events.WaitUntilAsync(() => events.Of(server).Any(IsRefreshRequired) && events.Of(device).Any(IsRefreshRequired));
(rig.Nm.ImportedRefreshRequiredQueued - before).ShouldBe(2, "one per item that held it");
// Must-arrive control on the map-b item, queued AFTER the removal.
f.Apply(Update(Key2, version: 3, active: true, acked: false, [f.BPlacement()], message: "control"));
await Events.WaitUntilAsync(() => events.Of(other).Any(e => Message(e) == "control"));
events.Of(other).Any(IsRefreshRequired).ShouldBeFalse("an item that never saw the removed condition is not told to refresh");
}
[Fact]
public async Task Deviation8_ConditionRefresh_replays_hundreds_of_imported_conditions_in_chunks_between_RefreshStart_and_RefreshEnd()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-replay", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
const int count = 300; // > 2 × the 128-condition chunk
rig.Nm.ApplyConditions(Enumerable.Range(0, count)
.Select(i => Update(KeyOf("bulk-" + i), version: 3, active: true, acked: false, f.TwoPlacements(), message: "bulk")).ToList());
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
await subscription.ConditionRefreshAsync(ct);
await Events.WaitUntilAsync(() => events.Of(server).Any(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType));
var list = events.Of(server).ToList();
var startAt = list.FindIndex(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshStartEventType);
var endAt = list.FindIndex(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType);
list.Skip(startAt + 1).Take(endAt - startAt - 1).Count(e => Message(e) == "bulk")
.ShouldBe(count, "every retained imported condition once, inside the refresh bracket");
}
private static string KeyOf(string seed) =>
Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static ImportedConditionUpdate Update(string key, long version, bool active, bool acked,
IReadOnlyList placements, string message = "HR200 high", bool known = true)
{
var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", "HR200", DataConditionSourceKind.Native,
placements.Select(p => p.Placement).ToArray(), (uint)DataConditionMethodSets.Native);
var state = new DataConditionState(key, version, false, known, info, active, acked, true, true, 0, 777, message,
StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, active || !acked, new DataActivationMarker("inc", 1));
var sourceName = (placements[0].MappingId == MappingA ? "Plant/remote-a/" : "Plant/remote-b/") + placements[0].RelativePath;
return new ImportedConditionUpdate(Connection, state, info, placements, sourceName);
}
private static string? Message(ArrayOf e) => e[MessageF].GetLocalizedText().Text;
private static async Task SubscribeAsync(ISession session, Events events, CancellationToken ct)
{
var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 };
subscription.FastEventCallback = events.OnEvents;
session.AddSubscription(subscription);
await subscription.CreateAsync(ct);
return subscription;
}
private static SdkMonitoredItem AddItem(Subscription subscription, NodeId source)
{
var filter = new EventFilter();
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.EventId));
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.SourceNode));
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.SourceName));
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Message));
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Severity));
filter.AddSelectClause(ObjectTypeIds.ConditionType, QualifiedName.From(BrowseNames.ConditionName));
filter.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AlarmConditionType,
[QualifiedName.From(BrowseNames.ActiveState), QualifiedName.From(BrowseNames.Id)]);
filter.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AcknowledgeableConditionType,
[QualifiedName.From(BrowseNames.AckedState), QualifiedName.From(BrowseNames.Id)]);
filter.AddSelectClause(ObjectTypeIds.ConditionType, QualifiedName.From(BrowseNames.Quality));
filter.SelectClauses += new SimpleAttributeOperand { TypeDefinitionId = ObjectTypeIds.ConditionType, AttributeId = Attributes.NodeId };
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.EventType));
var item = new SdkMonitoredItem(subscription.DefaultItem)
{
StartNodeId = source, AttributeId = Attributes.EventNotifier, Filter = filter, QueueSize = 1000, SamplingInterval = 0,
};
subscription.AddItem(item);
return item;
}
private sealed class Events
{
private readonly object _gate = new();
private readonly List<(uint Handle, ArrayOf Fields)> _events = [];
public void OnEvents(Subscription subscription, EventNotificationList notification, ArrayOf stringTable)
{
lock (_gate) foreach (var e in notification.Events) _events.Add((e.ClientHandle, e.EventFields));
}
public IReadOnlyList> Of(SdkMonitoredItem item)
{
lock (_gate) return _events.Where(e => e.Handle == item.ClientHandle).Select(e => e.Fields).ToList();
}
public static Task WaitUntilAsync(Func condition) => RecordedEvents.WaitUntilAsync(condition);
}
/// The fake §5.4 gate: a principal set (ACL enforcement stays OFF in the rig).
internal sealed class FakeConditionAccess : IProjectedConditionAccess
{
public HashSet Allowed { get; } = new(StringComparer.Ordinal);
public int Demands;
public long Generation = 1;
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) =>
caller is not null && Allowed.Contains(caller.Principal);
public long AuthorityGeneration => Interlocked.Read(ref Generation);
/// Review r2 NIT: like the real mapping gate, a mapping that is not condition-bearing admits nobody.
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) =>
caller is not null && ConditionBearing && Allowed.Contains(caller.Principal);
/// A4 F4: false models a mapping whose authority was not yet active when its folders materialised.
public volatile bool ConditionBearing = true;
public bool IsConditionBearingMapping(string mappingId) => ConditionBearing;
/// Leases currently held (acquired minus released).
public int Outstanding;
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller)
{
Interlocked.Increment(ref Demands);
Interlocked.Increment(ref Outstanding);
return new Lease(this);
}
private sealed class Lease(FakeConditionAccess owner) : IDisposable
{
private int _disposed;
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) Interlocked.Decrement(ref owner.Outstanding); }
}
}
/// A local parent, two mapping anchors (map-a, map-b) and one projected device folder under map-a.
private sealed class Fixture
{
public required ServerEventRig Rig { get; init; }
public required FakeConditionAccess Access { get; init; }
public required NodeId Anchor { get; init; }
public required NodeId AnchorB { get; init; }
public required NodeId DeviceFolder { get; init; }
public required ProjectedVariableDefinition DeviceDefinition { get; init; }
public static Fixture Install(ServerEventRig rig, string grantedPrincipal)
{
var access = new FakeConditionAccess();
access.Allowed.Add(grantedPrincipal);
return Install(rig, access);
}
public static Fixture Install(ServerEventRig rig, FakeConditionAccess access)
{
rig.Nm.ProjectedConditionAccess = access; // bound before projections materialise, as the host does
var (anchor, anchorB, device, definition) = Materialise(rig.Nm);
return new Fixture { Rig = rig, Access = access, Anchor = anchor, AnchorB = anchorB, DeviceFolder = device, DeviceDefinition = definition };
}
/// Re-creates the same projected folders (new instances, same NodeIds) — e.g. after a full rebuild.
public void Rematerialise() => Materialise(Rig.Nm);
private static (NodeId Anchor, NodeId AnchorB, NodeId Device, ProjectedVariableDefinition Definition) Materialise(OtOpcUaNodeManager nm)
{
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var rootA = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant");
var rootB = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Other");
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, rootA), parent,
"remote-a", "Plant/remote-a", MappingA, 1, () => true), out var anchor).ShouldBeTrue();
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingB, rootB), parent,
"remote-b", "Plant/remote-b", MappingB, 1, () => true), out var anchorB).ShouldBeTrue();
var devAddress = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1");
var metadata = new DataMetadata(new DataView(devAddress, DataRealm.Raw, MappingA, 1, "Plant/remote-a/dev1"), "dev1", "Folder",
DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false);
var definition = new ProjectedVariableDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, devAddress), anchor!.Value,
metadata, 1, () => true);
nm.TryEnsureProjectedVariable(definition, out var device).ShouldBeTrue();
return (anchor.Value, anchorB!.Value, device!.Value, definition);
}
/// Primary: the raw tag under dev1 (map-a); second: the same condition listed directly under the map-a root.
public IReadOnlyList TwoPlacements() =>
[
new(MappingA, DataRealm.Raw, View("Plant/dev1/HR200"), "Plant/remote-a/dev1", "dev1/HR200"),
new(MappingA, DataRealm.Raw, View("Plant/HR200"), "Plant/remote-a", "HR200"),
];
public ImportedConditionPlacement BPlacement() =>
new(MappingB, DataRealm.Raw, View("Other/HR200"), "Plant/remote-b", "HR200");
private static DataView View(string path) =>
new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path);
public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]);
}
}
///
/// Review r1 (test adequacy): A3-SEC with the DELIVERY gate isolated — on the denied path nothing is queued at all, so the
/// publish-time marker re-check (the second layer) has nothing to drop: ProjectedEventFieldList.DroppedOnPublish
/// does not move. Non-parallel: the counter is process-wide.
///
[Collection(ImportedDeliveryGateCollection.Name)]
[Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class ImportedConditionDeliveryGateTests
{
[Fact]
public async Task A3_SEC_the_delivery_gate_alone_withholds_a_denied_sessions_event_nothing_is_dropped_on_publish()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-gate", encrypted: false, ct);
var nm = rig.Nm;
var access = new ImportedConditionEventWireTests.FakeConditionAccess();
access.Allowed.Add(ServerEventRig.KeyPrincipal);
nm.ProjectedConditionAccess = access;
using var allowed = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var received = new System.Collections.Concurrent.ConcurrentBag<(string Who, uint Handle, string? Message)>();
async Task Subscribe(ISession session, string who)
{
var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 };
subscription.FastEventCallback = (_, n, _) =>
{
foreach (var e in n.Events)
received.Add((who, e.ClientHandle, e.EventFields[0].TryGetValue(out LocalizedText text) ? text.Text : null));
};
session.AddSubscription(subscription);
await subscription.CreateAsync(ct);
var filter = new EventFilter();
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Message));
subscription.AddItem(new SdkMonitoredItem(subscription.DefaultItem)
{ StartNodeId = ObjectIds.Server, AttributeId = Attributes.EventNotifier, Filter = filter, QueueSize = 1000, SamplingInterval = 0 });
await subscription.ApplyChangesAsync(ct);
return subscription;
}
await Subscribe(allowed, "allowed");
var deniedSub = await Subscribe(denied, "denied");
var dropped = ProjectedEventFieldList.DroppedOnPublish;
var key = Convert.ToBase64String(SHA256.HashData("gate"u8.ToArray())).TrimEnd('=').Replace('+', '-').Replace('/', '_');
var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR"), DataRealm.Raw, null, 0, "Plant/dev1/HR");
var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, view, "Plant/remote-a/dev1", "dev1/HR");
var info = new DataConditionInfo("AlarmConditionType", "HR", DataConditionSourceKind.Native, [view], 3);
var state = new DataConditionState(key, 1, false, true, info, true, false, true, true, 0, 500, "gated", 0, null, 0,
DateTimeOffset.UtcNow, true, new DataActivationMarker("i", 1));
nm.ApplyConditions([new ImportedConditionUpdate("conn-a", state, info, [placement], "Plant/remote-a/dev1/HR")]);
await RecordedEvents.WaitUntilAsync(() => received.Any(r => r.Who == "allowed" && r.Message == "gated")); // positive control
await deniedSub.ConditionRefreshAsync(ct); // must-arrive on the denied session: its own RefreshStart/End
await RecordedEvents.WaitUntilAsync(() => received.Count(r => r.Who == "denied") >= 2);
received.ShouldNotContain(r => r.Who == "denied" && r.Message == "gated");
(ProjectedEventFieldList.DroppedOnPublish - dropped).ShouldBe(0, "the delivery gate withheld it; nothing reached the publish-time drop");
}
}
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class ImportedDeliveryGateCollection
{
public const string Name = "Imported delivery gate (process-wide counter)";
}