Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaAlarmLastStateTests.cs
T
Joseph Doherty a2e9d71824 feat(dcl): move the OPC UA client to OPC Foundation SDK 2.0.1 (#125)
OPCFoundation.NetStandard.Opc.Ua.Client and the test-only .Server move
1.5.378.182 -> 2.0.1, the version OtOpcUa master runs (lmxopcua#782; #799
and #801 closed). Transitive Core/Core.Types/Types/Configuration/
Security.Certificates resolve to 2.0.1.

API breaks fixed in the DCL adapter:
- Built-in types are immutable structs (Variant, DataValue, NodeId,
  LocalizedText, StatusCode, ArrayOf<T>). New OpcUaValueBoundary restores
  the SDK 1.5 CLR shapes for every read, subscription and alarm-event
  value (byte[], UTC DateTime with no-timestamp = MinValue, Guid,
  detached arrays) and builds write variants with SDK 1.5's
  new Variant(object) semantics (byte[] = ByteString scalar).
- StatusCodes members are no longer constants: switches/patterns over
  them (verify-outcome mapping, connection-level classification,
  BadResourceUnavailable) match by value.
- CertificateIdentifier no longer caches a certificate and the
  CertificateValidator/CertificateValidation event is gone: the
  configuration's CertificateManager owns trust lists and the loaded
  application certificate and is disposed with the session; auto-accept
  and the verify probe's capture-and-reject use AcceptError.
- new UserIdentity(X509Certificate2) is gone: X509 user identities use
  X509IdentityTokenHandler with an on-demand PFX provider (still fails
  fast on a missing file/key).
- DefaultSessionFactory takes the telemetry context; collections are
  ArrayOf<T>; EventFilter select clauses and ContentFilter operands are
  built immutably.

UserName identity (lmxopcua#880): SDK 2's default handler sends a
password over 64 bytes - every 65-character OtOpcUa API key - as an
RsaEncryptedSecret that SDK 1.5 servers reject with BadIdentityTokenInvalid
and SDK 2 servers accept only within a 5-minute clock window (#873). The
DCL now always uses LegacyRsaUserNameIdentityTokenHandler (ported from
OtOpcUa be28aa44), i.e. exactly what it sent on SDK 1.5, so it logs in to
both server generations during a mixed rollout.

Tests: the in-process secured test server is ported to SDK 2 and can
admit an API key; new tests cover the handler (mutation-checked: 5 of 7
fail with the SDK default handler), the value boundary, and a 65-char key
end to end over None/Sign/SignAndEncrypt with a wrong key reaching the
key check (BadIdentityTokenRejected).

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-12 22:20:53 -05:00

90 lines
4.1 KiB
C#

using System.Collections.Concurrent;
using System.Reflection;
using Opc.Ua;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters;
/// <summary>
/// Review 2026-10-21 02/L3: the per-condition (active, acked) memory behind
/// <c>DeriveKind</c> must not grow for the life of a session. A condition that returns to
/// inactive + acknowledged is indistinguishable from one never seen (the default prior state), so
/// its key is dropped — otherwise a server whose condition names carry a per-occurrence component
/// (batch, lot, counter) adds a key per occurrence until the next reconnect.
/// </summary>
public class RealOpcUaAlarmLastStateTests
{
private const string Handle = "h1";
private static readonly MethodInfo Handler =
typeof(RealOpcUaClient).GetMethod("HandleAlarmEvent", BindingFlags.Instance | BindingFlags.NonPublic)!;
private static Dictionary<string, (bool Active, bool Acked)> SeedLastState(RealOpcUaClient client)
{
var field = typeof(RealOpcUaClient).GetField("_alarmLastState", BindingFlags.Instance | BindingFlags.NonPublic)!;
var map = (ConcurrentDictionary<string, Dictionary<string, (bool Active, bool Acked)>>)field.GetValue(client)!;
var perHandle = new Dictionary<string, (bool Active, bool Acked)>(StringComparer.Ordinal);
map[Handle] = perHandle;
return perHandle;
}
private static void Emit(RealOpcUaClient client, string condition, bool active, bool acked, List<NativeAlarmTransition> sink)
{
var fields = new Variant[]
{
Variant.From(ObjectTypeIds.AlarmConditionType), // 0 EventType
Variant.From(new NodeId("Tank01", 2)), // 1 SourceNode
Variant.From("Tank01"), // 2 SourceName
Variant.From(DateTime.UtcNow), // 3 Time
Variant.From(new LocalizedText("msg")), // 4 Message
Variant.From((ushort)500), // 5 Severity
Variant.From(active), // 6 ActiveState/Id
Variant.From(acked), // 7 AckedState/Id
Variant.Null, // 8 ConfirmedState/Id
Variant.From(false), // 9 SuppressedOrShelved
Variant.Null, // 10 ShelvingState
Variant.From(condition), // 11 ConditionName
};
Handler.Invoke(client, [Handle, "ns=2;s=Tank01", new EventFieldList { EventFields = fields },
(Action<NativeAlarmTransition>)sink.Add]);
}
/// <summary>A per-occurrence condition that clears and is acknowledged leaves no key behind.</summary>
[Fact]
public void ReturnToNormal_DropsTheConditionKey()
{
var client = new RealOpcUaClient();
var lastState = SeedLastState(client);
var sink = new List<NativeAlarmTransition>();
for (var lot = 1; lot <= 50; lot++)
{
Emit(client, $"Hi.Lot{lot}", active: true, acked: false, sink);
Emit(client, $"Hi.Lot{lot}", active: false, acked: true, sink);
}
Assert.Empty(lastState);
Assert.Equal(100, sink.Count);
}
/// <summary>
/// Dropping the key does not change the transition kinds derived for a condition that comes
/// back — the dropped state equals the default prior state.
/// </summary>
[Fact]
public void ReRaiseAfterReturnToNormal_StillDerivesARaise()
{
var client = new RealOpcUaClient();
var lastState = SeedLastState(client);
var sink = new List<NativeAlarmTransition>();
Emit(client, "Hi", active: true, acked: false, sink);
Emit(client, "Hi", active: false, acked: true, sink);
Emit(client, "Hi", active: true, acked: false, sink);
Assert.Equal(sink[0].Kind, sink[2].Kind);
Assert.Single(lastState); // the re-raised condition is tracked again
}
}