976 lines
50 KiB
C#
976 lines
50 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;
|
|
ISampledDataChangeMonitoredItem? constructed = null;
|
|
MonitoredNode2? registeredNode = null;
|
|
var cacheAdded = false;
|
|
var createdNode = false;
|
|
try
|
|
{
|
|
// Mirrors MonitoredNodeMonitoredItemManager.CreateMonitoredItem in exact tagged 2.0.1, swapping only the item type.
|
|
var cachedNode = addNodeToComponentCache(context, handle, handle.Node);
|
|
cacheAdded = true;
|
|
if (!MonitoredNodes.TryGetValue(handle.Node.NodeId, out var monitoredNode))
|
|
{
|
|
MonitoredNodes[handle.Node.NodeId] = monitoredNode = new MonitoredNode2(nodeManager, server, cachedNode,
|
|
nodeManager.IsMultipleEventConsumerNode(cachedNode.NodeId));
|
|
createdNode = true;
|
|
}
|
|
|
|
handle.Node = monitoredNode.Node;
|
|
handle.MonitoredNode = monitoredNode;
|
|
registeredNode = monitoredNode;
|
|
uint id;
|
|
do
|
|
{
|
|
id = monitoredItemIdFactory.GetNextId();
|
|
}
|
|
while (!MonitoredItems.TryAdd(id, null!));
|
|
reservedId = id;
|
|
|
|
ISampledDataChangeMonitoredItem item = constructed = 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 _);
|
|
if (constructed is IDataChangeMonitoredItem2 data && registeredNode is not null)
|
|
{
|
|
try { registeredNode.Remove(data); } catch (Exception) { }
|
|
}
|
|
if (createdNode && registeredNode is not null && !registeredNode.HasMonitoredItems &&
|
|
MonitoredNodes.TryGetValue(registeredNode.Node.NodeId, out var currentNode) && ReferenceEquals(currentNode, registeredNode) &&
|
|
MonitoredNodes.TryRemove(registeredNode.Node.NodeId, out _))
|
|
{
|
|
try { registeredNode.Dispose(); } catch (Exception) { }
|
|
}
|
|
if (cacheAdded)
|
|
{
|
|
try { owner.ReleaseFailedComponentCache(context, handle); } catch (Exception) { }
|
|
}
|
|
if (constructed is IDisposable disposable)
|
|
{
|
|
try { disposable.Dispose(); } catch (Exception) { }
|
|
}
|
|
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;
|
|
internal 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);
|
|
internal 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 SampleEvidence? _latestEvidence;
|
|
private SampleEvidence? _reportedLoss;
|
|
private LossControl? _queuedLoss;
|
|
internal Action? AfterLossDequeueForTests;
|
|
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);
|
|
_latestEvidence = new SampleEvidence(_binding, initialSample.Proof, initialSample.OriginAgeBounds, initialSample.ReceivedTimestamp);
|
|
}
|
|
}
|
|
|
|
internal NodeId ProjectedNodeId => _nodeId;
|
|
internal bool ObserveSample(ProjectedValueWrite sample)
|
|
{
|
|
lock (_bindingSync)
|
|
{
|
|
var original = _binding;
|
|
// A new physical attempt may use the same logical source identity, but an
|
|
// ended attempt's captured evidence must not keep the SDK queue bound to it.
|
|
var sameSource = original is { IsValid: true } && ReferenceEquals(original.Proof?.SourceIdentity, sample.Proof.SourceIdentity);
|
|
if (sample.IsCompleteSnapshot && sameSource && !_needsSnapshot)
|
|
{
|
|
var matching = _candidates.FirstOrDefault(candidate => ReferenceEquals(candidate.Binding, original) &&
|
|
SameAcquisition(candidate.Sample, sample));
|
|
if (matching is not null)
|
|
{
|
|
// A queued notification keeps its original evidence. If it has expired,
|
|
// a separately fresh observation must start a new binding and queue.
|
|
if (FreshForDemand(matching.Sample))
|
|
{
|
|
// A separately proven observation may renew health without
|
|
// changing the queued candidate's original sample witness.
|
|
if (FreshForDemand(sample))
|
|
{
|
|
var successor = new SampleEvidence(original!, sample.Proof, sample.OriginAgeBounds, sample.ReceivedTimestamp);
|
|
_latestEvidence?.Clear();
|
|
_latestEvidence = successor; _reportedLoss = null;
|
|
}
|
|
return false;
|
|
}
|
|
if (!FreshForDemand(sample)) return true;
|
|
_needsSnapshot = true;
|
|
}
|
|
}
|
|
if (!sameSource || (_needsSnapshot && sample.IsCompleteSnapshot))
|
|
{
|
|
original?.Retire();
|
|
_binding = null;
|
|
_latestEvidence?.Clear(); _latestEvidence = null; _queuedLoss = null; _reportedLoss = 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;
|
|
if (_queuedLoss is not null)
|
|
{
|
|
// A newly admitted value supersedes an unconsumed outage status.
|
|
// Reset the SDK queue before its normal value callback is delivered.
|
|
var mode = MonitoringMode;
|
|
if (mode != MonitoringMode.Disabled) { SetMonitoringMode(MonitoringMode.Disabled); SetMonitoringMode(mode); }
|
|
ClearCandidates(); _queuedLoss = null;
|
|
}
|
|
if (!AddCandidate(sample, _binding)) return true;
|
|
_latestEvidence?.Clear(); _reportedLoss = null;
|
|
_latestEvidence = new SampleEvidence(_binding, sample.Proof, sample.OriginAgeBounds, sample.ReceivedTimestamp);
|
|
return false;
|
|
}
|
|
}
|
|
internal bool HealthRetired => Volatile.Read(ref _retired) != 0;
|
|
internal sealed class LossControl(ProjectedMonitoredItem owner, SampleEvidence evidence)
|
|
{
|
|
internal bool IsCurrent => owner.IsLossCurrent(evidence);
|
|
internal bool IsAuthorized
|
|
{
|
|
get
|
|
{
|
|
try { return owner.HasCurrentDemand; }
|
|
catch (Exception ex) when (ex is not OutOfMemoryException) { return false; }
|
|
}
|
|
}
|
|
internal SampleEvidence Evidence => evidence;
|
|
}
|
|
private bool IsLossCurrent(SampleEvidence evidence)
|
|
{
|
|
if (Volatile.Read(ref _retired) != 0 || !ReferenceEquals(Volatile.Read(ref _latestEvidence), evidence) ||
|
|
!ReferenceEquals(Volatile.Read(ref _binding), evidence.Binding)) return false;
|
|
var proof = evidence.Proof;
|
|
var demand = _demand;
|
|
if (proof is null || demand is null) return true;
|
|
try
|
|
{
|
|
if (!proof.IsValid || demand.MaximumSampleAge <= TimeSpan.Zero) return true;
|
|
var elapsed = proof.Clock.GetElapsedTime(evidence.ReceivedTimestamp, proof.Clock.GetTimestamp());
|
|
return elapsed < TimeSpan.Zero || !evidence.Age.Advance(elapsed).IsFresh(demand.MaximumSampleAge);
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException) { return true; }
|
|
}
|
|
internal LossControl? CaptureLoss()
|
|
{
|
|
if (Volatile.Read(ref _queuedLoss) is not null) return null;
|
|
var latest = Volatile.Read(ref _latestEvidence);
|
|
if (ReferenceEquals(Volatile.Read(ref _reportedLoss), latest)) return null;
|
|
return latest is not null && IsLossCurrent(latest) ? new LossControl(this, latest) : null;
|
|
}
|
|
// Called under the manager lock, matching the order used by ObserveSample.
|
|
// No source/caller callback is evaluated while that lock is held.
|
|
internal void QueueLossIfCurrent(LossControl loss)
|
|
{
|
|
lock (_bindingSync)
|
|
{
|
|
if (MonitoringMode == MonitoringMode.Disabled || _queuedLoss is not null || ReferenceEquals(_reportedLoss, loss.Evidence) || _retired != 0 || !ReferenceEquals(_latestEvidence, loss.Evidence) ||
|
|
!ReferenceEquals(_binding, loss.Evidence.Binding)) return;
|
|
_queuedLoss = loss;
|
|
try { QueueValue(new DataValue(Variant.Null, StatusCodes.BadNoCommunication, DateTimeUtc.MinValue, DateTimeUtc.MinValue),
|
|
new ServiceResult(StatusCodes.BadNoCommunication), ignoreFilters: true); }
|
|
catch (Exception) { _queuedLoss = null; }
|
|
}
|
|
}
|
|
private bool FreshForDemand(ProjectedValueWrite sample)
|
|
{
|
|
if (_demand is not { IsValid: true } demand || demand.MaximumSampleAge <= TimeSpan.Zero || !sample.Proof.IsValid) return false;
|
|
try
|
|
{
|
|
return sample.OriginAgeBounds.Advance(sample.Proof.Clock.GetElapsedTime(sample.ReceivedTimestamp,
|
|
sample.Proof.Clock.GetTimestamp())).IsFresh(demand.MaximumSampleAge);
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
|
|
}
|
|
internal static bool SameAcquisition(ProjectedValueWrite left, ProjectedValueWrite right)
|
|
{
|
|
if (left.SourceVersion is not > 0 || left.SourceVersion != right.SourceVersion ||
|
|
!ReferenceEquals(left.Proof.SourceIdentity, right.Proof.SourceIdentity) || !ReferenceEquals(left.Proof.Clock, right.Proof.Clock) ||
|
|
left.Realm != right.Realm || left.LocalIdentifier != right.LocalIdentifier || left.ProjectionGeneration != right.ProjectionGeneration ||
|
|
left.Serving != right.Serving ||
|
|
left.Snapshot.StatusCode != right.Snapshot.StatusCode || left.Snapshot.SourceTimestampUtc != right.Snapshot.SourceTimestampUtc ||
|
|
left.Snapshot.ServerTimestampUtc != right.Snapshot.ServerTimestampUtc) return false;
|
|
var first = left.Snapshot.Value; var second = right.Snapshot.Value;
|
|
if (first is Array || second is Array)
|
|
return first is Array firstArray && second is Array secondArray && firstArray.GetType() == secondArray.GetType() &&
|
|
System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(firstArray, secondArray);
|
|
return Equals(first, second);
|
|
}
|
|
// The SDK removes the DataValue info-type marker when it carries no info bits.
|
|
// Keep every actual information, structure, semantics, severity and subcode bit.
|
|
internal static bool SameObservedStatus(uint source, uint observed)
|
|
{
|
|
static uint Normalize(uint value) => (value & 0x00000FFFu) == 0x00000400u ? value & ~0x00000400u : value;
|
|
return Normalize(source) == Normalize(observed);
|
|
}
|
|
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) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CurrentBindingRejected); return false; }
|
|
if (candidate.Proof is not { IsValid: true } proof) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CurrentProofRejected); RequestBaseline(); return false; }
|
|
try
|
|
{
|
|
var age = candidate.Age.Advance(proof.Clock.GetElapsedTime(candidate.ReceivedTimestamp, proof.Clock.GetTimestamp()));
|
|
if (age.IsFresh(demand.MaximumSampleAge))
|
|
{
|
|
var current = proof.IsValid && IsCurrentBinding(binding);
|
|
ProjectedDeliveryDiagnostics.Count(current ? ProjectedDeliveryDiagnostics.Event.CurrentAccepted : ProjectedDeliveryDiagnostics.Event.CurrentBindingRejected);
|
|
return current;
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or OverflowException) { }
|
|
ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CurrentAgeRejected);
|
|
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 ResetHealthMonitoringMode()
|
|
{
|
|
lock (_bindingSync) { _queuedLoss = null; _reportedLoss = null; }
|
|
}
|
|
internal void Retire()
|
|
{
|
|
if (Interlocked.Exchange(ref _retired, 1) != 0) return;
|
|
_owner.ForgetProjectedHealth(this);
|
|
lock (_bindingSync) { _binding?.Retire(); _binding = null; _latestEvidence?.Clear(); _latestEvidence = null; _queuedLoss = null; _reportedLoss = null; ClearCandidates(); }
|
|
_definition = null;
|
|
if (Interlocked.Exchange(ref _released, 1) == 0) Interlocked.Exchange(ref _demand, null)?.Dispose();
|
|
}
|
|
protected override void Dispose(bool disposing)
|
|
{
|
|
try { if (disposing) Retire(); }
|
|
finally { base.Dispose(disposing); }
|
|
}
|
|
public override bool Publish(OperationContext context, Queue<MonitoredItemNotification> notifications,
|
|
Queue<DiagnosticInfo> diagnostics, uint maximum, ILogger logger)
|
|
{
|
|
var local = new Queue<MonitoredItemNotification>();
|
|
var localDiagnostics = new Queue<DiagnosticInfo>();
|
|
SourceBinding? captured;
|
|
LossControl? capturedLoss;
|
|
bool more;
|
|
lock (_bindingSync)
|
|
{
|
|
captured = _binding;
|
|
capturedLoss = _queuedLoss;
|
|
more = base.Publish(context, local, localDiagnostics, maximum, logger);
|
|
}
|
|
var hadLocal = local.Count > 0;
|
|
if (capturedLoss is not null && local.Any(x => x.Value.WrappedValue.IsNull && x.Value.StatusCode.Code == StatusCodes.BadNoCommunication))
|
|
AfterLossDequeueForTests?.Invoke();
|
|
var sawLoss = false;
|
|
while (local.Count > 0)
|
|
{
|
|
var notification = local.Dequeue();
|
|
SampleEvidence? evidence = null;
|
|
lock (_bindingSync)
|
|
{
|
|
if (capturedLoss is { } loss && notification.Value.WrappedValue.IsNull &&
|
|
notification.Value.StatusCode.Code == StatusCodes.BadNoCommunication)
|
|
{
|
|
sawLoss = true;
|
|
if (ReferenceEquals(_queuedLoss, loss)) _queuedLoss = null;
|
|
if (ReferenceEquals(_latestEvidence, loss.Evidence)) _reportedLoss = loss.Evidence;
|
|
notifications.Enqueue(new ProjectedSdkNotification(notification,
|
|
new ProjectedLossMarker(notification.ClientHandle, loss)));
|
|
if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
|
|
continue;
|
|
}
|
|
// The SDK can replace a Bad source sample's value with null. Every
|
|
// Bad candidate of the same status could have produced that null;
|
|
// consider all of them before using a source timestamp to disambiguate.
|
|
var badNull = notification.Value.WrappedValue.IsNull && StatusCode.IsBad(notification.Value.StatusCode);
|
|
var matching = _candidates.Where(candidate => ReferenceEquals(candidate.Binding, captured) &&
|
|
(badNull || candidate.Value.Equals(notification.Value.WrappedValue)) &&
|
|
SameObservedStatus(candidate.Sample.Snapshot.StatusCode, notification.Value.StatusCode.Code)).Take(2).ToArray();
|
|
if (matching.Length > 1 && notification.Value.SourceTimestamp != DateTimeUtc.MinValue)
|
|
{
|
|
// The SDK carries the source timestamp from the projected node. It can
|
|
// distinguish equal values from different acquisitions, but only when
|
|
// exactly one retained acquisition has that original timestamp.
|
|
matching = _candidates.Where(candidate => ReferenceEquals(candidate.Binding, captured) &&
|
|
(badNull || candidate.Value.Equals(notification.Value.WrappedValue)) &&
|
|
SameObservedStatus(candidate.Sample.Snapshot.StatusCode, notification.Value.StatusCode.Code) &&
|
|
candidate.Sample.Snapshot.SourceTimestampUtc is { } sourceTimestamp &&
|
|
(DateTimeUtc)sourceTimestamp == notification.Value.SourceTimestamp).Take(2).ToArray();
|
|
}
|
|
if (matching.Length == 1 && notification.Value.SourceTimestamp != DateTimeUtc.MinValue &&
|
|
matching[0].Sample.Snapshot.SourceTimestampUtc is { } originalTimestamp &&
|
|
(DateTimeUtc)originalTimestamp != DateTimeUtc.MinValue &&
|
|
(DateTimeUtc)originalTimestamp != notification.Value.SourceTimestamp)
|
|
{
|
|
// A contradictory timestamp cannot consume the sole remaining
|
|
// candidate's proof, even when value and status happen to match.
|
|
matching = [];
|
|
}
|
|
if (matching.Length == 1)
|
|
{
|
|
ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CandidateUnique);
|
|
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 { ProjectedDeliveryDiagnostics.Count(matching.Length == 0 ? ProjectedDeliveryDiagnostics.Event.CandidateMissing : ProjectedDeliveryDiagnostics.Event.CandidateAmbiguous); _needsSnapshot = true; }
|
|
}
|
|
if (evidence is null) RequestBaseline();
|
|
var originalSample = evidence;
|
|
notifications.Enqueue(new ProjectedSdkNotification(notification,
|
|
new ProjectedNotificationMarker(notification.ClientHandle, notification.Value,
|
|
() => IsCurrentCandidate(captured, originalSample))));
|
|
if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
|
|
}
|
|
if (!sawLoss && capturedLoss is not null && !more)
|
|
{
|
|
lock (_bindingSync)
|
|
if (ReferenceEquals(_queuedLoss, capturedLoss) && hadLocal)
|
|
_queuedLoss = null;
|
|
}
|
|
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>Owns a projected payload and keeps its proof through the SDK's server-side clone.</summary>
|
|
internal sealed class ProjectedSdkNotification : MonitoredItemNotification
|
|
{
|
|
public ProjectedSdkNotification(MonitoredItemNotification rented, NotificationMessage marker)
|
|
{
|
|
ClientHandle = rented.ClientHandle;
|
|
Value = rented.Value;
|
|
DiagnosticInfo = rented.DiagnosticInfo;
|
|
Marker = marker;
|
|
|
|
// The SDK resets its encoded fields on return. Clear its manual fields
|
|
// before returning this stock object for ordinary or built-in items.
|
|
rented.Message = null!;
|
|
rented.DiagnosticInfo = null!;
|
|
rented.Reuse();
|
|
}
|
|
|
|
internal NotificationMessage? Marker { get; private set; }
|
|
|
|
protected override void ReuseCore()
|
|
{
|
|
// ACK, eviction and message disposal use this hook through IPooledEncodeable.
|
|
// This subclass stays out of the shared stock pool.
|
|
Marker = null;
|
|
Message = null!;
|
|
DiagnosticInfo = null!;
|
|
ResetForReuse();
|
|
}
|
|
}
|
|
|
|
/// <summary>Captured authority and value identity for a projected notification.</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) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.MarkerHandleRejected); return false; }
|
|
try
|
|
{
|
|
var current = Fingerprint(notification.Value);
|
|
if (current is null || !System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(_fingerprint, current)) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.MarkerFingerprintRejected); return false; }
|
|
var allowed = _authorize();
|
|
ProjectedDeliveryDiagnostics.Count(allowed ? ProjectedDeliveryDiagnostics.Event.MarkerAccepted : ProjectedDeliveryDiagnostics.Event.MarkerAuthorizationRejected);
|
|
return allowed;
|
|
}
|
|
catch { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.MarkerException); 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; }
|
|
}
|
|
}
|
|
|
|
internal sealed class ProjectedLossMarker(uint clientHandle, ProjectedMonitoredItem.LossControl loss) : NotificationMessage
|
|
{
|
|
internal bool IsObsolete => !loss.IsCurrent;
|
|
internal bool Permits(MonitoredItemNotification notification) => notification.ClientHandle == clientHandle &&
|
|
notification.Value.WrappedValue.IsNull && notification.Value.StatusCode.Code == StatusCodes.BadNoCommunication &&
|
|
notification.Value.SourceTimestamp == DateTimeUtc.MinValue && loss.IsAuthorized;
|
|
}
|
|
|
|
/// <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 originalDiagnostics = change.DiagnosticInfos.ToArray() ?? [];
|
|
var alignedDiagnostics = originalDiagnostics.Length == change.MonitoredItems.Count;
|
|
var keptDiagnostics = new List<DiagnosticInfo>(originalDiagnostics.Length);
|
|
var changedPayload = false;
|
|
var index = 0;
|
|
foreach (var item in change.MonitoredItems)
|
|
{
|
|
var diagnostic = alignedDiagnostics ? originalDiagnostics[index] : null;
|
|
index++;
|
|
var projected = item as ProjectedSdkNotification;
|
|
var marker = projected?.Marker;
|
|
if (marker is ProjectedLossMarker loss && loss.IsObsolete)
|
|
{
|
|
changedPayload = true;
|
|
continue;
|
|
}
|
|
if (marker is ProjectedLossMarker deniedLoss && !deniedLoss.Permits(item))
|
|
{
|
|
if (deniedLoss.IsObsolete) { changedPayload = true; continue; }
|
|
items.Add(new MonitoredItemNotification { ClientHandle = item.ClientHandle,
|
|
Value = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, item.Value.ServerTimestamp) });
|
|
changedPayload = true;
|
|
if (alignedDiagnostics) keptDiagnostics.Add(diagnostic!);
|
|
continue;
|
|
}
|
|
if (marker is ProjectedLossMarker currentLoss && currentLoss.IsObsolete)
|
|
{ changedPayload = true; continue; }
|
|
if (projected is not null && marker is not ProjectedLossMarker &&
|
|
(marker is not ProjectedNotificationMarker proof || !proof.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 (alignedDiagnostics) keptDiagnostics.Add(diagnostic!);
|
|
}
|
|
if (changedPayload)
|
|
{
|
|
changed = true;
|
|
payloads.Add(new ExtensionObject(new DataChangeNotification { MonitoredItems = items,
|
|
DiagnosticInfos = alignedDiagnostics ? keptDiagnostics.ToArray() : change.DiagnosticInfos }));
|
|
}
|
|
else payloads.Add(payload);
|
|
}
|
|
return changed ? new NotificationMessage { SequenceNumber = message.SequenceNumber, PublishTime = message.PublishTime, NotificationData = payloads } : message;
|
|
}
|
|
}
|