688 lines
34 KiB
C#
688 lines
34 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Server;
|
|
using DataValue = Opc.Ua.DataValue;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
|
|
/// <summary>
|
|
/// The node-manager-wide Warm standby flags (Gitea #717, spec §4.4–§4.6). One instance per server. Under
|
|
/// <c>Unset</c>/<c>None</c> <see cref="WarmMode"/> is false and nothing ever sets a flag, so every reader sees
|
|
/// today's behaviour. Under <c>Warm</c> the node starts Standby (all flags set) until the redundancy layer
|
|
/// promotes it.
|
|
/// </summary>
|
|
internal sealed class WarmStandbyState
|
|
{
|
|
private volatile bool _dataProjected;
|
|
private volatile bool _alarmsSuppressed;
|
|
|
|
/// <summary>Initializes the state.</summary>
|
|
/// <param name="warmMode">Whether this server runs the Warm role contract.</param>
|
|
public WarmStandbyState(bool warmMode)
|
|
{
|
|
WarmMode = warmMode;
|
|
_dataProjected = warmMode;
|
|
_alarmsSuppressed = warmMode;
|
|
Delivery = warmMode ? new FirstDeliveryRecord(standby: true) : null;
|
|
}
|
|
|
|
/// <summary>The not-Warm state (no projection, no suppression, no decision record).</summary>
|
|
public static WarmStandbyState Off { get; } = new(false);
|
|
|
|
/// <summary>Whether this server runs the Warm role contract.</summary>
|
|
public bool WarmMode { get; }
|
|
|
|
/// <summary>Ordinary-tag reads/samples project <c>BadOutOfService</c>; writes and Part 9 methods are refused.</summary>
|
|
public bool DataProjected
|
|
{
|
|
get => _dataProjected;
|
|
set => _dataProjected = WarmMode && value;
|
|
}
|
|
|
|
/// <summary>New alarm condition events are not delivered (still stamped).</summary>
|
|
public bool AlarmsSuppressed
|
|
{
|
|
get => _alarmsSuppressed;
|
|
set => _alarmsSuppressed = WarmMode && value;
|
|
}
|
|
|
|
/// <summary>Whether a Warm Standby must refuse a write or a Part 9 method (owner answers Q1/Q4).</summary>
|
|
public bool RefusesMutations => WarmMode && _dataProjected;
|
|
|
|
/// <summary>The first-delivery decision record; null when not Warm.</summary>
|
|
public FirstDeliveryRecord? Delivery { get; }
|
|
|
|
/// <summary>The refusal returned to a write or a Part 9 method on a Warm Standby.</summary>
|
|
public static ServiceResult StandbyRefusal(string what) => new(StatusCodes.BadInvalidState,
|
|
new LocalizedText($"This server is the Warm redundancy standby; {what} on the active server (the one with the higher ServiceLevel)."));
|
|
}
|
|
|
|
/// <summary>
|
|
/// The ordinary-tag marker (spec §4.6 item 1): set on <see cref="MonitoredItemNotification.Message"/>, a helper
|
|
/// reference the binary encoder never writes and the SDK's per-delivery <c>CoreUtils.Clone</c> copies
|
|
/// (pinned by <c>WarmStandbySdkFieldContractTests</c>). Valid only for the notification whose
|
|
/// <see cref="ClientHandle"/> and <see cref="Value"/> it captured, so a stale marker left on a pooled payload
|
|
/// (2.0.1's <c>Initialize()</c> does not clear the helper) fails <see cref="Matches"/>.
|
|
/// </summary>
|
|
/// <remarks>Derives from <see cref="NotificationMessage"/> only because that is the helper's declared type.</remarks>
|
|
internal sealed class OrdinaryTagMarker : NotificationMessage
|
|
{
|
|
/// <summary>Initializes the marker.</summary>
|
|
/// <param name="clientHandle">The notification's client handle when it was built.</param>
|
|
/// <param name="value">The notification's final value when it was built.</param>
|
|
public OrdinaryTagMarker(uint clientHandle, DataValue value)
|
|
{
|
|
ClientHandle = clientHandle;
|
|
Value = value;
|
|
}
|
|
|
|
/// <summary>The client handle captured at build time.</summary>
|
|
public uint ClientHandle { get; }
|
|
|
|
/// <summary>The value captured at build time.</summary>
|
|
public DataValue Value { get; }
|
|
|
|
/// <summary>Whether <paramref name="n"/> is the notification this marker was made for.</summary>
|
|
/// <param name="n">A delivered notification.</param>
|
|
/// <returns>True for a match on client handle and value.</returns>
|
|
public bool Matches(MonitoredItemNotification n) => n.ClientHandle == ClientHandle && Equals(n.Value, Value);
|
|
|
|
/// <summary>Whether <paramref name="n"/> carries a valid ordinary-tag marker.</summary>
|
|
/// <param name="n">A delivered notification.</param>
|
|
/// <returns>True when it is an ordinary-tag notification.</returns>
|
|
public static bool IsOrdinaryTag(MonitoredItemNotification n) => n.Message is OrdinaryTagMarker m && m.Matches(n);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The per-message first-delivery decision (spec §4.6 item 2, D4), keyed by
|
|
/// <c>(SubscriptionId, SequenceNumber)</c> — never by object: SDK 2.0.1 hands every Publish and Republish a fresh
|
|
/// clone of the cached message. The first delivery of a sequence number records Active or Standby; every later
|
|
/// delivery (Republish included) applies the recorded decision. One lock orders a decision against a role flip;
|
|
/// it is never held across an await or a projection.
|
|
/// </summary>
|
|
internal sealed class FirstDeliveryRecord
|
|
{
|
|
/// <summary>Recorded messages kept per subscription beyond what <c>AvailableSequenceNumbers</c> prunes.</summary>
|
|
internal const int MaxPerSubscription = 1024;
|
|
|
|
/// <summary>Subscriptions kept before the least-recently-used one is dropped (dead subscriptions).</summary>
|
|
internal const int MaxSubscriptions = 8192;
|
|
|
|
private readonly object _gate = new();
|
|
private readonly Dictionary<uint, SubscriptionRecord> _subscriptions = new();
|
|
private bool _standby;
|
|
private long _touch;
|
|
|
|
/// <summary>Initializes the record.</summary>
|
|
/// <param name="standby">The initial delivery state (a Warm node boots Standby).</param>
|
|
public FirstDeliveryRecord(bool standby) => _standby = standby;
|
|
|
|
/// <summary>Test seam: runs inside the lock after the decision is read and before it is recorded.</summary>
|
|
internal Action? DecisionBarrier { get; set; }
|
|
|
|
/// <summary>The current first-delivery state.</summary>
|
|
public bool Standby
|
|
{
|
|
get { lock (_gate) return _standby; }
|
|
}
|
|
|
|
/// <summary>Flips the first-delivery state (the D4 boundary). Waits for a decision in progress.</summary>
|
|
/// <param name="standby">Whether later first deliveries are Standby.</param>
|
|
public void SetStandby(bool standby)
|
|
{
|
|
lock (_gate) _standby = standby;
|
|
}
|
|
|
|
/// <summary>The decision for one delivery: the recorded one, or (first delivery) the current state, recorded.</summary>
|
|
/// <param name="subscriptionId">The subscription.</param>
|
|
/// <param name="sequenceNumber">The message's sequence number.</param>
|
|
/// <returns>True when the delivery must be projected (Standby).</returns>
|
|
public bool Decide(uint subscriptionId, uint sequenceNumber)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (!_subscriptions.TryGetValue(subscriptionId, out var sub))
|
|
{
|
|
if (_subscriptions.Count >= MaxSubscriptions) EvictLeastRecentlyUsed();
|
|
_subscriptions[subscriptionId] = sub = new SubscriptionRecord();
|
|
}
|
|
|
|
sub.Touched = ++_touch;
|
|
if (sub.Decisions.TryGetValue(sequenceNumber, out var recorded)) return recorded;
|
|
var standby = _standby;
|
|
DecisionBarrier?.Invoke();
|
|
sub.Decisions[sequenceNumber] = standby;
|
|
sub.Order.Enqueue(sequenceNumber);
|
|
while (sub.Order.Count > MaxPerSubscription && sub.Order.TryDequeue(out var oldest)) sub.Decisions.Remove(oldest);
|
|
return standby;
|
|
}
|
|
}
|
|
|
|
/// <summary>Drops the decisions of messages the subscription no longer retains (they can never be republished).</summary>
|
|
/// <param name="subscriptionId">The subscription the Publish response belongs to.</param>
|
|
/// <param name="available">The response's <c>AvailableSequenceNumbers</c>.</param>
|
|
/// <param name="justDelivered">The sequence number just delivered (kept: it becomes available for Republish).</param>
|
|
public void Prune(uint subscriptionId, IReadOnlyCollection<uint> available, uint justDelivered)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (!_subscriptions.TryGetValue(subscriptionId, out var sub)) return;
|
|
var keep = new HashSet<uint>(available) { justDelivered };
|
|
var kept = new Queue<uint>();
|
|
while (sub.Order.TryDequeue(out var seq))
|
|
{
|
|
if (keep.Contains(seq)) kept.Enqueue(seq);
|
|
else sub.Decisions.Remove(seq);
|
|
}
|
|
|
|
sub.Order.Clear();
|
|
foreach (var seq in kept) sub.Order.Enqueue(seq);
|
|
}
|
|
}
|
|
|
|
/// <summary>Drops every record of subscriptions not in <paramref name="live"/>.</summary>
|
|
/// <param name="live">The ids of live subscriptions.</param>
|
|
public void SweepDead(IReadOnlySet<uint> live)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
foreach (var id in _subscriptions.Keys.Where(id => !live.Contains(id)).ToList()) _subscriptions.Remove(id);
|
|
}
|
|
}
|
|
|
|
/// <summary>Recorded decisions (test observation).</summary>
|
|
internal int Count
|
|
{
|
|
get { lock (_gate) return _subscriptions.Values.Sum(s => s.Decisions.Count); }
|
|
}
|
|
|
|
/// <summary>Recorded subscriptions (test observation).</summary>
|
|
internal int SubscriptionCount
|
|
{
|
|
get { lock (_gate) return _subscriptions.Count; }
|
|
}
|
|
|
|
private void EvictLeastRecentlyUsed()
|
|
{
|
|
var victim = _subscriptions.MinBy(kv => kv.Value.Touched).Key;
|
|
_subscriptions.Remove(victim);
|
|
}
|
|
|
|
private sealed class SubscriptionRecord
|
|
{
|
|
public readonly Dictionary<uint, bool> Decisions = new();
|
|
public readonly Queue<uint> Order = new();
|
|
public long Touched;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Rewrites a Standby delivery (spec §4.6): every marked ordinary-tag notification whose status is not Bad becomes
|
|
/// <c>BadOutOfService</c>/null with its server timestamp kept. Builds new objects; the message handed in (the SDK's
|
|
/// fresh per-delivery clone) and, a fortiori, the SDK's cached copy are never mutated.
|
|
/// </summary>
|
|
internal static class StandbyNotificationRewriter
|
|
{
|
|
/// <summary>Projects <paramref name="message"/>, or returns it unchanged when nothing needs rewriting.</summary>
|
|
/// <param name="message">A delivered message.</param>
|
|
/// <param name="rewritten">The number of notifications rewritten.</param>
|
|
/// <returns>The message to deliver.</returns>
|
|
public static NotificationMessage Project(NotificationMessage message, out int rewritten)
|
|
{
|
|
rewritten = 0;
|
|
if (message is null || message.NotificationData.Count == 0) return message!;
|
|
|
|
var data = new List<ExtensionObject>(message.NotificationData.Count);
|
|
var changed = false;
|
|
for (var i = 0; i < message.NotificationData.Count; i++)
|
|
{
|
|
var eo = message.NotificationData[i];
|
|
if (eo.TryGetValue<DataChangeNotification>(out var dcn) && dcn is not null)
|
|
{
|
|
List<MonitoredItemNotification>? items = null;
|
|
for (var j = 0; j < dcn.MonitoredItems.Count; j++)
|
|
{
|
|
var n = dcn.MonitoredItems[j];
|
|
if (OrdinaryTagMarker.IsOrdinaryTag(n) && !StatusCode.IsBad(n.Value.StatusCode))
|
|
{
|
|
items ??= CopyPrefix(dcn, j);
|
|
items.Add(new MonitoredItemNotification
|
|
{
|
|
ClientHandle = n.ClientHandle,
|
|
Value = new DataValue(Variant.Null, StatusCodes.BadOutOfService, DateTimeUtc.MinValue, n.Value.ServerTimestamp),
|
|
});
|
|
rewritten++;
|
|
}
|
|
else
|
|
{
|
|
items?.Add(n);
|
|
}
|
|
}
|
|
|
|
if (items is not null)
|
|
{
|
|
changed = true;
|
|
data.Add(new ExtensionObject(new DataChangeNotification { MonitoredItems = items, DiagnosticInfos = dcn.DiagnosticInfos }));
|
|
continue;
|
|
}
|
|
}
|
|
|
|
data.Add(eo);
|
|
}
|
|
|
|
if (!changed) return message;
|
|
return new NotificationMessage { SequenceNumber = message.SequenceNumber, PublishTime = message.PublishTime, NotificationData = data };
|
|
}
|
|
|
|
private static List<MonitoredItemNotification> CopyPrefix(DataChangeNotification dcn, int count)
|
|
{
|
|
var list = new List<MonitoredItemNotification>(dcn.MonitoredItems.Count);
|
|
for (var k = 0; k < count; k++) list.Add(dcn.MonitoredItems[k]);
|
|
return list;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// A sampled data-change item for an ordinary-tag <c>Value</c> (spec §4.6 item 1): after the SDK's own per-value
|
|
/// publish (so the timestamp filter has run) it marks each notification it produced with an
|
|
/// <see cref="OrdinaryTagMarker"/>. Everything else is the SDK's <see cref="MonitoredItem"/>.
|
|
/// </summary>
|
|
internal sealed class OrdinaryTagMonitoredItem : MonitoredItem
|
|
{
|
|
/// <summary>Initializes the item exactly as <see cref="MonitoredNodeMonitoredItemManager"/> does.</summary>
|
|
public OrdinaryTagMonitoredItem(IServerInternal server, IAsyncNodeManager nodeManager, NodeHandle handle, uint subscriptionId,
|
|
uint id, MonitoredItemCreateRequest request, DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn,
|
|
MonitoringFilter? filter, Opc.Ua.Range? range, double samplingInterval, uint queueSize, bool durable)
|
|
: base(server, nodeManager, handle, subscriptionId, id, request.ItemToMonitor, diagnosticsMasks, timestampsToReturn,
|
|
request.MonitoringMode, request.RequestedParameters.ClientHandle, filter, filter, range, samplingInterval, queueSize,
|
|
request.RequestedParameters.DiscardOldest, 0, durable)
|
|
{
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public override bool Publish(OperationContext context, Queue<MonitoredItemNotification> notifications,
|
|
Queue<DiagnosticInfo> diagnostics, uint maxNotificationsPerPublish, ILogger logger)
|
|
{
|
|
var local = new Queue<MonitoredItemNotification>();
|
|
var localDiagnostics = new Queue<DiagnosticInfo>();
|
|
var more = base.Publish(context, local, localDiagnostics, maxNotificationsPerPublish, logger);
|
|
while (local.Count > 0)
|
|
{
|
|
var n = local.Dequeue();
|
|
n.Message = new OrdinaryTagMarker(n.ClientHandle, n.Value);
|
|
notifications.Enqueue(n);
|
|
if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
|
|
}
|
|
|
|
while (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
|
|
return more;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Installs <see cref="OrdinaryTagMonitoredItem"/> for ordinary-tag (<see cref="EquipmentVariableState"/>)
|
|
/// <c>Value</c> items only. Re-implements <see cref="IMonitoredItemManager.CreateMonitoredItem"/> on the SDK's
|
|
/// public, non-sealed manager, so <c>CustomNodeManager2</c>'s <c>is MonitoredNodeMonitoredItemManager</c> checks and
|
|
/// its internal lifecycle interface keep working (T0c; the 2.0.1 <c>MonitoredItemFactory</c> hook exists only on
|
|
/// <c>AsyncCustomNodeManager</c>). Installed only under Warm; <c>Unset</c>/<c>None</c> keep the SDK's manager.
|
|
/// </summary>
|
|
internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, IServerInternal server, OtOpcUaNodeManager owner, bool warmMode)
|
|
: MonitoredNodeMonitoredItemManager(nodeManager, server), IMonitoredItemManager
|
|
{
|
|
/// <inheritdoc />
|
|
ISampledDataChangeMonitoredItem IMonitoredItemManager.CreateMonitoredItem(IServerInternal server, IAsyncNodeManager nodeManager,
|
|
ServerSystemContext context, NodeHandle handle, uint subscriptionId, double publishingInterval,
|
|
DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn, MonitoredItemCreateRequest itemToCreate,
|
|
Opc.Ua.Range euRange, MonitoringFilter filterToUse, double samplingInterval, uint revisedQueueSize, bool createDurable,
|
|
MonitoredItemIdFactory monitoredItemIdFactory, Func<ISystemContext, NodeHandle, NodeState, NodeState> addNodeToComponentCache)
|
|
{
|
|
var projected = owner.IsProjectedItem(handle.NodeId) && itemToCreate.ItemToMonitor.AttributeId == Attributes.Value;
|
|
if (!projected && (!warmMode || handle.Node is not EquipmentVariableState || itemToCreate.ItemToMonitor.AttributeId != Attributes.Value))
|
|
{
|
|
return CreateMonitoredItem(server, nodeManager, context, handle, subscriptionId, publishingInterval, diagnosticsMasks,
|
|
timestampsToReturn, itemToCreate, euRange, filterToUse, samplingInterval, revisedQueueSize, createDurable,
|
|
monitoredItemIdFactory, addNodeToComponentCache);
|
|
}
|
|
IProjectedDemandLease? demand = null;
|
|
ProjectedValueWrite? initialSample = null;
|
|
ProjectedVariableDefinition? definition = null;
|
|
if (projected && !owner.TryAcquireProjectedItem(context, handle.NodeId, publishingInterval, out demand, out initialSample, out definition))
|
|
throw new ServiceResultException(StatusCodes.BadUserAccessDenied);
|
|
|
|
uint? reservedId = null;
|
|
try
|
|
{
|
|
// Mirrors MonitoredNodeMonitoredItemManager.CreateMonitoredItem in exact tagged 2.0.1, swapping only the item type.
|
|
var cachedNode = addNodeToComponentCache(context, handle, handle.Node);
|
|
if (!MonitoredNodes.TryGetValue(handle.Node.NodeId, out var monitoredNode))
|
|
{
|
|
MonitoredNodes[handle.Node.NodeId] = monitoredNode = new MonitoredNode2(nodeManager, server, cachedNode,
|
|
nodeManager.IsMultipleEventConsumerNode(cachedNode.NodeId));
|
|
}
|
|
|
|
handle.Node = monitoredNode.Node;
|
|
handle.MonitoredNode = monitoredNode;
|
|
uint id;
|
|
do
|
|
{
|
|
id = monitoredItemIdFactory.GetNextId();
|
|
}
|
|
while (!MonitoredItems.TryAdd(id, null!));
|
|
reservedId = id;
|
|
|
|
ISampledDataChangeMonitoredItem item = projected
|
|
? new ProjectedMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks,
|
|
timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable,
|
|
owner, demand!, initialSample, definition!)
|
|
: new OrdinaryTagMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks,
|
|
timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable);
|
|
monitoredNode.Add((IDataChangeMonitoredItem2)item);
|
|
if (item is ProjectedMonitoredItem projectedItem) owner.ObserveCurrentProjectedSource(projectedItem);
|
|
MonitoredItems[id] = item;
|
|
demand = null;
|
|
return item;
|
|
}
|
|
catch
|
|
{
|
|
if (reservedId is { } id) MonitoredItems.TryRemove(id, out _);
|
|
demand?.Dispose();
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>A projected item retains its original caller, item lifetime and source proof.</summary>
|
|
internal sealed class ProjectedMonitoredItem : MonitoredItem
|
|
{
|
|
private readonly OtOpcUaNodeManager _owner;
|
|
private IProjectedDemandLease? _demand;
|
|
private ProjectedVariableDefinition? _definition;
|
|
private readonly NodeId _nodeId;
|
|
private sealed class SourceBinding(IProjectedSamplePublicationProof proof)
|
|
{
|
|
private readonly object _sync = new();
|
|
private IProjectedSamplePublicationProof? _proof = proof;
|
|
private readonly List<WeakReference<SampleEvidence>> _evidence = [];
|
|
public IProjectedSamplePublicationProof? Proof { get { lock (_sync) return _proof; } }
|
|
public bool IsValid => Proof is { IsSourceValid: true };
|
|
public SampleEvidence? Capture(IProjectedSamplePublicationProof sample, DataAgeBounds age, long timestamp)
|
|
{
|
|
lock (_sync)
|
|
{
|
|
if (_proof is null) return null;
|
|
_evidence.RemoveAll(entry => !entry.TryGetTarget(out _));
|
|
if (_evidence.Count >= 4096) return null;
|
|
var evidence = new SampleEvidence(this, sample, age, timestamp);
|
|
_evidence.Add(new(evidence));
|
|
return evidence;
|
|
}
|
|
}
|
|
public void Retire()
|
|
{
|
|
lock (_sync)
|
|
{
|
|
_proof = null;
|
|
foreach (var entry in _evidence) if (entry.TryGetTarget(out var evidence)) evidence.Clear();
|
|
_evidence.Clear();
|
|
}
|
|
}
|
|
}
|
|
private sealed record Candidate(ProjectedValueWrite Sample, Variant Value, SourceBinding Binding, long Bytes, IDisposable Charge);
|
|
private sealed class SampleEvidence(SourceBinding binding, IProjectedSamplePublicationProof proof, DataAgeBounds age, long receivedTimestamp)
|
|
{
|
|
private IProjectedSamplePublicationProof? _proof = proof;
|
|
public SourceBinding Binding => binding;
|
|
public IProjectedSamplePublicationProof? Proof => Volatile.Read(ref _proof);
|
|
public DataAgeBounds Age => age;
|
|
public long ReceivedTimestamp => receivedTimestamp;
|
|
public void Clear() => Interlocked.Exchange(ref _proof, null);
|
|
}
|
|
private const int MaxCandidates = 1024;
|
|
private const long MaxCandidateBytes = 1024 * 1024;
|
|
private readonly object _bindingSync = new();
|
|
private readonly List<Candidate> _candidates = [];
|
|
private long _candidateBytes;
|
|
private bool _needsSnapshot;
|
|
private int _snapshotRequested;
|
|
private SourceBinding? _binding;
|
|
private int _retired;
|
|
private int _released;
|
|
|
|
public ProjectedMonitoredItem(IServerInternal server, IAsyncNodeManager nodeManager, NodeHandle handle, uint subscriptionId,
|
|
uint id, MonitoredItemCreateRequest request, DiagnosticsMasks masks, TimestampsToReturn timestamps,
|
|
MonitoringFilter? filter, Opc.Ua.Range? range, double samplingInterval, uint queueSize, bool durable,
|
|
OtOpcUaNodeManager owner, IProjectedDemandLease demand, ProjectedValueWrite? initialSample, ProjectedVariableDefinition definition)
|
|
: base(server, nodeManager, handle, subscriptionId, id, request.ItemToMonitor, masks, timestamps,
|
|
request.MonitoringMode, request.RequestedParameters.ClientHandle, filter, filter, range, samplingInterval, queueSize,
|
|
request.RequestedParameters.DiscardOldest, 0, durable)
|
|
{
|
|
_owner = owner; _demand = demand; _definition = definition; _nodeId = handle.NodeId;
|
|
if (initialSample is not null)
|
|
{
|
|
_binding = new(initialSample.Proof);
|
|
AddCandidate(initialSample, _binding);
|
|
}
|
|
}
|
|
|
|
internal NodeId ProjectedNodeId => _nodeId;
|
|
internal bool ObserveSample(ProjectedValueWrite sample)
|
|
{
|
|
lock (_bindingSync)
|
|
{
|
|
var original = _binding;
|
|
var sameSource = original is not null && ReferenceEquals(original.Proof?.SourceIdentity, sample.Proof.SourceIdentity);
|
|
if (!sameSource || (_needsSnapshot && sample.IsCompleteSnapshot))
|
|
{
|
|
original?.Retire();
|
|
_binding = null;
|
|
if (Volatile.Read(ref _retired) != 0 || !sample.IsCompleteSnapshot || !sample.Proof.IsSourceValid || _demand?.IsValid != true)
|
|
{ _needsSnapshot = true; return true; }
|
|
// Pinned SDK resets the entire data queue and last value across this transition.
|
|
var mode = MonitoringMode;
|
|
if (mode != MonitoringMode.Disabled)
|
|
{
|
|
SetMonitoringMode(MonitoringMode.Disabled);
|
|
SetMonitoringMode(mode);
|
|
}
|
|
ClearCandidates(); _needsSnapshot = false;
|
|
Interlocked.Exchange(ref _snapshotRequested, 0);
|
|
_binding = new(sample.Proof);
|
|
}
|
|
if (_binding is null) { _needsSnapshot = true; return true; }
|
|
if (_candidates.Any(candidate => ReferenceEquals(candidate.Sample, sample))) return false;
|
|
return !AddCandidate(sample, _binding);
|
|
}
|
|
}
|
|
private bool AddCandidate(ProjectedValueWrite sample, SourceBinding binding)
|
|
{
|
|
long bytes = 256;
|
|
if (sample.Snapshot.Value is string text) bytes += 2L * text.Length;
|
|
else if (sample.Snapshot.Value is Array array)
|
|
{
|
|
if (array.Rank != 1 || array.Length > 65_536) { _needsSnapshot = true; return false; }
|
|
bytes += 64L * array.Length;
|
|
if (array is string[] strings) foreach (var item in strings) bytes += 2L * (item?.Length ?? 0);
|
|
}
|
|
if (bytes > MaxCandidateBytes || _candidates.Count >= MaxCandidates || _candidateBytes > MaxCandidateBytes - bytes)
|
|
{ _needsSnapshot = true; return false; }
|
|
if (!_owner.ProjectedCandidateBudget.TryReserve(bytes, out var charge) || charge is null)
|
|
{ _needsSnapshot = true; return false; }
|
|
try
|
|
{
|
|
var value = SdkValueBoundary.FromClr(sample.Snapshot.Value,
|
|
_definition?.Metadata.ValueKind == DataValueKind.Array && _definition.Metadata.ArrayElementKind == DataValueKind.UInt8);
|
|
_candidates.Add(new(sample, value, binding, bytes, charge));
|
|
_candidateBytes += bytes;
|
|
return true;
|
|
}
|
|
catch (ArgumentException) { charge.Dispose(); _needsSnapshot = true; return false; }
|
|
}
|
|
private void ClearCandidates()
|
|
{
|
|
foreach (var candidate in _candidates) candidate.Charge.Dispose();
|
|
_candidates.Clear(); _candidateBytes = 0;
|
|
}
|
|
internal void RequestBaseline()
|
|
{
|
|
if (Volatile.Read(ref _retired) != 0 || _demand?.IsValid != true || Interlocked.CompareExchange(ref _snapshotRequested, 1, 0) != 0) return;
|
|
if (_demand is not { } demand || !_owner.RequestProjectedSnapshot(demand)) Interlocked.Exchange(ref _snapshotRequested, 0);
|
|
}
|
|
private bool IsCurrentCandidate(SourceBinding? binding, SampleEvidence? candidate)
|
|
{
|
|
if (candidate is null || !ReferenceEquals(candidate.Binding, binding) || !IsCurrentBinding(binding) ||
|
|
_demand is not { } demand || demand.MaximumSampleAge <= TimeSpan.Zero) return false;
|
|
if (candidate.Proof is not { IsValid: true } proof) { RequestBaseline(); return false; }
|
|
try
|
|
{
|
|
var age = candidate.Age.Advance(proof.Clock.GetElapsedTime(candidate.ReceivedTimestamp, proof.Clock.GetTimestamp()));
|
|
if (age.IsFresh(demand.MaximumSampleAge)) return proof.IsValid && IsCurrentBinding(binding);
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or OverflowException) { }
|
|
RequestBaseline();
|
|
return false;
|
|
}
|
|
private bool IsCurrentBinding(SourceBinding? binding) => Volatile.Read(ref _retired) == 0 && _demand is { IsValid: true } &&
|
|
binding is { IsValid: true } && _definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition);
|
|
internal bool IsCurrent => IsCurrentBinding(Volatile.Read(ref _binding));
|
|
internal bool HasCurrentDemand => Volatile.Read(ref _retired) == 0 && _demand is { IsValid: true } &&
|
|
_definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition);
|
|
internal void Retire()
|
|
{
|
|
Interlocked.Exchange(ref _retired, 1);
|
|
lock (_bindingSync) { _binding?.Retire(); _binding = null; ClearCandidates(); }
|
|
_definition = null;
|
|
if (Interlocked.Exchange(ref _released, 1) == 0) Interlocked.Exchange(ref _demand, null)?.Dispose();
|
|
}
|
|
public override bool Publish(OperationContext context, Queue<MonitoredItemNotification> notifications,
|
|
Queue<DiagnosticInfo> diagnostics, uint maximum, ILogger logger)
|
|
{
|
|
var captured = Volatile.Read(ref _binding);
|
|
var local = new Queue<MonitoredItemNotification>();
|
|
var localDiagnostics = new Queue<DiagnosticInfo>();
|
|
var more = base.Publish(context, local, localDiagnostics, maximum, logger);
|
|
while (local.Count > 0)
|
|
{
|
|
var notification = local.Dequeue();
|
|
SampleEvidence? evidence = null;
|
|
lock (_bindingSync)
|
|
{
|
|
var matching = _candidates.Where(candidate => ReferenceEquals(candidate.Binding, captured) &&
|
|
candidate.Value.Equals(notification.Value.WrappedValue) && candidate.Sample.Snapshot.StatusCode == notification.Value.StatusCode.Code).Take(2).ToArray();
|
|
if (matching.Length == 1)
|
|
{
|
|
var matched = matching[0]; _candidates.Remove(matched); _candidateBytes -= matched.Bytes;
|
|
evidence = matched.Binding.Capture(matched.Sample.Proof, matched.Sample.OriginAgeBounds, matched.Sample.ReceivedTimestamp);
|
|
matched.Charge.Dispose();
|
|
}
|
|
else _needsSnapshot = true;
|
|
}
|
|
if (evidence is null) RequestBaseline();
|
|
var originalSample = evidence;
|
|
notification.Message = new ProjectedNotificationMarker(notification.ClientHandle, notification.Value, () => IsCurrentCandidate(captured, originalSample));
|
|
notifications.Enqueue(notification);
|
|
if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
|
|
}
|
|
while (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
|
|
return more;
|
|
}
|
|
}
|
|
|
|
/// <summary>The <see cref="ZB.MOM.WW.OtOpcUa.Commons.OpcUa.IStandbyProjection"/> a Warm server hands the redundancy layer.</summary>
|
|
internal sealed class SdkStandbyProjection(OtOpcUaNodeManager nodeManager, WarmStandbyState state)
|
|
: ZB.MOM.WW.OtOpcUa.Commons.OpcUa.IStandbyProjection
|
|
{
|
|
/// <inheritdoc />
|
|
public void SetDataProjection(bool projected) => state.DataProjected = projected;
|
|
|
|
/// <inheritdoc />
|
|
public void SetStandbyDelivery(bool standby) => state.Delivery?.SetStandby(standby);
|
|
|
|
/// <inheritdoc />
|
|
public void SetAlarmSuppression(bool suppressed) => state.AlarmsSuppressed = suppressed;
|
|
|
|
/// <inheritdoc />
|
|
public int QueueCurrentToLiveItems(bool projected) => nodeManager.QueueCurrentToLiveItems(projected);
|
|
|
|
/// <inheritdoc />
|
|
public int RefreshAllEventItems() => nodeManager.RefreshAllEventItems();
|
|
}
|
|
|
|
/// <summary>Captured per-notification proof. A stale pooled helper is treated as denied.</summary>
|
|
internal sealed class ProjectedNotificationMarker : NotificationMessage
|
|
{
|
|
private readonly uint _clientHandle;
|
|
private readonly byte[]? _fingerprint;
|
|
private readonly Func<bool> _authorize;
|
|
public ProjectedNotificationMarker(uint clientHandle, DataValue value, Func<bool> authorize)
|
|
{ _clientHandle = clientHandle; _fingerprint = Fingerprint(value); _authorize = authorize; }
|
|
public bool Permits(MonitoredItemNotification notification)
|
|
{
|
|
if (notification.ClientHandle != _clientHandle || _fingerprint is null) return false;
|
|
try
|
|
{
|
|
var current = Fingerprint(notification.Value);
|
|
return current is not null && System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(_fingerprint, current) && _authorize();
|
|
}
|
|
catch { return false; }
|
|
}
|
|
private static byte[]? Fingerprint(DataValue value)
|
|
{
|
|
try
|
|
{
|
|
var payload = SdkValueBoundary.ToClr(value.WrappedValue);
|
|
if (payload is Array array)
|
|
{
|
|
if (array.Rank != 1 || array.Length > 65_536 || array.GetType().GetElementType() is not { } type ||
|
|
type != typeof(bool) && type != typeof(sbyte) && type != typeof(byte) && type != typeof(short) && type != typeof(ushort) &&
|
|
type != typeof(int) && type != typeof(uint) && type != typeof(long) && type != typeof(ulong) &&
|
|
type != typeof(float) && type != typeof(double) && type != typeof(string) && type != typeof(DateTime)) return null;
|
|
}
|
|
else if (payload is not (null or bool or sbyte or byte or short or ushort or int or uint or long or ulong or float or double or string or DateTime or Guid) ||
|
|
payload is string { Length: > 524288 }) return null;
|
|
var encoded = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new
|
|
{
|
|
Type = payload?.GetType().FullName, Value = payload, Status = value.StatusCode.Code,
|
|
Source = value.SourceTimestamp.ToString(), Server = value.ServerTimestamp.ToString()
|
|
});
|
|
return encoded.Length <= 1024 * 1024 ? System.Security.Cryptography.SHA256.HashData(encoded) : null;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NotSupportedException or System.Text.Json.JsonException)
|
|
{ return null; }
|
|
}
|
|
}
|
|
|
|
/// <summary>Rechecks captured projected notification authority for every delivery and retransmission.</summary>
|
|
internal static class ProjectedNotificationRewriter
|
|
{
|
|
public static NotificationMessage Project(NotificationMessage message, bool republish)
|
|
{
|
|
var changed = false;
|
|
var payloads = new List<ExtensionObject>(message.NotificationData.Count);
|
|
foreach (var payload in message.NotificationData)
|
|
{
|
|
if (!payload.TryGetValue<DataChangeNotification>(out var change) || change is null)
|
|
{ payloads.Add(payload); continue; }
|
|
var items = new List<MonitoredItemNotification>(change.MonitoredItems.Count);
|
|
var changedPayload = false;
|
|
foreach (var item in change.MonitoredItems)
|
|
{
|
|
if (item.Message is ProjectedNotificationMarker marker && !marker.Permits(item))
|
|
{
|
|
items.Add(new MonitoredItemNotification { ClientHandle = item.ClientHandle,
|
|
Value = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, item.Value.ServerTimestamp) });
|
|
changedPayload = true;
|
|
}
|
|
else items.Add(item);
|
|
}
|
|
if (changedPayload)
|
|
{
|
|
changed = true;
|
|
payloads.Add(new ExtensionObject(new DataChangeNotification { MonitoredItems = items, DiagnosticInfos = change.DiagnosticInfos }));
|
|
}
|
|
else payloads.Add(payload);
|
|
}
|
|
return changed ? new NotificationMessage { SequenceNumber = message.SequenceNumber, PublishTime = message.PublishTime, NotificationData = payloads } : message;
|
|
}
|
|
}
|