6bdca132fe
Adds the ProjectedFolderEventNotifier test observation. Co-Authored-By: Claude <noreply@anthropic.com>
754 lines
50 KiB
C#
754 lines
50 KiB
C#
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;
|
||
|
||
/// <summary>
|
||
/// A3b over the wire (plan §5.6): Part 9 methods on an imported condition are claimed by the node manager's
|
||
/// <see cref="ICallAsyncNodeManager"/> implementation and dispatched to the origin through the
|
||
/// <see cref="IProjectedConditionMethods"/> port — never under the node manager's <c>Lock</c>, 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).
|
||
/// </summary>
|
||
[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));
|
||
_ = refresh; // review S6: the RefreshRequired itself is pinned over the wire by A_resync_that_cannot_re_bind_…
|
||
}
|
||
|
||
/// <summary>
|
||
/// A4 review r2 NIT (F1 EventId retention across a held-set takeover, previously only live-gated by A03): the consumer
|
||
/// holds its conditions across its own deploy and the next runner re-snapshots ONTO the same nodes. What reaches the
|
||
/// node manager is a restart of the stream's versions with the same marker — and, after an origin reload restatement
|
||
/// (#935), a new record time. The condition instance, its current EventId and every older still-retained EventId stay
|
||
/// bound, no event is reported; the takeover's RefreshRequired is not a condition event either.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task R2_a_takeover_re_snapshot_with_the_same_marker_keeps_the_instance_and_every_retained_EventId()
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await ServerEventRig.StartAsync("a4-r2-takeover", 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, message: "first"));
|
||
var older = f.CurrentEventId();
|
||
f.Apply(Update(version: 4, active: true, acked: false, time: t0.AddSeconds(1), message: "second"));
|
||
var current = f.CurrentEventId();
|
||
current.ShouldNotBe(older, "positive control: a real transition mints a new EventId");
|
||
var instance = rig.Nm.FindImportedCondition(Connection, Key1);
|
||
var reported = rig.Nm.ImportedEventsReported;
|
||
|
||
// The takeover runner's first snapshot: versions restart (new stream), same marker, a restated (newer) record time.
|
||
f.Apply(Update(version: 1, active: true, acked: false, time: t0.AddSeconds(30), message: "second"));
|
||
rig.Nm.RequireRefresh(Connection);
|
||
ReferenceEquals(rig.Nm.FindImportedCondition(Connection, Key1), instance).ShouldBeTrue("the same condition object — not removed and re-created");
|
||
f.CurrentEventId().ShouldBe(current, "no event, no new EventId");
|
||
rig.Nm.ImportedEventsReported.ShouldBe(reported, "an unchanged occurrence reports nothing");
|
||
|
||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||
var id = f.ConditionId(session);
|
||
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, older, "older", ct)).ShouldBe(StatusCodes.Good);
|
||
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, current, "current", ct)).ShouldBe(StatusCodes.Good);
|
||
f.Port.Calls.Count.ShouldBe(2);
|
||
f.Port.Calls.ShouldAllBe(c => c.ExpectedActivation == Marker1);
|
||
}
|
||
|
||
/// <summary>
|
||
/// §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 <c>Lock</c> is free, and no acknowledged state is
|
||
/// observable before the origin's record (positive control: it arrives after release).
|
||
/// </summary>
|
||
/// <param name="realPath">
|
||
/// Review S5: false = the stall sits at the consumer's port (the original measurement); true = behind a REAL
|
||
/// <c>ProjectedConditionAccess</c> + lease + <c>GrpcDataConnection</c>, the in-process origin's handler stalling 5 s.
|
||
/// </param>
|
||
[Theory]
|
||
[InlineData(false)]
|
||
[InlineData(true)]
|
||
public async Task Lock_freedom_a_5s_stalled_origin_method_delays_no_Read_Browse_or_data_Publish_and_applies_nothing_before_the_record(bool realPath)
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await ServerEventRig.StartAsync("a3b-l3", encrypted: false, ct);
|
||
var f = Fixture.Install(rig);
|
||
await using var real = realPath ? new RealConditionMethodPath(Connection, MappingA, f.Port, TimeSpan.FromSeconds(5)) : null;
|
||
if (real is not null)
|
||
{
|
||
rig.Nm.ProjectedConditionMethods = real.Port;
|
||
// The condition stream is open (its serving incarnation addresses the call) before anything is measured.
|
||
await WaitUntilAsync(() => real.Access.CallAsync(new ImportedConditionMethodCall(Connection, Key1, Fixture.DefaultPlacements[0],
|
||
DataConditionMethods.Acknowledge, Marker1, null, "probe", TimeSpan.Zero, null), ct).Result.StatusCode != 0x80310000u);
|
||
}
|
||
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<double, long>();
|
||
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(() => real is null ? f.Port.Calls.Count == 1 : Volatile.Read(ref real.Server.MethodCalls) == 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);
|
||
if (real is not null) Volatile.Read(ref real.Server.MethodAnswers).ShouldBe(1, "the origin's stalled handler answered once, after the stall");
|
||
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 ({(realPath ? "real ProjectedConditionAccess + GrpcDataConnection" : "port")}): 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) { Volatile.Write(ref 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");
|
||
// Review N1: the port's call is cancelled explicitly on the timeout (it used to rely on a timer sharing WaitAsync's due
|
||
// time, disposed unfired when WaitAsync won).
|
||
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);
|
||
// Review S2: the transport's KNOWN timeout passes through (it used to be inferred from the consumer's own clock, so a
|
||
// deadline the transport hit before the consumer's budget elapsed read as BadCommunicationError).
|
||
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, "deadline"));
|
||
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadTimeout);
|
||
// Review S3: a definite failure at the origin is the origin's status, not "unknown".
|
||
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.DriverConfirmedFailure, StatusCodes.BadConditionAlreadyEnabled.Code, "refused"));
|
||
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadConditionAlreadyEnabled);
|
||
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");
|
||
}
|
||
|
||
/// <summary>
|
||
/// A3b review S6 (non-vacuous RefreshRequired) + N2: a same-incarnation marker move at an unchanged time is a NEW
|
||
/// occurrence — not re-bound; the old EventId is unknown, a fresh one is ackable, and a subscriber that can see the
|
||
/// condition receives RefreshRequired over the wire.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task A_resync_that_cannot_re_bind_sends_RefreshRequired_to_a_subscriber_and_a_same_incarnation_bump_is_not_re_bound()
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await ServerEventRig.StartAsync("a3b-refreshreq", 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 events = new RecordedEvents();
|
||
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
|
||
var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
|
||
await subscription.ApplyChangesAsync(ct);
|
||
var id = f.ConditionId(session);
|
||
var before = f.CurrentEventId();
|
||
events.HasType(serverItem, ObjectTypeIds.RefreshRequiredEventType).ShouldBeFalse();
|
||
|
||
// Same incarnation, sequence bumped, same time and state: by the origin's definition a new occurrence (review N2).
|
||
f.Apply(Update(version: 4, active: true, acked: false, time: t0, marker: new DataActivationMarker(Marker1.Incarnation, 2)));
|
||
await RecordedEvents.WaitUntilAsync(() => events.HasType(serverItem, ObjectTypeIds.RefreshRequiredEventType));
|
||
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown);
|
||
var fresh = f.CurrentEventId();
|
||
fresh.ShouldNotBe(before);
|
||
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, fresh, "x", ct)).ShouldBe(StatusCodes.Good);
|
||
f.Port.Calls.Single().ExpectedActivation.ShouldBe(new DataActivationMarker(Marker1.Incarnation, 2));
|
||
}
|
||
|
||
/// <summary>Review N3: a record that first carries a marker (the previous one had none) binds a fresh, ackable EventId.</summary>
|
||
[Fact]
|
||
public async Task A_marker_appearing_on_an_unchanged_state_mints_an_ackable_EventId()
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await ServerEventRig.StartAsync("a3b-nullmarker", 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, noMarker: true));
|
||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||
var id = f.ConditionId(session);
|
||
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
|
||
.ShouldBe(StatusCodes.BadEventIdUnknown, "no marker: nothing to address the origin's occurrence with");
|
||
|
||
f.Apply(Update(version: 4, active: true, acked: false, time: t0));
|
||
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good);
|
||
f.Port.Calls.Single().ExpectedActivation.ShouldBe(Marker1);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Review S6: the native-Confirm guard and the supported-methods guard, each isolated — a native condition whose listing
|
||
/// DOES carry Confirm is still refused; a scripted one whose listing lacks it is refused; a scripted one with it dispatches.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task Native_Confirm_is_refused_even_when_listed_and_a_scripted_Confirm_follows_the_listing()
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await ServerEventRig.StartAsync("a3b-confirm", encrypted: false, ct);
|
||
var f = Fixture.Install(rig);
|
||
var native = KeyOf("native-listed"); var scriptedNo = KeyOf("scripted-no"); var scriptedYes = KeyOf("scripted-yes");
|
||
var all = (uint)DataConditionMethodSets.All;
|
||
f.Apply(Update(version: 3, active: true, acked: true, key: native, methods: all));
|
||
f.Apply(Update(version: 3, active: true, acked: true, native: false, key: scriptedNo,
|
||
methods: (uint)(DataConditionMethods.Acknowledge | DataConditionMethods.AddComment)));
|
||
f.Apply(Update(version: 3, active: true, acked: true, native: false, key: scriptedYes, methods: all));
|
||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||
|
||
(await CallAsync(session, f.ConditionId(session, key: native), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: native), "c", ct))
|
||
.ShouldBe(StatusCodes.BadNotSupported, "native: no upstream confirm path, whatever the listing says");
|
||
(await CallAsync(session, f.ConditionId(session, key: scriptedNo), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: scriptedNo), "c", ct))
|
||
.ShouldBe(StatusCodes.BadNotSupported, "the origin's supported_methods lacks Confirm");
|
||
f.Port.Calls.ShouldBeEmpty();
|
||
(await CallAsync(session, f.ConditionId(session, key: scriptedYes), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: scriptedYes), "c", ct))
|
||
.ShouldBe(StatusCodes.Good);
|
||
f.Port.Calls.Single().Method.ShouldBe(DataConditionMethods.Confirm);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Review S1 + S6: a fault BEFORE dispatch (the gate throws) is that item's <c>BadInternalError</c>, unsent — the batch
|
||
/// still answers and a local item after the imported one is applied and Good (imported-first ordering); a batch
|
||
/// carrying a pre-validation failure answers it per item while its imported call dispatches; a port that THROWS after
|
||
/// dispatch is OutcomeUnknown (<c>BadCommunicationError</c>), dispatched once.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task A_fault_before_dispatch_is_a_per_item_BadInternalError_and_the_rest_of_the_batch_still_answers()
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await ServerEventRig.StartAsync("a3b-fault", 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");
|
||
|
||
f.Port.AuthorizeThrows = true;
|
||
var response = await session.CallAsync(null,
|
||
[
|
||
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
|
||
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] },
|
||
new CallMethodRequest { ObjectId = ServerEventRig.ConditionNodeId(session, native: true), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
|
||
InputArguments = [new Variant(ByteString.From(localEventId)), new Variant(new LocalizedText("local ack"))] },
|
||
], ct);
|
||
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInternalError.Code, "the imported item faulted before dispatch");
|
||
response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the local item after it was applied and answers");
|
||
Volatile.Read(ref routed).ShouldBe(1);
|
||
f.Port.Calls.ShouldBeEmpty("nothing was sent");
|
||
|
||
// A pre-validation failure in the same batch as a good imported call: answered per item, the imported one dispatched.
|
||
f.Port.AuthorizeThrows = false;
|
||
response = await session.CallAsync(null,
|
||
[
|
||
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = NodeId.Null },
|
||
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
|
||
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] },
|
||
], ct);
|
||
StatusCode.IsBad(response.Results[0].StatusCode).ShouldBeTrue();
|
||
response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
|
||
f.Port.Calls.Count.ShouldBe(1);
|
||
|
||
// A port that throws after dispatch: OutcomeUnknown, never retried.
|
||
f.Port.Handler = (_, _) => throw new InvalidOperationException("port fault");
|
||
(await CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), "n", ct))
|
||
.ShouldBe(StatusCodes.BadCommunicationError);
|
||
f.Port.Calls.Count.ShouldBe(2);
|
||
f.Acked().ShouldBeFalse();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Review S4: one stalled connection holds at most its sub-limit (4) of the node's 8 slots — a call to another connection
|
||
/// still dispatches at once; the stalled connection's further calls wait out their budget and answer
|
||
/// <c>BadTooManyOperations</c> unsent (slot exhaustion).
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task One_stalled_connection_cannot_starve_another_and_its_excess_calls_are_BadTooManyOperations_unsent()
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await ServerEventRig.StartAsync("a3b-slots", encrypted: false, ct);
|
||
var f = Fixture.Install(rig);
|
||
const string other = "conn-b";
|
||
f.Apply(Update(version: 3, active: true, acked: false));
|
||
f.Apply(Update(version: 3, active: true, acked: false, connection: other));
|
||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||
f.Port.Timeout = TimeSpan.FromSeconds(3);
|
||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
f.Port.Handler = async (call, token) =>
|
||
{
|
||
if (call.ConnectionId == Connection) await release.Task.WaitAsync(token);
|
||
return Applied();
|
||
};
|
||
var stalled = Enumerable.Range(0, OtOpcUaNodeManager.DefaultImportedMethodConcurrency)
|
||
.Select(i => CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), $"c{i}", ct)).ToArray();
|
||
await WaitUntilAsync(() => f.Port.Calls.Count == OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection);
|
||
|
||
var sw = Stopwatch.StartNew();
|
||
(await CallAsync(session, f.ConditionId(session, other), MethodIds.ConditionType_AddComment, f.CurrentEventId(other), "b", ct))
|
||
.ShouldBe(StatusCodes.Good, "a healthy origin is not starved by a stalled one");
|
||
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(1.5));
|
||
|
||
var outcomes = await Task.WhenAll(stalled);
|
||
outcomes.Count(o => o == StatusCodes.BadTooManyOperations).ShouldBe(
|
||
OtOpcUaNodeManager.DefaultImportedMethodConcurrency - OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection);
|
||
outcomes.Count(o => o == StatusCodes.BadTimeout).ShouldBe(OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection);
|
||
f.Port.Calls.Count(c => c.ConnectionId == Connection).ShouldBe(OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection,
|
||
"the excess calls never dispatched");
|
||
release.SetResult();
|
||
}
|
||
|
||
/// <summary>Review S4 floor: a request whose own deadline leaves less than the minimum dispatch budget is BadTimeout, unsent.</summary>
|
||
[Fact]
|
||
public async Task A_request_deadline_below_the_dispatch_floor_is_BadTimeout_unsent()
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await ServerEventRig.StartAsync("a3b-floor", 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 response = await session.CallAsync(new RequestHeader { TimeoutHint = 450 },
|
||
[new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
|
||
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("x"))] }], ct);
|
||
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
|
||
f.Port.Calls.ShouldBeEmpty("450 ms − 250 ms grace leaves less than the 250 ms floor: refused before dispatch");
|
||
|
||
// Positive control: a roomy deadline dispatches, and the port's budget ends before the client's TimeoutHint (N7).
|
||
response = await session.CallAsync(new RequestHeader { TimeoutHint = 2_000 },
|
||
[new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
|
||
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("x"))] }], ct);
|
||
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
|
||
f.Port.Calls.Single().RemainingBudget.ShouldBeLessThanOrEqualTo(TimeSpan.FromMilliseconds(2_000) - OtOpcUaNodeManager.ImportedMethodGrace);
|
||
}
|
||
|
||
/// <summary>Review S6: a Warm standby refuses an imported method locally (<c>BadInvalidState</c>), nothing sent.</summary>
|
||
[Fact]
|
||
public async Task A_warm_standby_refuses_an_imported_method_unsent()
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await WarmRedundancyWireTests.StartModeAsync("a3b-standby", "Warm", ct);
|
||
var f = Fixture.Install(rig);
|
||
f.Apply(Update(version: 3, active: true, acked: false));
|
||
var projection = rig.Server.CreateStandbyProjection()!;
|
||
WarmRedundancyWireTests.Demote(projection);
|
||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||
(await CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
|
||
.ShouldBe(StatusCodes.BadInvalidState);
|
||
f.Port.Calls.ShouldBeEmpty();
|
||
WarmRedundancyWireTests.Promote(projection);
|
||
(await CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
|
||
.ShouldBe(StatusCodes.Good);
|
||
}
|
||
|
||
/// <summary>Review S6: identical calls from DIFFERENT principals never join — each is its own dispatch.</summary>
|
||
[Fact]
|
||
public async Task Identical_calls_from_different_principals_do_not_join()
|
||
{
|
||
var ct = TestContext.Current.CancellationToken;
|
||
await using var rig = await ServerEventRig.StartAsync("a3b-nojoin", encrypted: false, ct);
|
||
var f = Fixture.Install(rig);
|
||
f.Port.Granted.Add("anonymous");
|
||
f.Apply(Update(version: 3, active: true, acked: false));
|
||
using var keyed = await rig.ConnectAsync(anonymous: false, ct);
|
||
using var anonymous = await rig.ConnectAsync(anonymous: true, ct);
|
||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
f.Port.Handler = async (_, _) => { await release.Task; return Applied(); };
|
||
var eventId = f.CurrentEventId();
|
||
var a = CallAsync(keyed, f.ConditionId(keyed), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "same", ct);
|
||
var b = CallAsync(anonymous, f.ConditionId(anonymous), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "same", ct);
|
||
await WaitUntilAsync(() => f.Port.Calls.Count == 2);
|
||
rig.Nm.ImportedMethodsJoined.ShouldBe(0);
|
||
release.SetResult();
|
||
(await a).ShouldBe(StatusCodes.Good);
|
||
(await b).ShouldBe(StatusCodes.Good);
|
||
f.Port.Calls.Select(c => c.OnBehalfOf).Order().ShouldBe(new[] { "anonymous", Granted }.Order());
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
|
||
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, string connection = Connection, string? key = null,
|
||
uint? methods = null, bool noMarker = false)
|
||
{
|
||
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(),
|
||
methods ?? (uint)(native ? DataConditionMethodSets.Native : DataConditionMethodSets.Scripted));
|
||
var state = new DataConditionState(key ?? Key1, version, false, true, info, active, acked, true, true, 0, 777, message,
|
||
StatusCodes.Good.Code, null, 0, time ?? DateTimeOffset.UtcNow, active || !acked, noMarker ? null : marker ?? Marker1);
|
||
return new ImportedConditionUpdate(connection, state, info, placements, "Plant/remote-a/" + placements[0].RelativePath);
|
||
}
|
||
|
||
/// <summary>Calls one method and returns its status (never throws for a Bad result).</summary>
|
||
private static async Task<StatusCode> 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<bool> 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);
|
||
}
|
||
}
|
||
|
||
/// <summary>The fake origin port: a per-principal, per-method gate and a scriptable handler that records each dispatch.</summary>
|
||
internal sealed class FakePort : IProjectedConditionMethods
|
||
{
|
||
public HashSet<string> 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<ImportedConditionMethodCall> Calls { get; } = new();
|
||
/// <summary>The gate throws (an unexpected fault BEFORE dispatch — review S1).</summary>
|
||
public bool AuthorizeThrows { get; set; }
|
||
public Func<ImportedConditionMethodCall, CancellationToken, Task<DataConditionMethodResult>> Handler { get; set; } =
|
||
(_, _) => Task.FromResult(Applied());
|
||
|
||
public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements,
|
||
DataConditionMethods method)
|
||
{
|
||
AuthorizedFor.Enqueue((caller?.Principal ?? "", method));
|
||
if (AuthorizeThrows) throw new InvalidOperationException("gate fault");
|
||
return caller is not null && Granted.Contains(caller.Principal) && (GrantedMethods & method) == method
|
||
? new ImportedConditionMethodRoute(placements[0], Timeout) : null;
|
||
}
|
||
|
||
public Task<DataConditionMethodResult> 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<ImportedConditionPlacement> DefaultPlacements { get; } =
|
||
[
|
||
new(MappingA, DataRealm.Raw, View("Plant/dev1/HR200"), "Plant/remote-a", "dev1/HR200"),
|
||
];
|
||
|
||
public IReadOnlyList<ImportedConditionPlacement> 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, string connection = Connection, string? key = null) =>
|
||
new(ImportedConditionIds.Identifier(connection, key ?? Key1), (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri));
|
||
|
||
public ByteString CurrentEventId(string connection = Connection, string? key = null) =>
|
||
Rig.Nm.FindImportedCondition(connection, key ?? Key1)!.EventId!.Value;
|
||
|
||
public bool Acked(string connection = Connection, string? key = null) =>
|
||
Rig.Nm.FindImportedCondition(connection, key ?? 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);
|
||
}
|
||
}
|