feat(grpc-data): A1 origin condition state in the node manager — delta callback, state_known, activation marker, sliced snapshot, MarkConditionsKnown sink seam, IAlarmInitialStateSignal
This commit is contained in:
@@ -88,6 +88,14 @@ public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgical
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply() => _inner.CompleteAddressSpaceApply();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
=> _inner.MarkConditionsKnown(source, conditionIds, realm);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsUnknown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
=> _inner.MarkConditionsUnknown(source, conditionIds, realm);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) => _inner.RaiseNodesAddedModelChange(affectedNodeId, realm);
|
||||
|
||||
|
||||
@@ -213,6 +213,31 @@ public interface IOpcUaAddressSpaceSink
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A1 (plan §5.1 T1/T2): the state of <paramref name="conditionIds"/> has been ESTABLISHED by
|
||||
/// <paramref name="source"/> (a driver's <c>InitialAlarmStateDelivered</c>, its backstop timer, or a scripted
|
||||
/// alarm whose inputs were all pushed). An SDK-backed sink sets each materialised condition's known flag and
|
||||
/// raises one state-only condition-state record per newly known condition. <c>OpcUaPublishActor</c> applies it
|
||||
/// strictly after the alarm projections the source emitted before it (F2). Default: no-op.
|
||||
/// </summary>
|
||||
/// <param name="source">The source (driver instance id, or the scripted host) — diagnostics only.</param>
|
||||
/// <param name="conditionIds">The condition node ids (RawPath for native, ScriptedAlarmId for scripted).</param>
|
||||
/// <param name="realm">Their realm.</param>
|
||||
void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A1: withdraw "known" from conditions whose state can no longer be vouched for (a scripted alarm whose input
|
||||
/// reverted to never-pushed). Raises one state-only record per condition that was known. Default: no-op.
|
||||
/// </summary>
|
||||
/// <param name="source">The source — diagnostics only.</param>
|
||||
/// <param name="conditionIds">The condition node ids.</param>
|
||||
/// <param name="realm">Their realm.</param>
|
||||
void MarkConditionsUnknown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Announce that nodes were added at runtime (discovered-node injection) under
|
||||
/// <paramref name="affectedNodeId"/> so subscribed clients refresh their browse
|
||||
@@ -316,6 +341,12 @@ public sealed class NullOpcUaAddressSpaceSink : IOpcUaAddressSpaceSink
|
||||
/// <inheritdoc />
|
||||
public void RebuildAddressSpace() { }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm) { }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsUnknown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm) { }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { }
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Optional companion to <see cref="IAlarmSource"/>: the driver says when the standing state of a set of its
|
||||
/// conditions has been <b>established</b> — the initial replay, refresh, poll or walk that covers them has
|
||||
/// completed and every alarm event it produced has already been raised (plan
|
||||
/// <c>2026-11-23-grpc-data-connections-history-alarms</c> §5.1, F1/F2/G1/G5).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>An ordered callback, never a <see cref="System.Threading.Tasks.Task"/> (F2).</b> Raise
|
||||
/// <see cref="InitialAlarmStateDelivered"/> synchronously, on the same thread and callback path as
|
||||
/// <see cref="IAlarmSource.OnAlarmEvent"/>, <b>after</b> the last alarm event the completed read covers. The
|
||||
/// host marshals both onto the same actor mailbox, so the "known" mark it derives is applied after every
|
||||
/// projection the driver emitted before raising it. A task continuation could overtake queued transitions.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Carry what it covers (G1).</b> <see cref="AlarmInitialStateEventArgs.ConditionIds"/> lists the driver
|
||||
/// <c>ConditionId</c>s (= the condition's RawPath, the routing key of the alarm event) whose state the
|
||||
/// completed read established — never "the whole driver". An unreachable device's conditions are simply
|
||||
/// left out and stay unknown.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Raise on every completed read or cycle</b>, not only the first. Repeats are no-ops downstream; they are
|
||||
/// what makes conditions known again after a reconnect or a deploy that adds conditions.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Suppression gate (G5).</b> Obey exactly the gate <see cref="IAlarmSource.OnAlarmEvent"/> obeys: raise
|
||||
/// only while an alarm subscription is live. A refresh / poll / sentinel that completes while events are
|
||||
/// suppressed raises nothing; the first signal after (re)subscribe follows the post-subscribe replay.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>A source that cannot signal at all</b> (an OPC UA upstream without ConditionRefresh) raises the event
|
||||
/// once with <see cref="AlarmInitialStateEventArgs.Unsignalable"/> set: the host then applies its
|
||||
/// per-driver-type backstop timer to those conditions instead. No other shipped source should use it.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public interface IAlarmInitialStateSignal
|
||||
{
|
||||
/// <summary>The standing state of <see cref="AlarmInitialStateEventArgs.ConditionIds"/> has been delivered.</summary>
|
||||
event EventHandler<AlarmInitialStateEventArgs>? InitialAlarmStateDelivered;
|
||||
}
|
||||
|
||||
/// <summary>Payload of <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/>.</summary>
|
||||
public sealed class AlarmInitialStateEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>Creates the payload.</summary>
|
||||
/// <param name="conditionIds">The driver condition ids (RawPaths) whose state the completed read established.</param>
|
||||
/// <param name="unsignalable">
|
||||
/// <see langword="true"/> when the source can never signal for these conditions (no refresh upstream);
|
||||
/// the host's backstop timer applies instead of an immediate mark.
|
||||
/// </param>
|
||||
public AlarmInitialStateEventArgs(IReadOnlyList<string> conditionIds, bool unsignalable = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(conditionIds);
|
||||
ConditionIds = conditionIds;
|
||||
Unsignalable = unsignalable;
|
||||
}
|
||||
|
||||
/// <summary>The driver condition ids (= RawPaths) the completed read covers. Never "everything".</summary>
|
||||
public IReadOnlyList<string> ConditionIds { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The source reports <c>InitialStateUnsignalable</c> for these conditions: no real signal will ever come,
|
||||
/// so the per-driver-type backstop timer (OpcUaClient only) decides when they become known.
|
||||
/// </summary>
|
||||
public bool Unsignalable { get; }
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
/// <summary>
|
||||
/// The origin-owned activation marker of one condition (plan §5.6 step 3, T3): <c>(serving incarnation,
|
||||
/// per-condition sequence)</c>. The sequence moves only on a NEW occurrence — an Active false→true edge or any
|
||||
/// Acked true→false edge — never on a re-projection that leaves Active/Acked unchanged.
|
||||
/// </summary>
|
||||
/// <param name="Incarnation">The node manager's serving incarnation (one per process lifetime).</param>
|
||||
/// <param name="Sequence">The per-condition occurrence sequence.</param>
|
||||
public readonly record struct ConditionActivationMarker(string Incarnation, ulong Sequence);
|
||||
|
||||
/// <summary>
|
||||
/// One immutable, SDK-free copy of a live condition's state (plan §5.1), produced by the node manager under its
|
||||
/// <c>Lock</c> — either as a delta (raised for every condition state change) or inside a
|
||||
/// <see cref="ConditionSnapshotSlice"/>. Invisible until A2 puts it on the wire.
|
||||
/// </summary>
|
||||
/// <param name="Realm">The condition's realm (Raw = native RawPath, Uns = ScriptedAlarmId).</param>
|
||||
/// <param name="ConditionId">The condition node id within <paramref name="Realm"/>.</param>
|
||||
/// <param name="IsNative">Driver-fed (native) rather than scripted.</param>
|
||||
/// <param name="Version">The hub version: the delta's own version, or the slice watermark for a snapshot copy.</param>
|
||||
/// <param name="Removed">A removal record: the condition left the address space.</param>
|
||||
/// <param name="StateKnown">
|
||||
/// The condition's state has actually been established (§5.1 T2). A record with <c>false</c> never changes a
|
||||
/// consumer's last state; it only marks the condition Uncertain.
|
||||
/// </param>
|
||||
/// <param name="Active">Part 9 ActiveState.</param>
|
||||
/// <param name="Acknowledged">Part 9 AckedState.</param>
|
||||
/// <param name="Confirmed">Part 9 ConfirmedState.</param>
|
||||
/// <param name="Enabled">Part 9 EnabledState.</param>
|
||||
/// <param name="Shelving">The shelving kind.</param>
|
||||
/// <param name="Severity">The node's Part 9 severity (1..1000).</param>
|
||||
/// <param name="Message">The node's message text.</param>
|
||||
/// <param name="Quality">The condition's source-data Quality status code.</param>
|
||||
/// <param name="ConditionClassName">The Part 9 ConditionClassName text, if set.</param>
|
||||
/// <param name="TimeUtc">The condition's <c>Time</c>.</param>
|
||||
/// <param name="Retain">Part 9 Retain.</param>
|
||||
/// <param name="Activation">The origin-owned activation marker (T3).</param>
|
||||
/// <param name="Comment">The condition's Comment text, if any.</param>
|
||||
/// <param name="ClientUserId">Who left that comment, if recorded.</param>
|
||||
public sealed record ConditionStateRecord(
|
||||
AddressSpaceRealm Realm,
|
||||
string ConditionId,
|
||||
bool IsNative,
|
||||
long Version,
|
||||
bool Removed,
|
||||
bool StateKnown,
|
||||
bool Active,
|
||||
bool Acknowledged,
|
||||
bool Confirmed,
|
||||
bool Enabled,
|
||||
AlarmShelvingKind Shelving,
|
||||
ushort Severity,
|
||||
string Message,
|
||||
uint Quality,
|
||||
string? ConditionClassName,
|
||||
DateTime TimeUtc,
|
||||
bool Retain,
|
||||
ConditionActivationMarker Activation,
|
||||
string? Comment = null,
|
||||
string? ClientUserId = null);
|
||||
|
||||
/// <summary>
|
||||
/// The node manager's SDK-free delta callback (plan §5.1). Implemented by the Runtime's <c>ConditionStateHub</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Both members are called <b>under the node manager's <c>Lock</c></b>, which is what makes a snapshot cut atomic:
|
||||
/// every delta is either inside a slice or after its watermark. Implementations must therefore only enqueue —
|
||||
/// no I/O, never block, never call back into the node manager.
|
||||
/// </remarks>
|
||||
public interface IConditionStateSink
|
||||
{
|
||||
/// <summary>The version of the last appended record (the snapshot watermark). Read under the node manager's Lock.</summary>
|
||||
long Watermark { get; }
|
||||
|
||||
/// <summary>Append one delta record. The sink assigns its version; the record's own <c>Version</c> is ignored.</summary>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <returns>The version assigned.</returns>
|
||||
long Append(ConditionStateRecord record);
|
||||
|
||||
/// <summary>
|
||||
/// The node manager's address-space apply state changed: <see langword="false"/> when a rebuild began (the
|
||||
/// condition set is being re-created), <see langword="true"/> when <c>CompleteAddressSpaceApply</c> ran. Part of
|
||||
/// the <c>snapshot_complete</c> readiness (§5.1: apply complete + Primary verdict).
|
||||
/// </summary>
|
||||
/// <param name="complete">Whether the current apply has completed.</param>
|
||||
void OnApplyStateChanged(bool complete);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One <c>Lock</c> hold of <see cref="OtOpcUaNodeManager.SnapshotConditions"/>: at most <c>MaxConditions</c>
|
||||
/// records plus the watermark at that instant. A delta for one of these conditions with a version above
|
||||
/// <see cref="Watermark"/> applies after the slice; one at or below it is already inside.
|
||||
/// </summary>
|
||||
/// <param name="Watermark">The sink's watermark taken under the same hold.</param>
|
||||
/// <param name="Records">The copied records (each carries <see cref="Watermark"/> as its version).</param>
|
||||
public sealed record ConditionSnapshotSlice(long Watermark, IReadOnlyList<ConditionStateRecord> Records);
|
||||
@@ -0,0 +1,310 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
/// <summary>
|
||||
/// A1 origin condition state (plan §5.1): the SDK-free delta callback, <c>state_known</c>, the activation marker
|
||||
/// (T3) and the sliced snapshot. Every member that touches these maps runs under <c>Lock</c>; nothing here does
|
||||
/// I/O or blocks — the sink only enqueues.
|
||||
/// </summary>
|
||||
public sealed partial class OtOpcUaNodeManager
|
||||
{
|
||||
/// <summary>The default most conditions one snapshot <c>Lock</c> hold copies (§5.5 <c>MaxConditions</c>).</summary>
|
||||
public const int DefaultMaxConditionsPerHold = 1000;
|
||||
|
||||
/// <summary>Per-condition activation bookkeeping: the occurrence sequence plus the Active/Acked basis it was
|
||||
/// last compared against. Mutable, only touched under <c>Lock</c>.</summary>
|
||||
private sealed class ActivationEntry
|
||||
{
|
||||
public ulong Sequence;
|
||||
public bool Active;
|
||||
public bool Acked = true;
|
||||
public ActivationEntry Clone() => new() { Sequence = Sequence, Active = Active, Acked = Acked };
|
||||
}
|
||||
|
||||
private IConditionStateSink? _conditionStateSink;
|
||||
private readonly HashSet<RealmKey> _conditionStateKnown = new();
|
||||
private readonly Dictionary<RealmKey, ActivationEntry> _activation = new();
|
||||
// Rebuild memory for SCRIPTED conditions (native ones ride NativeConditionCarryOver): their marker basis survives
|
||||
// the clear-and-re-materialise so the engine's re-assert of an unchanged active alarm is not a new occurrence.
|
||||
private readonly Dictionary<RealmKey, ActivationEntry> _rebuildScriptedActivation = new();
|
||||
// Conditions a rebuild discarded and no materialise has claimed yet; at CompleteAddressSpaceApply the remainder
|
||||
// gets a removal record. A condition that comes back is never announced as removed (T2: a rebuild must not make
|
||||
// a consumer retire a condition that is still active at the origin).
|
||||
private readonly HashSet<RealmKey> _rebuildPendingRemoval = new();
|
||||
private bool _conditionApplyComplete;
|
||||
|
||||
/// <summary>The serving incarnation the activation markers are minted under (one per node-manager lifetime).</summary>
|
||||
internal string ConditionIncarnation { get; set; } = Guid.NewGuid().ToString("N");
|
||||
|
||||
/// <summary>Test seam: invoked after each snapshot <c>Lock</c> hold (outside it) with the records that hold copied.</summary>
|
||||
internal Action<int>? OnConditionSnapshotHold { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The SDK-free condition-state delta callback (the Runtime's <c>ConditionStateHub</c>). Null = no hub; the
|
||||
/// known flags and activation markers are still maintained. Set once at host start.
|
||||
/// </summary>
|
||||
public IConditionStateSink? ConditionStateSink
|
||||
{
|
||||
get => _conditionStateSink;
|
||||
set
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
_conditionStateSink = value;
|
||||
value?.OnApplyStateChanged(_conditionApplyComplete);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether the last address-space apply has completed (<c>CompleteAddressSpaceApply</c> ran since the
|
||||
/// last rebuild began). Part of the <c>snapshot_complete</c> readiness.</summary>
|
||||
public bool IsConditionApplyComplete { get { lock (Lock) return _conditionApplyComplete; } }
|
||||
|
||||
/// <summary>Whether the condition's state is known (test + diagnostics read).</summary>
|
||||
/// <param name="conditionNodeId">The condition id.</param>
|
||||
/// <param name="realm">Its realm.</param>
|
||||
/// <returns><see langword="true"/> when its state has been established.</returns>
|
||||
public bool IsConditionStateKnown(string conditionNodeId, AddressSpaceRealm realm)
|
||||
{
|
||||
lock (Lock) return _conditionStateKnown.Contains(MapKey(realm, conditionNodeId));
|
||||
}
|
||||
|
||||
/// <summary>The condition's current activation marker, or null when no such condition is materialised.</summary>
|
||||
/// <param name="conditionNodeId">The condition id.</param>
|
||||
/// <param name="realm">Its realm.</param>
|
||||
/// <returns>The marker.</returns>
|
||||
public ConditionActivationMarker? GetActivationMarker(string conditionNodeId, AddressSpaceRealm realm)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
var key = MapKey(realm, conditionNodeId);
|
||||
return _alarmConditions.ContainsKey(key) && _activation.TryGetValue(key, out var e)
|
||||
? new ConditionActivationMarker(ConditionIncarnation, e.Sequence) : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mark conditions whose state has been established (plan §5.1 T1/T2): sets the flag under <c>Lock</c> and raises
|
||||
/// one state-only record per NEWLY known condition. Repeats and unmaterialised ids are no-ops.
|
||||
/// </summary>
|
||||
/// <param name="source">The source (driver instance id, or the scripted host) — diagnostics only.</param>
|
||||
/// <param name="conditionIds">The condition ids.</param>
|
||||
/// <param name="realm">Their realm.</param>
|
||||
/// <returns>How many conditions became known.</returns>
|
||||
public int MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(conditionIds);
|
||||
var marked = 0;
|
||||
lock (Lock)
|
||||
{
|
||||
foreach (var id in conditionIds)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id)) continue;
|
||||
var key = MapKey(realm, id);
|
||||
if (!_alarmConditions.TryGetValue(key, out var condition) || !_conditionStateKnown.Add(key)) continue;
|
||||
RaiseConditionRecord(key, condition);
|
||||
marked++;
|
||||
}
|
||||
}
|
||||
|
||||
if (marked > 0)
|
||||
_logger.LogDebug("OtOpcUaNodeManager: {Source} established the state of {Count} condition(s)", source, marked);
|
||||
return marked;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Withdraw "known" from conditions whose state can no longer be vouched for (a scripted alarm whose input
|
||||
/// reverted to never-pushed). Raises one state-only record per condition that was known.
|
||||
/// </summary>
|
||||
/// <param name="source">The source — diagnostics only.</param>
|
||||
/// <param name="conditionIds">The condition ids.</param>
|
||||
/// <param name="realm">Their realm.</param>
|
||||
/// <returns>How many conditions became unknown.</returns>
|
||||
public int MarkConditionsUnknown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(conditionIds);
|
||||
var cleared = 0;
|
||||
lock (Lock)
|
||||
{
|
||||
foreach (var id in conditionIds)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id)) continue;
|
||||
var key = MapKey(realm, id);
|
||||
if (!_alarmConditions.TryGetValue(key, out var condition) || !_conditionStateKnown.Remove(key)) continue;
|
||||
RaiseConditionRecord(key, condition);
|
||||
cleared++;
|
||||
}
|
||||
}
|
||||
|
||||
if (cleared > 0)
|
||||
_logger.LogDebug("OtOpcUaNodeManager: {Source} withdrew the state of {Count} condition(s)", source, cleared);
|
||||
return cleared;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copy every live condition in <paramref name="scope"/> (inactive, acknowledged and normal ones too — the
|
||||
/// snapshot defines the SET), never more than <paramref name="maxConditionsPerHold"/> per <c>Lock</c> hold.
|
||||
/// Each slice carries the sink's watermark taken under the same hold, so a delta is either inside the slice or
|
||||
/// after its watermark. A consumer must register for deltas before snapshotting.
|
||||
/// </summary>
|
||||
/// <param name="scope">Realm + id filter (an export's root); evaluated outside <c>Lock</c>.</param>
|
||||
/// <param name="maxConditionsPerHold">The most conditions one hold copies (≥ 1).</param>
|
||||
/// <returns>The slices in ascending (realm, id) order.</returns>
|
||||
public IReadOnlyList<ConditionSnapshotSlice> SnapshotConditions(
|
||||
Func<AddressSpaceRealm, string, bool> scope, int maxConditionsPerHold = DefaultMaxConditionsPerHold)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(scope);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(maxConditionsPerHold, 1);
|
||||
|
||||
// Key enumeration and the scope filter run OFF Lock (the map is concurrent and keys are immutable); a
|
||||
// condition added after this point is not in the snapshot but its materialise record is a delta.
|
||||
var keys = _alarmConditions.Keys.Where(k => scope(k.Realm, k.Id))
|
||||
.OrderBy(k => k.Realm).ThenBy(k => k.Id, StringComparer.Ordinal).ToList();
|
||||
var slices = new List<ConditionSnapshotSlice>((keys.Count + maxConditionsPerHold - 1) / maxConditionsPerHold);
|
||||
for (var start = 0; start < keys.Count; start += maxConditionsPerHold)
|
||||
{
|
||||
var end = Math.Min(start + maxConditionsPerHold, keys.Count);
|
||||
var records = new List<ConditionStateRecord>(end - start);
|
||||
long watermark;
|
||||
lock (Lock)
|
||||
{
|
||||
watermark = _conditionStateSink?.Watermark ?? 0;
|
||||
for (var i = start; i < end; i++)
|
||||
{
|
||||
if (_alarmConditions.TryGetValue(keys[i], out var condition))
|
||||
records.Add(BuildConditionRecord(keys[i], condition, watermark, removed: false));
|
||||
}
|
||||
}
|
||||
|
||||
OnConditionSnapshotHold?.Invoke(records.Count);
|
||||
slices.Add(new ConditionSnapshotSlice(watermark, records));
|
||||
}
|
||||
|
||||
return slices;
|
||||
}
|
||||
|
||||
/// <summary>Called under <c>Lock</c> when a condition is (re)materialised: clears known, seeds (or restores) its
|
||||
/// activation basis. The record is raised by <see cref="FinishConditionMaterialise"/>.</summary>
|
||||
private void BeginConditionMaterialise(RealmKey key, bool isNative)
|
||||
{
|
||||
_conditionStateKnown.Remove(key);
|
||||
_rebuildPendingRemoval.Remove(key);
|
||||
_activation[key] = !isNative && _rebuildScriptedActivation.Remove(key, out var kept) ? kept : new ActivationEntry();
|
||||
}
|
||||
|
||||
/// <summary>Under <c>Lock</c>, after registration and any carry-over restore: raise the condition's first record.</summary>
|
||||
/// <remarks>It does NOT advance the activation basis: a scripted condition re-created by a rebuild keeps the basis it
|
||||
/// had, so the engine's re-assert of the same still-active alarm onto the fresh (inactive) node is no new occurrence.</remarks>
|
||||
private void FinishConditionMaterialise(RealmKey key, AlarmConditionState alarm) =>
|
||||
_conditionStateSink?.Append(BuildConditionRecord(key, alarm, 0, removed: false));
|
||||
|
||||
/// <summary>Under <c>Lock</c>: a condition left the address space — drop its flags and raise a removal record.</summary>
|
||||
private void ForgetConditionState(RealmKey key, AlarmConditionState condition)
|
||||
{
|
||||
_conditionStateKnown.Remove(key);
|
||||
_activation.Remove(key, out var entry);
|
||||
_conditionStateSink?.Append(BuildConditionRecord(key, condition, 0, removed: true, entry));
|
||||
}
|
||||
|
||||
/// <summary>Under <c>Lock</c>, at the start of a full rebuild: remember what must survive the clear.</summary>
|
||||
private void CaptureConditionStateForRebuild()
|
||||
{
|
||||
_conditionApplyComplete = false;
|
||||
_conditionStateSink?.OnApplyStateChanged(false);
|
||||
_rebuildScriptedActivation.Clear();
|
||||
foreach (var key in _alarmConditions.Keys)
|
||||
{
|
||||
_rebuildPendingRemoval.Add(key);
|
||||
if (!_nativeAlarmNodeIds.Contains(key) && _activation.TryGetValue(key, out var e))
|
||||
_rebuildScriptedActivation[key] = e.Clone();
|
||||
}
|
||||
|
||||
_conditionStateKnown.Clear();
|
||||
_activation.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Under <c>Lock</c>, at <c>CompleteAddressSpaceApply</c>: announce the conditions the rebuild dropped
|
||||
/// for good, forget the rebuild memory and mark the apply complete.</summary>
|
||||
private void CompleteConditionApply()
|
||||
{
|
||||
foreach (var key in _rebuildPendingRemoval)
|
||||
{
|
||||
if (_alarmConditions.ContainsKey(key)) continue;
|
||||
_conditionStateSink?.Append(new ConditionStateRecord(key.Realm, key.Id, false, 0, Removed: true, StateKnown: false,
|
||||
false, true, true, true, AlarmShelvingKind.Unshelved, 0, string.Empty, StatusCodes.Good.Code, null, UtcNow, false,
|
||||
new ConditionActivationMarker(ConditionIncarnation, 0)));
|
||||
}
|
||||
|
||||
_rebuildPendingRemoval.Clear();
|
||||
_rebuildScriptedActivation.Clear();
|
||||
_conditionApplyComplete = true;
|
||||
_conditionStateSink?.OnApplyStateChanged(true);
|
||||
}
|
||||
|
||||
/// <summary>Capture a native condition's marker basis + known flag for <see cref="NativeConditionCarryOver"/>.</summary>
|
||||
private (ulong Sequence, bool Active, bool Acked, bool Known) CaptureActivation(RealmKey key)
|
||||
{
|
||||
var known = _conditionStateKnown.Contains(key);
|
||||
return _activation.TryGetValue(key, out var e) ? (e.Sequence, e.Active, e.Acked, known) : (0, false, true, known);
|
||||
}
|
||||
|
||||
/// <summary>Restore a carried native condition's marker basis and (T2) its known flag — carried-over state is
|
||||
/// known at once, but only if it was known before the rebuild.</summary>
|
||||
private void RestoreActivation(RealmKey key, ulong sequence, bool active, bool acked, bool known)
|
||||
{
|
||||
_activation[key] = new ActivationEntry { Sequence = sequence, Active = active, Acked = acked };
|
||||
if (known) _conditionStateKnown.Add(key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Under <c>Lock</c>: advance the activation marker against the node's current Active/Acked and append one
|
||||
/// record to the sink. Called for every condition state change — event-firing or silent.
|
||||
/// </summary>
|
||||
private void RaiseConditionRecord(RealmKey key, AlarmConditionState condition)
|
||||
{
|
||||
var entry = AdvanceActivation(key, condition);
|
||||
_conditionStateSink?.Append(BuildConditionRecord(key, condition, 0, removed: false, entry));
|
||||
}
|
||||
|
||||
/// <summary>The raise path for a condition known only by instance (ReportConditionEvent).</summary>
|
||||
private void RaiseConditionRecord(AlarmConditionState condition)
|
||||
{
|
||||
var key = MapKey(condition.NodeId);
|
||||
// A stale instance (replaced or removed) is not the live condition: its report never describes the set.
|
||||
if (!_alarmConditions.TryGetValue(key, out var live) || !ReferenceEquals(live, condition)) return;
|
||||
RaiseConditionRecord(key, condition);
|
||||
}
|
||||
|
||||
/// <summary>T3: bump on an Active false→true edge or ANY Acked true→false edge; never otherwise.</summary>
|
||||
private ActivationEntry AdvanceActivation(RealmKey key, AlarmConditionState condition)
|
||||
{
|
||||
if (!_activation.TryGetValue(key, out var e)) _activation[key] = e = new ActivationEntry();
|
||||
var active = condition.ActiveState?.Id?.Value ?? false;
|
||||
var acked = condition.AckedState?.Id?.Value ?? true;
|
||||
if ((active && !e.Active) || (e.Acked && !acked)) e.Sequence++;
|
||||
e.Active = active;
|
||||
e.Acked = acked;
|
||||
return e;
|
||||
}
|
||||
|
||||
private ConditionStateRecord BuildConditionRecord(
|
||||
RealmKey key, AlarmConditionState c, long version, bool removed, ActivationEntry? entry = null)
|
||||
{
|
||||
entry ??= _activation.TryGetValue(key, out var e) ? e : null;
|
||||
var delta = ReadConditionDelta(c);
|
||||
return new ConditionStateRecord(
|
||||
key.Realm, key.Id, _nativeAlarmNodeIds.Contains(key), version, removed,
|
||||
StateKnown: !removed && _conditionStateKnown.Contains(key),
|
||||
delta.Active, delta.Acknowledged, delta.Confirmed, delta.Enabled, delta.Shelving, delta.MappedSeverity,
|
||||
delta.Message, delta.Quality.Code,
|
||||
c.ConditionClassName?.Value.Text,
|
||||
c.Time?.Value.ToDateTime() is { } t && t != DateTime.MinValue ? DateTime.SpecifyKind(t, DateTimeKind.Utc) : UtcNow,
|
||||
c.Retain?.Value == true,
|
||||
new ConditionActivationMarker(ConditionIncarnation, entry?.Sequence ?? 0),
|
||||
c.Comment?.Value.Text,
|
||||
c.ClientUserId?.Value);
|
||||
}
|
||||
}
|
||||
@@ -1419,10 +1419,18 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// WireMethodTransitionReporting) equals the node's current state → no delta → suppress, so
|
||||
// the transition is reported exactly once. ReportConditionEvent
|
||||
// stamps a fresh EventId, ClearChangeMasks, and ReportEvent — all still under this lock.
|
||||
// A1 (§5.1): a projected snapshot IS an established state. The record is raised by
|
||||
// ReportConditionEvent when the gate fires, otherwise here as a state-only record (ConditionClass and
|
||||
// the other silent fields).
|
||||
_conditionStateKnown.Add(key);
|
||||
if (fire)
|
||||
{
|
||||
ReportConditionEvent(condition, sourceTimestampUtc);
|
||||
}
|
||||
else
|
||||
{
|
||||
RaiseConditionRecord(key, condition);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1557,6 +1565,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// the InstanceStateSnapshot captures the just-projected values.
|
||||
alarm.ClearChangeMasks(SystemContext, includeChildren: true);
|
||||
|
||||
// A1 (§5.1): the condition-state delta is raised BEFORE the Warm-Standby return, so a standby's hub stays
|
||||
// current and a promoted Primary starts correct.
|
||||
RaiseConditionRecord(alarm);
|
||||
|
||||
// Gitea #717 spec §4.5: on a Warm Standby only the STAMP half above runs — the condition node is current and a
|
||||
// later refresh carries a valid, ackable EventId — and the DELIVER half below does not. Suppressing here, before
|
||||
// the snapshot and every SDK field projection, covers the Server-object, folder and direct paths, ACL on or
|
||||
@@ -2640,6 +2652,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
|
||||
AddPredefinedNode(SystemContext, alarm);
|
||||
_alarmConditions[conditionKey] = alarm;
|
||||
BeginConditionMaterialise(conditionKey, isNative);
|
||||
if (!string.IsNullOrEmpty(equipmentNodeId)) IndexChild(MapKey(realm, equipmentNodeId), conditionKey);
|
||||
// Only the new condition can be missing its unit here, so raise just that one — a full reconcile
|
||||
// walks every condition, which made a deploy of N alarms O(N²) under Lock whenever any Server-object
|
||||
@@ -2659,6 +2672,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// for a later re-add to resurrect.
|
||||
if (_rebuildCarryOver.Remove(conditionKey, out var carried) && isNative)
|
||||
RestoreCarryOver(alarm, conditionKey, carried);
|
||||
FinishConditionMaterialise(conditionKey, alarm);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2675,7 +2689,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
private sealed record NativeConditionCarryOver(
|
||||
AlarmConditionDelta State, DateTime Time, DateTime? ActiveTransitionTime, DateTime? QualityTimestamp,
|
||||
LocalizedText? Comment = null, string? ClientUserId = null, NodeId? ConditionClassId = null,
|
||||
LocalizedText? ConditionClassName = null);
|
||||
LocalizedText? ConditionClassName = null, ulong ActivationSequence = 0, bool ActivationActive = false,
|
||||
bool ActivationAcked = true, bool StateKnown = false);
|
||||
|
||||
/// <summary>
|
||||
/// Read what a native condition node holds right now, so the rebuild can put it back.
|
||||
@@ -2696,15 +2711,20 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// </remarks>
|
||||
/// <param name="condition">The live native condition, about to be discarded.</param>
|
||||
/// <returns>Its carried state.</returns>
|
||||
private NativeConditionCarryOver CaptureCarryOver(AlarmConditionState condition) => new(
|
||||
ReadConditionDelta(condition),
|
||||
condition.Time?.Value.ToDateTime() ?? UtcNow,
|
||||
condition.ActiveState?.TransitionTime?.Value.ToDateTime(),
|
||||
condition.Quality?.SourceTimestamp?.Value.ToDateTime(),
|
||||
condition.Comment?.Value,
|
||||
condition.ClientUserId?.Value,
|
||||
condition.ConditionClassId?.Value,
|
||||
condition.ConditionClassName?.Value);
|
||||
private NativeConditionCarryOver CaptureCarryOver(RealmKey key, AlarmConditionState condition)
|
||||
{
|
||||
var a = CaptureActivation(key);
|
||||
return new(
|
||||
ReadConditionDelta(condition),
|
||||
condition.Time?.Value.ToDateTime() ?? UtcNow,
|
||||
condition.ActiveState?.TransitionTime?.Value.ToDateTime(),
|
||||
condition.Quality?.SourceTimestamp?.Value.ToDateTime(),
|
||||
condition.Comment?.Value,
|
||||
condition.ClientUserId?.Value,
|
||||
condition.ConditionClassId?.Value,
|
||||
condition.ConditionClassName?.Value,
|
||||
a.Sequence, a.Active, a.Acked, a.Known);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Put a carried state back onto the freshly materialised native condition. MUST be called
|
||||
@@ -2733,6 +2753,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
private void RestoreCarryOver(AlarmConditionState alarm, RealmKey conditionKey, NativeConditionCarryOver carried)
|
||||
{
|
||||
var state = carried.State;
|
||||
// A1 (T3, T2): the activation marker and the known flag ride the carry-over, normal conditions included.
|
||||
RestoreActivation(conditionKey, carried.ActivationSequence, carried.ActivationActive, carried.ActivationAcked, carried.StateKnown);
|
||||
// #839: a driver-assigned ConditionClass is a property of the condition, not of its state — restored whether
|
||||
// or not the condition is off-normal (the materialise default is BaseConditionClass).
|
||||
if (alarm.ConditionClassId is { } classIdNode && carried.ConditionClassId is { } classId && !classId.IsNull)
|
||||
@@ -5583,8 +5605,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
_restoredConditionReports.Clear();
|
||||
foreach (var (key, alarm) in _alarmConditions)
|
||||
{
|
||||
if (_nativeAlarmNodeIds.Contains(key)) _rebuildCarryOver[key] = CaptureCarryOver(alarm);
|
||||
if (_nativeAlarmNodeIds.Contains(key)) _rebuildCarryOver[key] = CaptureCarryOver(key, alarm);
|
||||
}
|
||||
CaptureConditionStateForRebuild();
|
||||
|
||||
// tear down every native-alarm→equipment-folder notifier pair bidirectionally
|
||||
// BEFORE the conditions + folders are cleared below, so no inverse-notifier entry leaks across the
|
||||
@@ -5675,6 +5698,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
discarded = _rebuildCarryOver.Count;
|
||||
_restoredConditionReports.Clear();
|
||||
_rebuildCarryOver.Clear();
|
||||
CompleteConditionApply();
|
||||
}
|
||||
|
||||
if (reported > 0 || discarded > 0)
|
||||
@@ -5778,6 +5802,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// the condition drops — the folders (equipment, UNS realm) SURVIVE this scoped remove, so without
|
||||
// this they would keep a dangling inverse-notifier entry to the removed condition.
|
||||
UnwireAlarmNotifiers(key);
|
||||
ForgetConditionState(key, condition);
|
||||
condition.Parent?.RemoveChild(condition);
|
||||
ForgetPredefinedSubtree(condition);
|
||||
_nativeAlarmNodeIds.Remove(key);
|
||||
@@ -5889,6 +5914,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
UnindexChild(key);
|
||||
TombstoneMonitoredSubtree(c, now);
|
||||
UnwireAlarmNotifiers(key);
|
||||
ForgetConditionState(key, c);
|
||||
if (c.Parent is { } parent && !removedParents.Contains(parent)) parent.RemoveChild(c);
|
||||
ForgetPredefinedSubtree(c);
|
||||
_nativeAlarmNodeIds.Remove(key);
|
||||
|
||||
@@ -141,6 +141,14 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply() => _nodeManager.CompleteAddressSpaceApply();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
=> _nodeManager.MarkConditionsKnown(source, conditionIds, realm);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsUnknown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
=> _nodeManager.MarkConditionsUnknown(source, conditionIds, realm);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) => _nodeManager.RaiseNodesAddedModelChange(affectedNodeId, realm);
|
||||
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// A1 origin condition state (plan §5.1) at the node manager: the delta callback, <c>state_known</c>, the activation
|
||||
/// marker (T3) and the sliced snapshot. The parity cases (a)–(g) assert on NODE state: after each scenario the
|
||||
/// delta stream folded per condition equals a fresh snapshot of the live nodes.
|
||||
/// </summary>
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "A1")]
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ConditionStateNodeManagerTests : IDisposable
|
||||
{
|
||||
private const string Device = "Plant/Galaxy/dev1";
|
||||
private const string Native = "Plant/Galaxy/dev1/TankHi";
|
||||
private const string Native2 = "Plant/Galaxy/dev1/TankLo";
|
||||
private const string Equipment = "Area/Line/Eq";
|
||||
private const string Scripted = "scripted-eq-hi";
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-a1-{Guid.NewGuid():N}");
|
||||
|
||||
private static AlarmConditionSnapshot State(bool active, bool acked, string message = "hi", uint status = OpcUaStatus.Good,
|
||||
AlarmConditionClass? cls = null) => new(
|
||||
Active: active, Acknowledged: acked, Confirmed: true, Enabled: true, Shelving: AlarmShelvingKind.Unshelved,
|
||||
Severity: 700, Message: message, StatusCode: status, ConditionClass: cls);
|
||||
|
||||
// ---------------------------------------------------------------- parity (a)–(g)
|
||||
|
||||
[Fact]
|
||||
public async Task a_Cold_start_before_any_publish_lists_every_condition_unknown()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.CompleteAddressSpaceApply();
|
||||
|
||||
var snap = Flatten(nm.SnapshotConditions((_, _) => true));
|
||||
snap.Count.ShouldBe(3); // the snapshot defines the SET, normal conditions included
|
||||
snap.ShouldAllBe(r => !r.StateKnown);
|
||||
// Falsely-normal guard: no record ever claimed known before a source established a state.
|
||||
sink.Records.ShouldNotContain(r => r.StateKnown);
|
||||
AssertParity(nm, sink);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task b_Standby_promotion_with_standing_active_alarms_keeps_the_hub_current()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync(warm: true);
|
||||
nm.Standby.AlarmsSuppressed = true; // what a Warm OpcUaPublishActor sets while this node is not Primary
|
||||
nm.Standby.AlarmsSuppressed.ShouldBeTrue();
|
||||
MaterialiseAll(nm);
|
||||
nm.CompleteAddressSpaceApply();
|
||||
|
||||
// While Warm the event is suppressed, but the delta is raised before that return.
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
sink.Records.Last().ShouldSatisfyAllConditions(
|
||||
r => r.ConditionId.ShouldBe(Native), r => r.Active.ShouldBeTrue(), r => r.StateKnown.ShouldBeTrue());
|
||||
|
||||
nm.Standby.AlarmsSuppressed = false; // promotion
|
||||
AssertParity(nm, sink);
|
||||
Flatten(nm.SnapshotConditions((_, id) => id == Native)).Single().Active.ShouldBeTrue();
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task c_Rebuild_with_carried_over_alarms_is_known_at_once_and_never_announced_removed()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.CompleteAddressSpaceApply();
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
var marker = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw).ShouldNotBeNull();
|
||||
var before = sink.Records.Count;
|
||||
|
||||
nm.RebuildAddressSpace();
|
||||
sink.ApplyComplete.ShouldBe(false);
|
||||
// Native2 (never known) comes back too; the scripted one does NOT come back.
|
||||
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
|
||||
nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||||
nm.MaterialiseAlarmCondition(Native2, Device, "TankLo", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||||
|
||||
// Carried over ⇒ known at once, same occurrence marker (T3).
|
||||
nm.IsConditionStateKnown(Native, AddressSpaceRealm.Raw).ShouldBeTrue();
|
||||
nm.GetActivationMarker(Native, AddressSpaceRealm.Raw).ShouldBe(marker);
|
||||
// A carried NORMAL condition that was never known stays unknown (no falsely-normal known).
|
||||
nm.IsConditionStateKnown(Native2, AddressSpaceRealm.Raw).ShouldBeFalse();
|
||||
|
||||
nm.CompleteAddressSpaceApply();
|
||||
sink.ApplyComplete.ShouldBe(true);
|
||||
var rebuild = sink.Records.Skip(before).ToList();
|
||||
rebuild.ShouldNotContain(r => r.Removed && r.ConditionId == Native);
|
||||
rebuild.ShouldContain(r => r.Removed && r.ConditionId == Scripted);
|
||||
rebuild.Where(r => r.ConditionId == Native).ShouldAllBe(r => r.Active && r.StateKnown);
|
||||
AssertParity(nm, sink);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task d_A_local_client_native_ack_applied_by_the_SDK_reaches_the_hub()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw).ShouldNotBeNull();
|
||||
|
||||
// The SDK's own Acknowledge handler, behind our method-transition wrapper; the driver route is stubbed Good.
|
||||
alarm.OnAcknowledge = (_, _, _, _) => ServiceResult.Good;
|
||||
var result = alarm.Acknowledge!.OnCall!(nm.SystemContext, alarm.Acknowledge, alarm.NodeId,
|
||||
alarm.EventId!.Value, new LocalizedText("ok"));
|
||||
ServiceResult.IsGood(result).ShouldBeTrue(result.ToString());
|
||||
|
||||
alarm.AckedState!.Id!.Value.ShouldBeTrue();
|
||||
sink.Records.Last().ShouldSatisfyAllConditions(r => r.ConditionId.ShouldBe(Native), r => r.Acknowledged.ShouldBeTrue());
|
||||
AssertParity(nm, sink);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task e_A_ConditionClass_only_change_raises_a_state_only_record_and_no_event()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
var alarm = nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw).ShouldNotBeNull();
|
||||
var eventId = alarm.EventId!.Value.ToArray();
|
||||
var count = sink.Records.Count;
|
||||
|
||||
nm.WriteAlarmCondition(Native, State(true, false, cls: AlarmConditionClass.Safety), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
|
||||
alarm.EventId!.Value.ToArray().ShouldBe(eventId); // the delta gate fired nothing
|
||||
sink.Records.Count.ShouldBe(count + 1);
|
||||
sink.Records.Last().ConditionClassName.ShouldBe("SafetyConditionClass");
|
||||
AssertParity(nm, sink);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task f_An_ack_revert_reaches_the_hub_and_is_a_new_occurrence()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
nm.WriteAlarmCondition(Native, State(true, true), DateTime.UtcNow, AddressSpaceRealm.Raw); // ack applied
|
||||
var acked = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence;
|
||||
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); // #760 revert
|
||||
|
||||
sink.Records.Last().Acknowledged.ShouldBeFalse();
|
||||
nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence.ShouldBe(acked + 1); // F4: Acked true→false
|
||||
AssertParity(nm, sink);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task g_A_quality_only_update_reaches_the_hub()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.WriteAlarmCondition(Native, State(false, true), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
|
||||
nm.WriteAlarmQuality(Native, StatusCodes.BadNoCommunication.Code, DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
|
||||
sink.Records.Last().Quality.ShouldBe(StatusCodes.BadNoCommunication.Code);
|
||||
AssertParity(nm, sink);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- known / T1 / T3
|
||||
|
||||
[Fact]
|
||||
public async Task T1_A_signal_after_the_snapshot_cut_arrives_as_a_state_only_known_record()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.CompleteAddressSpaceApply();
|
||||
var slice = nm.SnapshotConditions((r, _) => r == AddressSpaceRealm.Raw).Single();
|
||||
slice.Records.ShouldAllBe(r => !r.StateKnown);
|
||||
// Negative control: nothing claims known before the signal.
|
||||
sink.Records.Where(r => r.Version > slice.Watermark).ShouldBeEmpty();
|
||||
|
||||
nm.MarkConditionsKnown("drv", [Native, Native2], AddressSpaceRealm.Raw).ShouldBe(2);
|
||||
|
||||
var after = sink.Records.Where(r => r.Version > slice.Watermark).ToList();
|
||||
after.Count.ShouldBe(2); // positive control: the records arrive with no further origin activity
|
||||
after.ShouldAllBe(r => r.StateKnown && !r.Active);
|
||||
// A repeat signal is a no-op.
|
||||
nm.MarkConditionsKnown("drv", [Native], AddressSpaceRealm.Raw).ShouldBe(0);
|
||||
sink.Records.Count(r => r.Version > slice.Watermark).ShouldBe(2);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Marking_unknown_withdraws_known_and_rematerialise_clears_it()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.MarkConditionsKnown("scripted", [Scripted], AddressSpaceRealm.Uns);
|
||||
nm.MarkConditionsUnknown("scripted", [Scripted], AddressSpaceRealm.Uns).ShouldBe(1);
|
||||
nm.IsConditionStateKnown(Scripted, AddressSpaceRealm.Uns).ShouldBeFalse();
|
||||
sink.Records.Last().StateKnown.ShouldBeFalse();
|
||||
nm.MarkConditionsUnknown("scripted", [Scripted], AddressSpaceRealm.Uns).ShouldBe(0);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task T3_The_marker_moves_only_on_a_new_occurrence()
|
||||
{
|
||||
var (host, nm, _) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
ulong Seq() => nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence;
|
||||
Seq().ShouldBe(0ul);
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
Seq().ShouldBe(1ul);
|
||||
nm.WriteAlarmCondition(Native, State(true, false, message: "changed"), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
nm.WriteAlarmCondition(Native, State(true, false, message: "changed"), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
Seq().ShouldBe(1ul); // message-only change and same-state re-projection
|
||||
nm.WriteAlarmCondition(Native, State(false, true), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
Seq().ShouldBe(1ul);
|
||||
nm.WriteAlarmCondition(Native, State(false, false), DateTime.UtcNow, AddressSpaceRealm.Raw); // InactiveUnacknowledged
|
||||
Seq().ShouldBe(2ul);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_scripted_condition_keeps_its_marker_across_a_rebuild_reassert()
|
||||
{
|
||||
var (host, nm, _) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns);
|
||||
var marker = nm.GetActivationMarker(Scripted, AddressSpaceRealm.Uns);
|
||||
|
||||
nm.RebuildAddressSpace();
|
||||
MaterialiseAll(nm);
|
||||
nm.IsConditionStateKnown(Scripted, AddressSpaceRealm.Uns).ShouldBeFalse(); // scripted: re-established by its engine
|
||||
nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns); // the re-assert
|
||||
nm.CompleteAddressSpaceApply();
|
||||
|
||||
nm.GetActivationMarker(Scripted, AddressSpaceRealm.Uns).ShouldBe(marker);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- snapshot structure
|
||||
|
||||
[Fact]
|
||||
public async Task A_snapshot_never_copies_more_than_MaxConditions_under_one_Lock_hold()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
|
||||
for (var i = 0; i < 25; i++)
|
||||
nm.MaterialiseAlarmCondition($"{Device}/A{i:00}", Device, $"A{i:00}", "OffNormalAlarm", 500, AddressSpaceRealm.Raw, isNative: true);
|
||||
|
||||
var holds = new List<int>();
|
||||
nm.OnConditionSnapshotHold = n =>
|
||||
{
|
||||
Monitor.IsEntered(nm.Lock).ShouldBeFalse(); // reported after the hold is released
|
||||
holds.Add(n);
|
||||
// A delta raised BETWEEN holds: into the second slice (A15) and into the first, already-cut one (A00).
|
||||
if (holds.Count == 1)
|
||||
{
|
||||
nm.WriteAlarmCondition($"{Device}/A15", State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
nm.WriteAlarmCondition($"{Device}/A00", State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
}
|
||||
};
|
||||
|
||||
var slices = nm.SnapshotConditions((_, _) => true, maxConditionsPerHold: 10);
|
||||
|
||||
holds.ShouldBe([10, 10, 5]);
|
||||
slices.Count.ShouldBe(3);
|
||||
// Atomic cut: A15's change is inside slice 2 (≤ its watermark); A00's is after slice 1's watermark.
|
||||
slices[1].Records.Single(r => r.ConditionId.EndsWith("A15")).Active.ShouldBeTrue();
|
||||
slices[0].Records.Single(r => r.ConditionId.EndsWith("A00")).Active.ShouldBeFalse();
|
||||
sink.Records.Single(r => r.ConditionId.EndsWith("A00") && r.Active).Version.ShouldBeGreaterThan(slices[0].Watermark);
|
||||
sink.Records.Single(r => r.ConditionId.EndsWith("A15") && r.Active).Version.ShouldBeLessThanOrEqualTo(slices[1].Watermark);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
private static void MaterialiseAll(OtOpcUaNodeManager nm)
|
||||
{
|
||||
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
|
||||
nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||||
nm.MaterialiseAlarmCondition(Native2, Device, "TankLo", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||||
nm.EnsureFolder(Equipment, null, "Eq", AddressSpaceRealm.Uns);
|
||||
nm.MaterialiseAlarmCondition(Scripted, Equipment, "Hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
|
||||
}
|
||||
|
||||
private static List<ConditionStateRecord> Flatten(IReadOnlyList<ConditionSnapshotSlice> slices) =>
|
||||
slices.SelectMany(s => s.Records).ToList();
|
||||
|
||||
/// <summary>Hub snapshot == node state: the delta stream folded per condition equals a fresh snapshot of the nodes.</summary>
|
||||
internal static void AssertParity(OtOpcUaNodeManager nm, RecordingConditionSink sink)
|
||||
{
|
||||
var fold = new Dictionary<(AddressSpaceRealm, string), ConditionStateRecord>();
|
||||
foreach (var r in sink.Records)
|
||||
{
|
||||
if (r.Removed) fold.Remove((r.Realm, r.ConditionId));
|
||||
else fold[(r.Realm, r.ConditionId)] = r;
|
||||
}
|
||||
|
||||
var nodes = nm.SnapshotConditions((_, _) => true).SelectMany(s => s.Records).ToList();
|
||||
fold.Count.ShouldBe(nodes.Count);
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
fold.TryGetValue((node.Realm, node.ConditionId), out var folded).ShouldBeTrue(node.ConditionId);
|
||||
(folded! with { Version = 0 }).ShouldBe(node with { Version = 0 }, node.ConditionId);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<(OpcUaApplicationHost Host, OtOpcUaNodeManager Nm, RecordingConditionSink Sink)> BootAsync(bool warm = false)
|
||||
{
|
||||
var applicationUri = $"urn:OtOpcUa.A1Test:{Guid.NewGuid():N}";
|
||||
var started = await OpcUaHostStart.StartAsync(
|
||||
port => new OpcUaApplicationHost(
|
||||
new OpcUaApplicationHostOptions
|
||||
{
|
||||
ApplicationName = "OtOpcUa.A1Test",
|
||||
ApplicationUri = applicationUri,
|
||||
OpcUaPort = port,
|
||||
PublicHostname = "localhost",
|
||||
PkiStoreRoot = _pkiRoot,
|
||||
Redundancy = new OpcUaRedundancyOptions { Mode = warm ? "Warm" : "Unset" },
|
||||
PeerApplicationUris = warm ? ["urn:peer"] : [],
|
||||
},
|
||||
Microsoft.Extensions.Logging.Abstractions.NullLogger<OpcUaApplicationHost>.Instance),
|
||||
() => new OtOpcUaSdkServer(), Ct);
|
||||
var nm = started.Server.NodeManager!;
|
||||
var sink = new RecordingConditionSink();
|
||||
nm.ConditionStateSink = sink;
|
||||
return (started.Host, nm, sink);
|
||||
}
|
||||
|
||||
/// <summary>Cleans up the PKI root directory.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_pkiRoot))
|
||||
{
|
||||
try { Directory.Delete(_pkiRoot, recursive: true); }
|
||||
catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An in-memory <see cref="IConditionStateSink"/> that keeps every record with its assigned version.</summary>
|
||||
internal sealed class RecordingConditionSink : IConditionStateSink
|
||||
{
|
||||
private long _version;
|
||||
|
||||
/// <summary>Every appended record, in order, with its version.</summary>
|
||||
public List<ConditionStateRecord> Records { get; } = new();
|
||||
|
||||
/// <summary>The last apply state the node manager reported.</summary>
|
||||
public bool? ApplyComplete { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public long Watermark => _version;
|
||||
|
||||
/// <inheritdoc />
|
||||
public long Append(ConditionStateRecord record)
|
||||
{
|
||||
var v = ++_version;
|
||||
Records.Add(record with { Version = v });
|
||||
return v;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void OnApplyStateChanged(bool complete) => ApplyComplete = complete;
|
||||
}
|
||||
Reference in New Issue
Block a user