Merge #995: alarm predicates compiled once outside the gate, node-indexed stood-down items, kept drivers not re-subscribed, artifact parsed once, VirtualTag/Calculation evaluation coalesced
This commit is contained in:
@@ -790,6 +790,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>()) item.Retire();
|
||||
_liveItems.Clear();
|
||||
_eventItems.Clear();
|
||||
lock (_trackedItemsByNodeLock) _trackedItemsByNode.Clear();
|
||||
_allEventsItems.Clear();
|
||||
lock (Lock) _allEventsMonitoredConditions.Clear();
|
||||
}
|
||||
@@ -6762,10 +6763,14 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// re-attaching an item the client has just deleted.
|
||||
lock (Lock)
|
||||
{
|
||||
if (_eventItems.TryRemove(monitoredItem, out var stoodDown) && stoodDown.Suppressed)
|
||||
if (_eventItems.TryRemove(monitoredItem, out var stoodDown))
|
||||
{
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
return ServiceResult.Good;
|
||||
UnindexIfUntracked(stoodDown.Handle.NodeId, monitoredItem);
|
||||
if (stoodDown.Suppressed)
|
||||
{
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
return ServiceResult.Good;
|
||||
}
|
||||
}
|
||||
|
||||
if (IsHandleInNamespace(sourceId) is { } h
|
||||
@@ -6813,6 +6818,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
&& monitored.EventMonitoredItems?.ContainsKey(monitoredItem.Id) == true)
|
||||
{
|
||||
_eventItems[monitoredItem] = new LiveEventItem(handle);
|
||||
IndexTrackedItem(handle.NodeId, monitoredItem); // after the map write — see IndexTrackedItem
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6861,7 +6867,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// </remarks>
|
||||
internal void TrackLiveMonitoredItem(NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem)
|
||||
{
|
||||
if (OwnsNamespace(handle.NodeId)) _liveItems[monitoredItem] = new LiveItem(handle);
|
||||
if (OwnsNamespace(handle.NodeId))
|
||||
{
|
||||
_liveItems[monitoredItem] = new LiveItem(handle);
|
||||
IndexTrackedItem(handle.NodeId, monitoredItem); // after the map write — see IndexTrackedItem
|
||||
}
|
||||
if (monitoredItem is ProjectedMonitoredItem projected) TrackProjectedHealth(projected);
|
||||
}
|
||||
|
||||
@@ -6871,6 +6881,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
{
|
||||
if (monitoredItem is ProjectedMonitoredItem projected) { ForgetProjectedHealth(projected); projected.Retire(); }
|
||||
if (_liveItems.TryRemove(monitoredItem, out var tracked) && tracked.Suppressed) Interlocked.Decrement(ref _suppressedItems);
|
||||
UnindexIfUntracked(handle.NodeId, monitoredItem);
|
||||
if (tracked is not null && tracked.Handle.NodeId != handle.NodeId) UnindexIfUntracked(tracked.Handle.NodeId, monitoredItem);
|
||||
base.OnMonitoredItemDeleted(context, handle, monitoredItem);
|
||||
}
|
||||
|
||||
@@ -6914,6 +6926,65 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// tombstone sweep for stood-down items — which are not on any fan-out list — run only when there are any.</summary>
|
||||
private int _suppressedItems;
|
||||
|
||||
/// <summary>Test/diagnostic (#995 U-5): tracked-item entries the stood-down sweep has visited. Mutated under
|
||||
/// <c>Lock</c> (every sweep runs under it).</summary>
|
||||
internal long StoodDownSweepVisits { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// #995 U-5: every item in <see cref="_liveItems"/> / <see cref="_eventItems"/>, indexed by the NodeId it was
|
||||
/// tracked against, so a removal's stood-down sweep (<see cref="SweepStoodDownItems"/>) looks up the removed
|
||||
/// node's items instead of scanning every tracked item — removing N stood-down nodes was O(N × items) under
|
||||
/// <c>Lock</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A SUPERSET index: an entry is added right after its map write (<see cref="TrackLiveMonitoredItem"/>,
|
||||
/// <c>TrackLiveEventItem</c>) and dropped when the client deletes the item; everything else that takes an item
|
||||
/// out of a map (the tombstone, a revalidation that finds its node replaced) leaves the entry, and the sweep
|
||||
/// re-validates each candidate against the maps and prunes the ones no longer tracked under that node. So the
|
||||
/// index never has to follow the <c>Suppressed</c> flips — it is only ever asked "which items could be on this
|
||||
/// node", and a candidate that is suppressed must be tracked, hence indexed. Its own lock (never held while
|
||||
/// taking <c>Lock</c>) because the track/delete paths are not all under <c>Lock</c>.
|
||||
/// </remarks>
|
||||
private readonly Dictionary<NodeId, HashSet<object>> _trackedItemsByNode = new();
|
||||
|
||||
private readonly object _trackedItemsByNodeLock = new();
|
||||
|
||||
/// <summary>Adds <paramref name="item"/> to <see cref="_trackedItemsByNode"/>. Call AFTER the map write: a
|
||||
/// concurrent prune that checks the map first then keeps the entry; one that ran before re-adds nothing it
|
||||
/// should not, because this add lands after it.</summary>
|
||||
private void IndexTrackedItem(NodeId nodeId, object item)
|
||||
{
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
if (!_trackedItemsByNode.TryGetValue(nodeId, out var set))
|
||||
_trackedItemsByNode[nodeId] = set = new HashSet<object>(System.Collections.Generic.ReferenceEqualityComparer.Instance);
|
||||
set.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="item"/> is tracked in either map against <paramref name="nodeId"/>.</summary>
|
||||
private bool IsTrackedUnder(NodeId nodeId, object item) =>
|
||||
(item is ISampledDataChangeMonitoredItem data && _liveItems.TryGetValue(data, out var live) && live.Handle.NodeId == nodeId)
|
||||
|| (item is IEventMonitoredItem evt && _eventItems.TryGetValue(evt, out var ev) && ev.Handle.NodeId == nodeId);
|
||||
|
||||
/// <summary>Drops <paramref name="item"/>'s index entry under <paramref name="nodeId"/> unless a map still
|
||||
/// tracks it there (one object can be both a data and an event item).</summary>
|
||||
private void UnindexIfUntracked(NodeId nodeId, object item)
|
||||
{
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
if (!_trackedItemsByNode.TryGetValue(nodeId, out var set) || IsTrackedUnder(nodeId, item)) return;
|
||||
set.Remove(item);
|
||||
if (set.Count == 0) _trackedItemsByNode.Remove(nodeId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Test/diagnostic: NodeIds with at least one index entry.</summary>
|
||||
internal int TrackedItemIndexNodeCount
|
||||
{
|
||||
get { lock (_trackedItemsByNodeLock) return _trackedItemsByNode.Count; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Review 01 L2 — forget the <see cref="MonitoredNode2"/> of a node this manager is removing, telling
|
||||
/// every data-change item on it <c>BadNodeIdUnknown</c> first. MUST be called under <c>Lock</c>, BEFORE
|
||||
@@ -6945,7 +7016,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// </remarks>
|
||||
/// <param name="nodeId">The NodeId being removed.</param>
|
||||
/// <param name="now">The timestamp the terminal <c>BadNodeIdUnknown</c> carries.</param>
|
||||
private void TombstoneMonitoredNode(NodeId nodeId, DateTime now)
|
||||
/// <param name="sweepStoodDown">False only for <see cref="TombstoneAllMonitoredNodes"/>, which runs one
|
||||
/// unfiltered sweep after the loop instead of one per node (#995 U-5).</param>
|
||||
private void TombstoneMonitoredNode(NodeId nodeId, DateTime now, bool sweepStoodDown = true)
|
||||
{
|
||||
if (MonitoredNodes.TryGetValue(nodeId, out var monitored))
|
||||
{
|
||||
@@ -6970,7 +7043,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
}
|
||||
}
|
||||
|
||||
if (!sweepStoodDown) return;
|
||||
if (Volatile.Read(ref _suppressedItems) > 0) SweepStoodDownItems(nodeId, now);
|
||||
else PruneIndexFor(nodeId);
|
||||
}
|
||||
|
||||
/// <summary>Tombstones <paramref name="node"/> and every descendant (a condition's instance-scoped
|
||||
@@ -7000,32 +7075,107 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
foreach (var nodeId in MonitoredNodes.Keys.ToList())
|
||||
{
|
||||
if (rootId is not null && nodeId == rootId.Value) continue;
|
||||
TombstoneMonitoredNode(nodeId, now);
|
||||
// #995 U-5: no per-node sweep — the one unfiltered sweep below covers every node, and per node it was
|
||||
// a full scan of the tracked items each time (O(monitored nodes × items) under Lock).
|
||||
TombstoneMonitoredNode(nodeId, now, sweepStoodDown: false);
|
||||
}
|
||||
|
||||
if (Volatile.Read(ref _suppressedItems) > 0) SweepStoodDownItems(nodeId: null, now);
|
||||
if (Volatile.Read(ref _suppressedItems) > 0) SweepStoodDownItems(nodeId: null, now); // prunes the index too
|
||||
else PruneIndexAll();
|
||||
}
|
||||
|
||||
/// <summary>Drops the stood-down items of <paramref name="nodeId"/> (every stood-down item when null —
|
||||
/// the rebuild case) from the revalidation maps, telling the data items <c>BadNodeIdUnknown</c>.</summary>
|
||||
/// <remarks>#995 U-5: a per-node sweep visits only the candidates <see cref="_trackedItemsByNode"/> holds for
|
||||
/// that node (and prunes the ones no longer tracked there); only the rebuild's unfiltered sweep scans the maps.</remarks>
|
||||
private void SweepStoodDownItems(NodeId? nodeId, DateTime now)
|
||||
{
|
||||
foreach (var (item, tracked) in _liveItems)
|
||||
if (nodeId is null)
|
||||
{
|
||||
if (!tracked.Suppressed || (nodeId is not null && tracked.Handle.NodeId != nodeId.Value)) continue;
|
||||
if (!_liveItems.TryRemove(item, out _)) continue;
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
if (item is ProjectedMonitoredItem projected) projected.Retire();
|
||||
TellNodeRemoved(item, now);
|
||||
ReleaseComponentCacheReference(item);
|
||||
foreach (var (item, tracked) in _liveItems)
|
||||
{
|
||||
StoodDownSweepVisits++;
|
||||
if (tracked.Suppressed) DropStoodDownDataItem(item, now);
|
||||
}
|
||||
|
||||
foreach (var (item, tracked) in _eventItems)
|
||||
{
|
||||
StoodDownSweepVisits++;
|
||||
if (tracked.Suppressed) DropStoodDownEventItem(item);
|
||||
}
|
||||
|
||||
PruneIndexAll();
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var (item, tracked) in _eventItems)
|
||||
var node = nodeId.Value;
|
||||
object[] candidates;
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
if (!tracked.Suppressed || (nodeId is not null && tracked.Handle.NodeId != nodeId.Value)) continue;
|
||||
if (!_eventItems.TryRemove(item, out _)) continue;
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
// Event items hold no component-cache reference (see TombstoneMonitoredNode).
|
||||
if (!_trackedItemsByNode.TryGetValue(node, out var set)) return;
|
||||
candidates = [.. set];
|
||||
}
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
StoodDownSweepVisits++;
|
||||
if (candidate is ISampledDataChangeMonitoredItem data
|
||||
&& _liveItems.TryGetValue(data, out var live) && live.Suppressed && live.Handle.NodeId == node)
|
||||
{
|
||||
DropStoodDownDataItem(data, now);
|
||||
}
|
||||
|
||||
if (candidate is IEventMonitoredItem evt
|
||||
&& _eventItems.TryGetValue(evt, out var ev) && ev.Suppressed && ev.Handle.NodeId == node)
|
||||
{
|
||||
DropStoodDownEventItem(evt);
|
||||
}
|
||||
|
||||
UnindexIfUntracked(node, candidate);
|
||||
}
|
||||
}
|
||||
|
||||
private void DropStoodDownDataItem(ISampledDataChangeMonitoredItem item, DateTime now)
|
||||
{
|
||||
if (!_liveItems.TryRemove(item, out _)) return;
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
if (item is ProjectedMonitoredItem projected) projected.Retire();
|
||||
TellNodeRemoved(item, now);
|
||||
ReleaseComponentCacheReference(item);
|
||||
}
|
||||
|
||||
private void DropStoodDownEventItem(IEventMonitoredItem item)
|
||||
{
|
||||
if (!_eventItems.TryRemove(item, out _)) return;
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
// Event items hold no component-cache reference (see TombstoneMonitoredNode).
|
||||
}
|
||||
|
||||
/// <summary>#995 U-5: drops <paramref name="nodeId"/>'s index entries that no map tracks there any more (a
|
||||
/// removal with no stood-down items, which skips the sweep).</summary>
|
||||
private void PruneIndexFor(NodeId nodeId)
|
||||
{
|
||||
object[] candidates;
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
if (!_trackedItemsByNode.TryGetValue(nodeId, out var set)) return;
|
||||
candidates = [.. set];
|
||||
}
|
||||
foreach (var candidate in candidates) UnindexIfUntracked(nodeId, candidate);
|
||||
}
|
||||
|
||||
/// <summary>#995 U-5: the rebuild's whole-index prune — every entry no map tracks under its node any more.</summary>
|
||||
private void PruneIndexAll()
|
||||
{
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
List<NodeId>? empty = null;
|
||||
foreach (var (nodeId, set) in _trackedItemsByNode)
|
||||
{
|
||||
set.RemoveWhere(item => !IsTrackedUnder(nodeId, item));
|
||||
if (set.Count == 0) (empty ??= []).Add(nodeId);
|
||||
}
|
||||
if (empty is not null) foreach (var nodeId in empty) _trackedItemsByNode.Remove(nodeId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Text.Json;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
@@ -88,8 +89,45 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
};
|
||||
private static readonly StringComparer DataIds = StringComparer.OrdinalIgnoreCase;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #995 (review 2026-12-02 R-14): the data projection deserialises the whole topology (every Tag, the UNS
|
||||
/// tables, VirtualTags, ScriptedAlarms, Scripts) and runs <see cref="DataConnectionValidator.ValidateDeployed"/>.
|
||||
/// <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/> alone asked for it three times and the driver
|
||||
/// host's catalog staging up to four more, per apply. It is now built (and validated) ONCE per node id per parsed
|
||||
/// artifact — a throw included, re-thrown to every caller — and the three row parsers skip it entirely when the
|
||||
/// artifact's data arrays are all empty (they could only return empty lists).
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, DataProjectionMemo> _dataProjectionByNodeId = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Diagnostics / tests (#995 R-14): how many data projections this parsed artifact actually built.</summary>
|
||||
internal int DataProjectionBuilds { get; private set; }
|
||||
|
||||
private sealed class DataProjectionMemo
|
||||
{
|
||||
public (DraftSnapshot Snapshot, string ClusterId)? Projection;
|
||||
public ExceptionDispatchInfo? Failure;
|
||||
public IReadOnlyList<ValidationError>? Errors;
|
||||
}
|
||||
|
||||
/// <summary>True when none of the three data arrays carries a row (absent, or present and empty) — no data row
|
||||
/// can then be returned, so the row parsers need no projection.</summary>
|
||||
private bool HasNoDataRows()
|
||||
{
|
||||
var root = Root;
|
||||
if (root.ValueKind != JsonValueKind.Object) return true;
|
||||
foreach (var name in DataArrayNames)
|
||||
if (root.TryGetProperty(name, out var value)
|
||||
&& (value.ValueKind != JsonValueKind.Array || value.GetArrayLength() != 0))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static readonly string[] DataArrayNames = ["DataConnections", "DataExports", "RemoteNamespaceMappings"];
|
||||
|
||||
public IReadOnlyList<DataConnection> ParseDataConnections(string nodeId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
|
||||
if (HasNoDataRows()) return [];
|
||||
var projection = ReadDataProjection(nodeId);
|
||||
if (projection is null)
|
||||
return [];
|
||||
@@ -104,6 +142,8 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
|
||||
public IReadOnlyList<DataExport> ParseDataExports(string nodeId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
|
||||
if (HasNoDataRows()) return [];
|
||||
var projection = ReadDataProjection(nodeId);
|
||||
if (projection is null)
|
||||
return [];
|
||||
@@ -116,6 +156,8 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
|
||||
public IReadOnlyList<RemoteNamespaceMapping> ParseRemoteNamespaceMappings(string nodeId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
|
||||
if (HasNoDataRows()) return [];
|
||||
var projection = ReadDataProjection(nodeId);
|
||||
if (projection is null)
|
||||
return [];
|
||||
@@ -140,6 +182,28 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
private (DraftSnapshot Snapshot, string ClusterId)? ReadDataProjection(string nodeId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
|
||||
if (!_dataProjectionByNodeId.TryGetValue(nodeId, out var memo))
|
||||
{
|
||||
memo = new DataProjectionMemo();
|
||||
try { memo.Projection = BuildDataProjection(nodeId); }
|
||||
catch (Exception ex) { memo.Failure = ExceptionDispatchInfo.Capture(ex); }
|
||||
_dataProjectionByNodeId[nodeId] = memo;
|
||||
}
|
||||
memo.Failure?.Throw();
|
||||
return memo.Projection;
|
||||
}
|
||||
|
||||
/// <summary>The deployed-data validation of <paramref name="snapshot"/>, computed once per memoised projection.</summary>
|
||||
private IReadOnlyList<ValidationError> ValidationErrors(DraftSnapshot snapshot)
|
||||
{
|
||||
foreach (var memo in _dataProjectionByNodeId.Values)
|
||||
if (memo.Projection is { } p && ReferenceEquals(p.Snapshot, snapshot))
|
||||
return memo.Errors ??= DataConnectionValidator.ValidateDeployed(snapshot).ToArray();
|
||||
return DataConnectionValidator.ValidateDeployed(snapshot).ToArray();
|
||||
}
|
||||
|
||||
private (DraftSnapshot Snapshot, string ClusterId)? BuildDataProjection(string nodeId)
|
||||
{
|
||||
var root = Root;
|
||||
if (root.ValueKind != JsonValueKind.Object)
|
||||
return null;
|
||||
@@ -201,6 +265,7 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
foreach (var m in mappings)
|
||||
if (m.ConsumerNodeIds is null)
|
||||
throw InvalidRow(m.RemoteNamespaceMappingId);
|
||||
DataProjectionBuilds++;
|
||||
var snapshot = new DraftSnapshot
|
||||
{
|
||||
GenerationId = 0,
|
||||
@@ -348,11 +413,10 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateRows(DraftSnapshot snapshot, IEnumerable<string> ids)
|
||||
private void ValidateRows(DraftSnapshot snapshot, IEnumerable<string> ids)
|
||||
{
|
||||
var requested = ids.ToHashSet(DataIds);
|
||||
var error = DataConnectionValidator
|
||||
.ValidateDeployed(snapshot)
|
||||
var error = ValidationErrors(snapshot)
|
||||
.FirstOrDefault(x => x.Context is not null && requested.Contains(x.Context));
|
||||
if (error is not null)
|
||||
throw InvalidRow(error.Context);
|
||||
|
||||
@@ -276,9 +276,42 @@ public static partial class DeploymentArtifact
|
||||
try
|
||||
{
|
||||
using var parsed = Open(blob.ToArray());
|
||||
var root = parsed.Root;
|
||||
return parsed.ReadClusterRedundancyMode(nodeId);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gitea #995 (R-14): the <see cref="ReadClusterRedundancyMode(ReadOnlySpan{byte}, string)"/> read off an
|
||||
/// ALREADY-parsed artifact, so the publish actor's off-thread plan step answers it from its own single parse instead
|
||||
/// of a second inflate + parse on the pinned OPC UA thread.</summary>
|
||||
/// <param name="parsed">The parsed artifact.</param>
|
||||
/// <param name="nodeId">This node's <c>host:port</c> id.</param>
|
||||
/// <returns>The mode name, or null.</returns>
|
||||
internal static string? ReadClusterRedundancyMode(ParsedDeploymentArtifact parsed, string nodeId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return parsed.ReadClusterRedundancyMode(nodeId);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed partial class ParsedDeploymentArtifact
|
||||
{
|
||||
/// <summary>See <see cref="DeploymentArtifact.ReadClusterRedundancyMode(ReadOnlySpan{byte}, string)"/>.</summary>
|
||||
internal string? ReadClusterRedundancyMode(string nodeId)
|
||||
{
|
||||
{
|
||||
var root = Root;
|
||||
if (!root.TryGetProperty("Clusters", out var clusters) || clusters.ValueKind != JsonValueKind.Array) return null;
|
||||
var scope = parsed.ResolveClusterScope(nodeId);
|
||||
var scope = ResolveClusterScope(nodeId);
|
||||
JsonElement? match = null;
|
||||
foreach (var cluster in clusters.EnumerateArray())
|
||||
{
|
||||
@@ -301,11 +334,11 @@ public static partial class DeploymentArtifact
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static partial class DeploymentArtifact
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Resolve how a node should scope a deployment artifact to its own ClusterId. Single-cluster
|
||||
@@ -833,6 +866,11 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
|
||||
private static string InjectScriptSource(string tagConfig, IReadOnlyDictionary<string, string> scriptSourceById)
|
||||
{
|
||||
if (scriptSourceById.Count == 0 || string.IsNullOrWhiteSpace(tagConfig)) return tagConfig;
|
||||
// #995 (R-14): a tag that cannot carry a scriptId is not parsed at all — once an artifact has any Scripts row this
|
||||
// ran a JsonNode.Parse per tag of every driver. The property lookup below is ordinal and case-sensitive, so a
|
||||
// config without the literal "scriptId" can never inject (only a \u-escaped property NAME would differ, which
|
||||
// no authoring path emits).
|
||||
if (!tagConfig.Contains("scriptId", StringComparison.Ordinal)) return tagConfig;
|
||||
JsonNode? node;
|
||||
try { node = JsonNode.Parse(tagConfig); }
|
||||
catch (JsonException) { return tagConfig; }
|
||||
|
||||
@@ -492,6 +492,33 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// the child the last-known-good set, not an empty one.</para></summary>
|
||||
private readonly Dictionary<string, DesiredSubscriptionSet> _desiredByDriver = new(StringComparer.Ordinal);
|
||||
|
||||
// ---- Gitea #995 (review 2026-12-02 R-11): skip the deploy re-subscribe of an untouched driver ----
|
||||
// A re-subscribe tears down and rebuilds the driver's whole data subscription (OpcUaClient monitored items, Galaxy
|
||||
// advise through mxaccessgw, a forced full re-read on every poll driver) and leaves a data gap. Its only job on a
|
||||
// KEPT driver whose desired set is unchanged is SEEDING: the initial values it produces are what give a node or a
|
||||
// consumer that is new since the last apply its first value. So the deploy path skips a driver only when nothing
|
||||
// that could need a seed changed for it (see SeedingFingerprint / ConsumerRefs), and re-pushes the skipped ones
|
||||
// after the address-space outcome if the apply turned out to be a full rebuild (or degraded / timed out).
|
||||
|
||||
/// <summary>The child actor last handed a plain (non-acquisition) desired set for each driver. A child that is not
|
||||
/// the current one (respawned) or that got an acquisition-demand set is never skipped.</summary>
|
||||
private readonly Dictionary<string, IActorRef> _plainPushedTo = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Per-driver seeding fingerprint from the last apply (see <see cref="SeedingFingerprint"/>).</summary>
|
||||
private Dictionary<string, string[]> _seedingFingerprints = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Every driver ref some mux consumer (enabled VirtualTag, enabled scripted alarm, dependency-consuming
|
||||
/// driver such as Calculation) read at the last apply. The mux replays a retained value only for refs a
|
||||
/// replay-opting subscriber already named, so a ref ENTERING this set needs its driver's initial value.</summary>
|
||||
private HashSet<string>? _consumerRefs;
|
||||
|
||||
/// <summary>The <see cref="IDependencyConsumer"/> drivers hosted here, keyed like <see cref="_depConsumerAdapters"/>.</summary>
|
||||
private readonly Dictionary<string, IDependencyConsumer> _depConsumers = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Drivers whose deploy re-subscribe was skipped, held per apply correlation until the address-space
|
||||
/// outcome says whether their nodes survived (non-rebuild, clean) or were recreated (re-push them).</summary>
|
||||
private readonly Dictionary<CorrelationId, HashSet<string>> _seedAfterAddressSpace = new();
|
||||
|
||||
/// <summary>
|
||||
/// Cached local <see cref="RedundancyRole"/> from the latest <see cref="RedundancyStateChanged"/>
|
||||
/// snapshot (null = unknown until the first snapshot arrives, or no local node match). The Primary
|
||||
@@ -3382,7 +3409,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
// resumes off the actor thread.
|
||||
// SubscribeBulk pass: hand each driver its desired tag references so live values flow into
|
||||
// the just-rebuilt address space instead of staying BadWaitingForInitialData.
|
||||
PushDesiredSubscriptionsFromParsed(msg.DeploymentId, parsed);
|
||||
// #995 R-11: a kept driver with nothing seedable changed is NOT re-subscribed; if the address-space apply
|
||||
// turns out to be a rebuild (its nodes recreated empty), HandleRebuildCompleted re-pushes it.
|
||||
var skippedResubscribes = PushDesiredSubscriptionsFromParsed(msg.DeploymentId, parsed, skipUnchanged: true);
|
||||
// Recorded at once, so a throw in the steps below still re-pushes them (the catch). No publish actor ⇒ no
|
||||
// address space whose rebuild could recreate a skipped driver's nodes.
|
||||
if (_opcUaPublishActor is not null && skippedResubscribes.Count > 0)
|
||||
_seedAfterAddressSpace[msg.Correlation] = new HashSet<string>(skippedResubscribes, StringComparer.Ordinal);
|
||||
// Cache the applied bytes as this node's last-known-good (idempotent store; skips empty).
|
||||
CacheAppliedArtifact(msg.DeploymentId, msg.Revision, appliedBlob, parsed);
|
||||
var catalogFailed = _opcUaPublishActor is null && _catalogAttempt is not null
|
||||
@@ -3413,6 +3446,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
// A throw after the Applied ack was put on hold — the Failed ack below is this apply's one
|
||||
// answer, so the held Applied must never follow it when the address-space outcome lands.
|
||||
DropPendingAck(msg.Correlation);
|
||||
// #995 R-11: the routing/desired state may be half-applied — re-push anything this apply skipped.
|
||||
SeedSkippedDrivers(msg.Correlation, reseed: true, "the apply threw");
|
||||
// #977 R-15: whatever revision is current now, a throw part-way through the apply means the drivers and the
|
||||
// routing maps (ApplyDesiredSubscriptions clears them before repopulating) may already be the NEW revision's,
|
||||
// partially. Nothing about the current revision is known-served any more, so a re-dispatch of EITHER revision
|
||||
@@ -3484,6 +3519,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// </summary>
|
||||
private void HandleRebuildCompleted(OpcUa.OpcUaPublishActor.RebuildCompleted msg)
|
||||
{
|
||||
SeedSkippedDrivers(msg.Correlation, reseed: msg.AddressSpaceRebuilt || msg.Degraded,
|
||||
msg.Degraded ? "degraded apply" : "full rebuild");
|
||||
if (!_pendingAcks.Remove(msg.Correlation, out var pending))
|
||||
{
|
||||
_log.Debug("DriverHost {Node}: address-space outcome for {Correlation} has no held ack (already timed out or superseded); dropping",
|
||||
@@ -3502,6 +3539,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// </summary>
|
||||
private void HandleApplyOutcomeTimedOut(ApplyOutcomeTimedOut msg)
|
||||
{
|
||||
SeedSkippedDrivers(msg.Correlation, reseed: true, "address-space outcome not reported in time");
|
||||
if (!_pendingAcks.Remove(msg.Correlation, out var pending)) return;
|
||||
|
||||
ReleasePendingAck(pending, degraded: true,
|
||||
@@ -4101,7 +4139,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// </remarks>
|
||||
/// <param name="deploymentId">The deployment being applied — diagnostics only.</param>
|
||||
/// <param name="parsed">The apply's parsed artifact.</param>
|
||||
private void PushDesiredSubscriptionsFromParsed(DeploymentId deploymentId, ParsedDeploymentArtifact parsed)
|
||||
/// <param name="skipUnchanged">#995 R-11: the deploy path skips the re-subscribe of a driver with nothing
|
||||
/// seedable changed (see <see cref="ApplyDesiredSubscriptions"/>).</param>
|
||||
/// <returns>The drivers whose re-subscribe was skipped (empty unless <paramref name="skipUnchanged"/>).</returns>
|
||||
private IReadOnlyCollection<string> PushDesiredSubscriptionsFromParsed(
|
||||
DeploymentId deploymentId, ParsedDeploymentArtifact parsed, bool skipUnchanged = false)
|
||||
{
|
||||
AddressSpaceComposition composition;
|
||||
try
|
||||
@@ -4111,10 +4153,10 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warning(ex, "DriverHost {Node}: failed to parse composition for SubscribeBulk ({Id})", _localNode, deploymentId);
|
||||
return;
|
||||
return Array.Empty<string>();
|
||||
}
|
||||
|
||||
ApplyDesiredSubscriptions(composition);
|
||||
return ApplyDesiredSubscriptions(composition, skipUnchanged);
|
||||
}
|
||||
|
||||
/// <summary>Gets (creating on first use) the per-driver bucket of a secondary index.</summary>
|
||||
@@ -4135,7 +4177,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// Equipment VirtualTag + ScriptedAlarm plans to their hosts.
|
||||
/// </summary>
|
||||
/// <param name="composition">The composition this node should serve.</param>
|
||||
private void ApplyDesiredSubscriptions(AddressSpaceComposition composition)
|
||||
/// <param name="skipUnchanged">
|
||||
/// #995 R-11 (deploy path only): do not re-push a kept driver whose seeding fingerprint is unchanged and none of
|
||||
/// whose value refs gained a mux consumer. The caller re-pushes the returned drivers if the address-space apply
|
||||
/// turns out to be a rebuild. Every other path (boot, restore) pushes every child, as before.
|
||||
/// </param>
|
||||
/// <returns>The drivers whose push was skipped.</returns>
|
||||
private IReadOnlyCollection<string> ApplyDesiredSubscriptions(AddressSpaceComposition composition, bool skipUnchanged = false)
|
||||
{
|
||||
_catalogCoordinator?.BeforeSubscriptionApplyForTests?.Invoke();
|
||||
// v3 Batch 4: the driver subscribes + publishes by RawPath (the wire-ref == RawPath == RawTagPlan.NodeId
|
||||
@@ -4310,9 +4358,29 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
alarmRefsByDriver.TryGetValue(driverId, out var ar) ? ar : Array.Empty<string>());
|
||||
}
|
||||
|
||||
// #995 R-11: what a re-subscribe would seed, per driver, and which refs gained a mux consumer since the last apply.
|
||||
var previousFingerprints = _seedingFingerprints;
|
||||
_seedingFingerprints = new Dictionary<string, string[]>(StringComparer.Ordinal);
|
||||
foreach (var driverId in _desiredByDriver.Keys)
|
||||
_seedingFingerprints[driverId] = SeedingFingerprint(driverId, composition);
|
||||
var previousConsumerRefs = _consumerRefs;
|
||||
_consumerRefs = ConsumerRefs(composition);
|
||||
HashSet<string>? newConsumerRefs = null;
|
||||
if (previousConsumerRefs is not null)
|
||||
{
|
||||
newConsumerRefs = new HashSet<string>(_consumerRefs, StringComparer.Ordinal);
|
||||
newConsumerRefs.ExceptWith(previousConsumerRefs);
|
||||
}
|
||||
|
||||
var total = 0;
|
||||
List<string>? skipped = null;
|
||||
foreach (var (driverId, entry) in _children)
|
||||
{
|
||||
if (skipUnchanged && CanSkipResubscribe(driverId, entry.Actor, previousFingerprints, newConsumerRefs))
|
||||
{
|
||||
(skipped ??= new List<string>()).Add(driverId);
|
||||
continue;
|
||||
}
|
||||
total += SendDesiredSubscriptions(entry.Actor, driverId);
|
||||
}
|
||||
|
||||
@@ -4321,6 +4389,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_log.Info("DriverHost {Node}: SubscribeBulk pushed {Refs} references across {Drivers} driver(s)",
|
||||
_localNode, total, refsByDriver.Count);
|
||||
}
|
||||
if (skipped is not null)
|
||||
{
|
||||
_log.Info("DriverHost {Node}: SubscribeBulk kept {Count} unchanged driver subscription(s) without re-subscribing ({Drivers})",
|
||||
_localNode, skipped.Count, string.Join(", ", skipped));
|
||||
}
|
||||
|
||||
// Hand the Equipment-namespace VirtualTags to the host so it spawns/reconciles a
|
||||
// VirtualTagActor per plan and streams their evaluated values back onto the just-rebuilt
|
||||
@@ -4350,6 +4423,84 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_log.Info("DriverHost {Node}: applied {Count} Equipment ScriptedAlarm(s) to the ScriptedAlarm host",
|
||||
_localNode, composition.EquipmentScriptedAlarms.Count);
|
||||
}
|
||||
|
||||
return (IReadOnlyCollection<string>?)skipped ?? Array.Empty<string>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 R-11: whether the deploy push to <paramref name="driverId"/> can be skipped. Only when the child is the
|
||||
/// one that already holds a plain (non-acquisition) set from this host, that set and everything it seeds are
|
||||
/// unchanged (<see cref="SeedingFingerprint"/>), and none of its value refs gained a mux consumer — any of those
|
||||
/// means some node or consumer may be new and needs the initial values a re-subscribe produces.
|
||||
/// </summary>
|
||||
private bool CanSkipResubscribe(string driverId, IActorRef child, Dictionary<string, string[]> previousFingerprints,
|
||||
HashSet<string>? newConsumerRefs)
|
||||
{
|
||||
if (newConsumerRefs is null) return false; // first apply of this incarnation
|
||||
if (_acquisitionDemands.ContainsKey(driverId)) return false;
|
||||
if (!_plainPushedTo.TryGetValue(driverId, out var pushed) || !pushed.Equals(child)) return false;
|
||||
if (!previousFingerprints.TryGetValue(driverId, out var before)
|
||||
|| !_seedingFingerprints.TryGetValue(driverId, out var now)
|
||||
|| !before.AsSpan().SequenceEqual(now)) return false;
|
||||
if (newConsumerRefs.Count > 0 && _desiredByDriver.TryGetValue(driverId, out var set))
|
||||
foreach (var r in set.ValueRefs)
|
||||
if (newConsumerRefs.Contains(r)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 R-11: everything a deploy re-subscribe of <paramref name="driverId"/> would (re)seed — its value refs, each
|
||||
/// with its fan-out NodeIds (raw + every referencing UNS mirror, so a new or re-pointed mirror changes it) and its
|
||||
/// historization (a ref that starts being recorded), then its alarm refs. Built after the routing maps.
|
||||
/// </summary>
|
||||
private string[] SeedingFingerprint(string driverId, AddressSpaceComposition composition)
|
||||
{
|
||||
var set = _desiredByDriver[driverId];
|
||||
var historized = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var t in composition.RawTags)
|
||||
if (string.Equals(t.DriverInstanceId, driverId, StringComparison.Ordinal))
|
||||
historized[t.NodeId] = t.IsHistorized ? "H:" + t.HistorianTagname : "-";
|
||||
var parts = new List<string>(set.ValueRefs.Count + set.AlarmRefs.Count + 1);
|
||||
foreach (var r in set.ValueRefs)
|
||||
{
|
||||
var nodes = _nodeIdByDriverRef.TryGetValue((driverId, r), out var fan)
|
||||
? string.Join("|", fan.Select(n => n.Realm + ":" + n.NodeId).Order(StringComparer.Ordinal))
|
||||
: string.Empty;
|
||||
parts.Add("v\u0001" + r + "\u0001" + historized.GetValueOrDefault(r, "-") + "\u0001" + nodes);
|
||||
}
|
||||
parts.Add("alarms");
|
||||
foreach (var r in set.AlarmRefs) parts.Add("a\u0001" + r);
|
||||
return parts.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>#995 R-11: every ref a mux consumer reads under <paramref name="composition"/> — enabled VirtualTags,
|
||||
/// enabled scripted alarms and the hosted dependency-consuming drivers (read after the apply's reconcile).</summary>
|
||||
private HashSet<string> ConsumerRefs(AddressSpaceComposition composition)
|
||||
{
|
||||
var refs = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var vt in composition.EquipmentVirtualTags)
|
||||
if (vt.Enabled) refs.UnionWith(vt.DependencyRefs);
|
||||
foreach (var a in composition.EquipmentScriptedAlarms)
|
||||
if (a.Enabled) refs.UnionWith(a.DependencyRefs);
|
||||
foreach (var consumer in _depConsumers.Values) refs.UnionWith(consumer.DependencyRefs);
|
||||
return refs;
|
||||
}
|
||||
|
||||
/// <summary>#995 R-11: re-push the drivers an apply skipped, once its address-space outcome says their nodes were
|
||||
/// recreated (a rebuild), may be partial (degraded) or is unknown (timed out). Always forgets the entry.</summary>
|
||||
private void SeedSkippedDrivers(CorrelationId correlation, bool reseed, string why)
|
||||
{
|
||||
if (!_seedAfterAddressSpace.Remove(correlation, out var skipped) || !reseed) return;
|
||||
var pushed = 0;
|
||||
foreach (var driverId in skipped)
|
||||
if (_children.TryGetValue(driverId, out var child))
|
||||
{
|
||||
SendDesiredSubscriptions(child.Actor, driverId);
|
||||
pushed++;
|
||||
}
|
||||
if (pushed > 0)
|
||||
_log.Info("DriverHost {Node}: re-subscribing {Count} kept driver(s) after the address-space apply ({Why})",
|
||||
_localNode, pushed, why);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -4374,8 +4525,17 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
{
|
||||
var demand = _acquisitionDemands.GetValueOrDefault(driverId);
|
||||
var message = BuildDesiredSubscriptions(driverId, demand);
|
||||
if (demand is null) actor.Tell(message);
|
||||
else if (!_acquisitionPending.ContainsKey(driverId)) StartAcquisitionDemand(driverId, demand, ActorRefs.Nobody);
|
||||
if (demand is null)
|
||||
{
|
||||
actor.Tell(message);
|
||||
_plainPushedTo[driverId] = actor;
|
||||
}
|
||||
else
|
||||
{
|
||||
// #995 R-11: an acquisition-demand set is not the plain set a later deploy could compare against.
|
||||
_plainPushedTo.Remove(driverId);
|
||||
if (!_acquisitionPending.ContainsKey(driverId)) StartAcquisitionDemand(driverId, demand, ActorRefs.Nobody);
|
||||
}
|
||||
return message.FullReferences.Count;
|
||||
}
|
||||
|
||||
@@ -4831,6 +4991,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyConsumerMuxAdapter.Props(consumer, _dependencyMux),
|
||||
"depmux-" + actorName);
|
||||
_depConsumerAdapters[spec.DriverInstanceId] = adapter;
|
||||
_depConsumers[spec.DriverInstanceId] = consumer;
|
||||
_log.Info("DriverHost {Node}: wired dependency-consumer mux adapter for {Id} ({Count} ref(s))",
|
||||
_localNode, spec.DriverInstanceId, consumer.DependencyRefs.Count);
|
||||
}
|
||||
@@ -4843,6 +5004,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// driver child is stopped/respawned so a stale adapter never keeps a dead driver's refs registered.</summary>
|
||||
private void StopDependencyAdapter(string driverInstanceId)
|
||||
{
|
||||
_depConsumers.Remove(driverInstanceId);
|
||||
if (_depConsumerAdapters.Remove(driverInstanceId, out var adapter))
|
||||
Context.Stop(adapter);
|
||||
}
|
||||
@@ -4864,6 +5026,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(driverInstanceId);
|
||||
Context.Stop(entry.Actor);
|
||||
_children.Remove(driverInstanceId);
|
||||
_plainPushedTo.Remove(driverInstanceId);
|
||||
// A1 review S2: the stopped incarnation can no longer vouch for its conditions (a respawn's carried-over
|
||||
// known state would otherwise stand until the new incarnation signals). No-op when the deploy removed them.
|
||||
WithdrawDriverConditionsKnown(driverInstanceId);
|
||||
|
||||
@@ -139,10 +139,15 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// ack only after that reply, so a degraded apply can no longer seal a deployment green. Off for the
|
||||
/// boot/restore paths, which re-ack nothing.
|
||||
/// </param>
|
||||
/// <param name="ArtifactRevision">
|
||||
/// Gitea #995 (R-14): SHA-256 (lower hex) of <see cref="Artifact"/>, computed ONCE by the actor when the request
|
||||
/// arrives and reused for the catalog attempt, the data-catalog generation and the data-plane authority revision
|
||||
/// — it used to be hashed up to three times on the pinned OPC UA thread. Callers leave it null.
|
||||
/// </param>
|
||||
public sealed record RebuildAddressSpace(
|
||||
CorrelationId Correlation, DeploymentId? DeploymentId = null, byte[]? Artifact = null,
|
||||
bool ReportOutcome = false, DataConnections.CatalogAttempt? CatalogAttempt = null,
|
||||
bool StageCatalog = false);
|
||||
bool StageCatalog = false, string? ArtifactRevision = null);
|
||||
|
||||
/// <summary>
|
||||
/// the reply to a <see cref="RebuildAddressSpace"/> carrying
|
||||
@@ -156,8 +161,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// stale. An empty plan (nothing changed) is clean.
|
||||
/// </param>
|
||||
/// <param name="DegradedReason">A short operator-readable reason; null when clean.</param>
|
||||
/// <param name="AddressSpaceRebuilt">
|
||||
/// Gitea #995 (R-11): <see langword="false"/> only when the apply was a clean NON-rebuild — every node that
|
||||
/// existed before it still exists with its value. <c>DriverHostActor</c> skips the re-subscribe of a driver
|
||||
/// whose desired set and fan-out are unchanged, and re-pushes those drivers when this is <see langword="true"/>
|
||||
/// (a full rebuild recreated their nodes without a value). Defaults to <see langword="true"/> — the
|
||||
/// conservative answer for any producer that does not know.
|
||||
/// </param>
|
||||
public sealed record RebuildCompleted(
|
||||
CorrelationId Correlation, DeploymentId? DeploymentId, bool Degraded, string? DegradedReason);
|
||||
CorrelationId Correlation, DeploymentId? DeploymentId, bool Degraded, string? DegradedReason,
|
||||
bool AddressSpaceRebuilt = true);
|
||||
|
||||
public sealed record ServiceLevelChanged(byte ServiceLevel);
|
||||
|
||||
@@ -175,11 +188,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
private sealed record PlanReady(
|
||||
object Incarnation, RebuildAddressSpace Request, IActorRef Requester, byte[] Artifact,
|
||||
DataPlaneAuthorityProjection? Authority, Exception? AuthorityError,
|
||||
AddressSpaceComposition Composition, AddressSpacePlan Plan, IReadOnlyList<string> Inconsistencies);
|
||||
AddressSpaceComposition Composition, AddressSpacePlan Plan, IReadOnlyList<string> Inconsistencies,
|
||||
string? ClusterRedundancyMode = null);
|
||||
|
||||
/// <summary>The off-thread parse / plan step threw (unreadable bytes, a composer fault).</summary>
|
||||
private sealed record PlanFailed(object Incarnation, RebuildAddressSpace Request, IActorRef Requester,
|
||||
Exception Error, DataPlaneAuthorityProjection? Authority = null, byte[]? Artifact = null);
|
||||
Exception Error, DataPlaneAuthorityProjection? Authority = null, byte[]? Artifact = null,
|
||||
string? ClusterRedundancyMode = null);
|
||||
|
||||
/// <summary>Test seams for the off-thread plan step. Production passes none.</summary>
|
||||
internal sealed class TestHooks
|
||||
@@ -189,6 +204,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
internal Action? BeforePlan { get; init; }
|
||||
internal Action? BeforeComposition { get; init; }
|
||||
|
||||
/// <summary>#995 R-14: observes every artifact redundancy-mode read (the reading thread's managed id), so a test can
|
||||
/// assert it ran on the plan step rather than the actor thread.</summary>
|
||||
internal Action<int>? OnRedundancyModeRead { get; init; }
|
||||
|
||||
/// <summary>Replaces <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/> (a test makes it throw).</summary>
|
||||
internal Func<ParsedDeploymentArtifact, string, DataPlaneAuthorityProjection>? ParseAuthority { get; init; }
|
||||
}
|
||||
@@ -484,12 +503,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
IDataPlaneAuthoritySink? dataPlaneAuthority = null,
|
||||
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
|
||||
DataConnections.DataConnectionWarmRoleView? dataWarmRole = null,
|
||||
DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) =>
|
||||
DataConnections.DataConnectionDeploymentRuntime? dataConnections = null,
|
||||
WarmRedundancySettings? redundancy = null) =>
|
||||
// CreateBy, not Create(expression): Akka's expression path activates through a PUBLIC constructor, and the
|
||||
// seam-carrying constructor is internal so the test seams stay off the public API (review M3).
|
||||
Akka.Actor.Props.CreateBy(new TestProducer(() => new OpcUaPublishActor(
|
||||
sink, NullServiceLevelPublisher.Instance, false, localNode, null, applier, null, null, null, null,
|
||||
false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null,
|
||||
false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null, redundancy: redundancy,
|
||||
catalogCoordinator: catalogCoordinator, dataWarmRole: dataWarmRole, dataConnections: dataConnections)));
|
||||
|
||||
/// <summary>Produces the actor through its internal (seam-carrying) constructor, for <see cref="PropsForTests(IOpcUaAddressSpaceSink, AddressSpaceApplier?, TestHooks?, int, NodeId?, IDataPlaneAuthoritySink?)"/>.</summary>
|
||||
@@ -877,16 +897,23 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
|
||||
private void HandleRebuild(RebuildAddressSpace msg)
|
||||
{
|
||||
// #995 R-14: hash the artifact ONCE; the catalog attempt, the data-catalog generation and the authority revision
|
||||
// all reuse it. The redundancy-mode cross-check is no longer a second full parse here: the plan step reads it
|
||||
// from its own parse, off this pinned thread (CheckRedundancyMode on PlanReady/PlanFailed).
|
||||
msg = WithArtifactRevision(msg);
|
||||
if (_catalogCoordinator is not null && msg.CatalogAttempt is null)
|
||||
{
|
||||
var revision = msg.Artifact is { Length: > 0 } bytes
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)) : "unavailable";
|
||||
msg = msg with { CatalogAttempt = _catalogCoordinator.BeginAttempt(revision), StageCatalog = true };
|
||||
}
|
||||
if (msg.Artifact is { Length: > 0 } artifact) CheckRedundancyMode(artifact);
|
||||
msg = msg with { CatalogAttempt = _catalogCoordinator.BeginAttempt(msg.ArtifactRevision!), StageCatalog = true };
|
||||
StartRebuild(msg, Sender);
|
||||
}
|
||||
|
||||
/// <summary>#995 R-14: stamp the request with its artifact's SHA-256 (or "unavailable"), unless it already carries it.</summary>
|
||||
private static RebuildAddressSpace WithArtifactRevision(RebuildAddressSpace msg) =>
|
||||
msg.ArtifactRevision is not null ? msg : msg with
|
||||
{
|
||||
ArtifactRevision = msg.Artifact is { Length: > 0 } bytes
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)) : "unavailable",
|
||||
};
|
||||
|
||||
private void StageStandaloneCatalog(RebuildAddressSpace msg, ParsedDeploymentArtifact parsed)
|
||||
{
|
||||
if (_catalogCoordinator is null || msg.CatalogAttempt is null) return;
|
||||
@@ -938,9 +965,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
|
||||
// Close the data-service generation before any fallible parse or topology work. Ordinary
|
||||
// local OPC UA availability remains independent; remote/mapped access uses this barrier.
|
||||
var desiredRevision = msg.Artifact is { Length: > 0 } desiredBytes
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(desiredBytes))
|
||||
: "unavailable";
|
||||
msg = WithArtifactRevision(msg);
|
||||
var desiredRevision = msg.ArtifactRevision!;
|
||||
if (_catalogCoordinator is null) _dataCatalogEpoch = _dataCatalog.Begin(desiredRevision);
|
||||
|
||||
// Only a node with NO applier at all (the F10b/dev seam) falls back to the raw-sink rebuild — and that
|
||||
@@ -948,6 +974,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
// real driver node that has an applier (that node diff-and-applies from its in-hand bytes below).
|
||||
if (_applier is null)
|
||||
{
|
||||
if (msg.Artifact is { Length: > 0 } modeBytes && WantsRedundancyModeCheck())
|
||||
CheckRedundancyMode(ReadRedundancyModeSafe(modeBytes, _localNode!.Value.Value, _hooks));
|
||||
if (msg.StageCatalog && msg.Artifact is { Length: > 0 } standaloneBytes)
|
||||
{
|
||||
try { using var parsed = DeploymentArtifact.Open(standaloneBytes); StageStandaloneCatalog(msg, parsed); }
|
||||
@@ -1001,6 +1029,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
var baseComposition = _lastApplied;
|
||||
var nodeId = _localNode?.Value;
|
||||
var wantAuthority = _dataPlaneAuthority is not null && _catalogCoordinator is null;
|
||||
var wantMode = WantsRedundancyModeCheck();
|
||||
var incarnation = _incarnation;
|
||||
var hooks = _hooks;
|
||||
Task.Run<object>(() =>
|
||||
@@ -1010,6 +1039,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
// result — and an empty composition is not a benign no-op here (see the no-bytes guard above). The
|
||||
// throw lands in PlanFailed: logged at Error, _lastApplied untouched, last-known-good still served.
|
||||
using var parsed = DeploymentArtifact.Open(artifact);
|
||||
// #995 R-14: the redundancy-mode cross-check reads this parse (it used to be a second full inflate +
|
||||
// parse of the artifact on the pinned actor thread). Compared and logged back on the actor thread.
|
||||
string? clusterMode = null;
|
||||
if (wantMode && nodeId is not null)
|
||||
{
|
||||
hooks?.OnRedundancyModeRead?.Invoke(Environment.CurrentManagedThreadId);
|
||||
// A diagnostic read: whatever it throws must never fail the address-space plan.
|
||||
try { clusterMode = DeploymentArtifact.ReadClusterRedundancyMode(parsed, nodeId); }
|
||||
catch (Exception) { clusterMode = null; }
|
||||
}
|
||||
if (msg.StageCatalog) StageStandaloneCatalog(msg, parsed);
|
||||
// The authority parse is isolated from the address-space plan (review fix I2): before the plan moved
|
||||
// off-thread a throw here was contained by FeedDataPlaneAuthority's own catch; it must not now
|
||||
@@ -1038,13 +1077,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
? parsed.ParseComposition(nodeId, inconsistencies.Add)
|
||||
: parsed.ParseComposition();
|
||||
var plan = AddressSpacePlanner.Compute(baseComposition, composition);
|
||||
return new PlanReady(incarnation, msg, requester, artifact, authority, authorityError, composition, plan, inconsistencies);
|
||||
return new PlanReady(incarnation, msg, requester, artifact, authority, authorityError, composition, plan, inconsistencies,
|
||||
clusterMode);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Parsed revocations remain independent of topology planning. Transfer them back
|
||||
// to the actor thread even when no address-space plan could be constructed.
|
||||
return new PlanFailed(incarnation, msg, requester, ex, authority, artifact);
|
||||
return new PlanFailed(incarnation, msg, requester, ex, authority, artifact, clusterMode);
|
||||
}
|
||||
})
|
||||
.PipeTo(Self, failure: ex => new PlanFailed(incarnation, msg, requester, ex));
|
||||
@@ -1053,6 +1093,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
private void HandlePlanReady(PlanReady ready)
|
||||
{
|
||||
if (IsFromAnotherIncarnation(ready.Incarnation, ready.Request, ready.Requester)) return;
|
||||
CheckRedundancyMode(ready.ClusterRedundancyMode);
|
||||
|
||||
if (ready.AuthorityError is { } authorityError)
|
||||
_log.Error(authorityError,
|
||||
@@ -1076,9 +1117,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
private void HandlePlanFailed(PlanFailed failed)
|
||||
{
|
||||
if (IsFromAnotherIncarnation(failed.Incarnation, failed.Request, failed.Requester)) return;
|
||||
CheckRedundancyMode(failed.ClusterRedundancyMode);
|
||||
|
||||
if (failed.Authority is not null && failed.Artifact is not null)
|
||||
FeedDataPlaneAuthority(failed.Authority, failed.Artifact);
|
||||
FeedDataPlaneAuthority(failed.Authority, failed.Artifact, failed.Request.ArtifactRevision);
|
||||
|
||||
_planInFlight = false;
|
||||
_log.Error(failed.Error, "OpcUaPublish: rebuild pipeline threw (correlation={Correlation})", failed.Request.Correlation);
|
||||
@@ -1491,6 +1533,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
outcome = (true, $"address-space completion threw: {ex.Message}");
|
||||
}
|
||||
|
||||
// #995 R-11: captured before the replay scope is reset — a rebuild (or the applier-less raw-sink rebuild) recreated
|
||||
// every node, so the driver host must re-seed values it skipped re-subscribing.
|
||||
var rebuilt = _applier is null || _replayScope.AllVariables;
|
||||
|
||||
// Land what arrived while the plan was in flight on the nodes the apply just created — before the answer,
|
||||
// so "applied" means the deferred first values are on the address space too (review fix C1).
|
||||
ReplayDeferredWrites(_replayScope);
|
||||
@@ -1504,7 +1550,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
|
||||
if (msg.ReportOutcome)
|
||||
requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason));
|
||||
requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason,
|
||||
AddressSpaceRebuilt: rebuilt));
|
||||
}
|
||||
|
||||
/// <summary>The actor-thread half of a rebuild: install the artifact's authority, apply the plan through the
|
||||
@@ -1580,7 +1627,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
// feeding this after that return would leave a revoked key authenticating until some unrelated
|
||||
// structural change happened to redeploy. Authorization and topology change on their own
|
||||
// schedules.
|
||||
if (ready.Authority is not null) FeedDataPlaneAuthority(ready.Authority, ready.Artifact);
|
||||
if (ready.Authority is not null) FeedDataPlaneAuthority(ready.Authority, ready.Artifact, ready.Request.ArtifactRevision);
|
||||
|
||||
var composition = ready.Composition;
|
||||
var plan = ready.Plan;
|
||||
@@ -1870,7 +1917,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// <param name="projection">The keys + grants decoded (off-thread) from the rebuild's single parse of the artifact.</param>
|
||||
/// <param name="artifactBytes">The RAW artifact bytes — hashed for the revision id, which must be
|
||||
/// SHA-256 of the exact blob (see below); never re-parsed here.</param>
|
||||
private void FeedDataPlaneAuthority(DataPlaneAuthorityProjection projection, byte[] artifactBytes)
|
||||
/// <param name="revision">#995 R-14: the request's already-computed SHA-256 of <paramref name="artifactBytes"/>; hashed
|
||||
/// here only when absent.</param>
|
||||
private void FeedDataPlaneAuthority(DataPlaneAuthorityProjection projection, byte[] artifactBytes, string? revision = null)
|
||||
{
|
||||
if (_dataPlaneAuthority is null) return;
|
||||
|
||||
@@ -1880,7 +1929,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
// which is what lets a node recognise a re-applied revision without the hash riding the wire.
|
||||
// Hashed off the RAW bytes for exactly that reason: a re-serialisation of the parsed document
|
||||
// would be a different byte sequence and would not match the deployment's RevisionHash.
|
||||
var revision = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(artifactBytes));
|
||||
revision ??= Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(artifactBytes));
|
||||
var snapshot = _dataPlaneAuthority.Apply(
|
||||
projection.ClusterId, revision, projection.Keys, projection.Grants, projection.ScopePaths,
|
||||
projection.EquipmentScopePaths, projection.ScriptedAlarmOwners, projection.UnsFolderScopes,
|
||||
@@ -2374,21 +2423,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// counts <c>otopcua.redundancy.mode_mismatch</c>. The node keeps its local mode — the only value available
|
||||
/// before SDK start. <c>Unset</c> has opted out and is not checked.
|
||||
/// </summary>
|
||||
/// <param name="artifact">The applied artifact bytes.</param>
|
||||
private void CheckRedundancyMode(byte[] artifact)
|
||||
/// <param name="clusterMode">The artifact's cluster mode, read off the plan step's parse (#995 R-14); null when the
|
||||
/// artifact does not say or could not be read.</param>
|
||||
private void CheckRedundancyMode(string? clusterMode)
|
||||
{
|
||||
if (_redundancy.Mode == OpcUaRedundancyMode.Unset || _localNode is null) return;
|
||||
string? clusterMode;
|
||||
try
|
||||
{
|
||||
clusterMode = DeploymentArtifact.ReadClusterRedundancyMode(artifact, _localNode.Value.Value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Debug(ex, "OpcUaPublish: could not read the artifact's cluster RedundancyMode");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!WantsRedundancyModeCheck()) return;
|
||||
if (clusterMode is null) return;
|
||||
if (string.Equals(clusterMode, _redundancy.Mode.ToString(), StringComparison.OrdinalIgnoreCase)) return;
|
||||
OtOpcUaTelemetry.RedundancyModeMismatch.Add(1,
|
||||
@@ -2399,6 +2438,17 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
clusterMode, _redundancy.Mode, _redundancy.Mode);
|
||||
}
|
||||
|
||||
/// <summary>Whether the #717 deploy-time redundancy-mode cross-check applies on this node.</summary>
|
||||
private bool WantsRedundancyModeCheck() => _redundancy.Mode != OpcUaRedundancyMode.Unset && _localNode is not null;
|
||||
|
||||
/// <summary>The applier-less (dev) path's synchronous redundancy-mode read; never throws.</summary>
|
||||
private static string? ReadRedundancyModeSafe(byte[] artifact, string nodeId, TestHooks? hooks)
|
||||
{
|
||||
hooks?.OnRedundancyModeRead?.Invoke(Environment.CurrentManagedThreadId);
|
||||
try { return DeploymentArtifact.ReadClusterRedundancyMode(artifact, nodeId); }
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
private void ScheduleWarmRetry() => Timers.StartSingleTimer("warm-retry", WarmRetry.Instance, TimeSpan.FromSeconds(1));
|
||||
|
||||
/// <summary>The legacy role-only ServiceLevel switch (primary-leader → 240, primary → 200,
|
||||
|
||||
@@ -31,14 +31,22 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
|
||||
/// <b>Evaluation never blocks the dispatcher (lmxopcua#779, #750 P0).</b> The evaluator is called through
|
||||
/// <see cref="IVirtualTagEvaluator.EvaluateAsync"/>. A synchronously completed result (passthrough, the null
|
||||
/// evaluator, test fakes) is applied inline in the same message turn, exactly as before. An incomplete one — a
|
||||
/// Roslyn script run, up to its 2 s budget — switches the actor into an <i>evaluating</i> behaviour that
|
||||
/// <b>stashes</b> every dependency / reassert message, and the result comes back as a private completion
|
||||
/// message. Applying it unstashes everything in arrival order. So each trigger is still evaluated against
|
||||
/// the dependency map as it stood at that trigger, results are applied and published in trigger order, and
|
||||
/// the dedup / Bad-transition state sees exactly the sequence it saw when the call blocked — only the
|
||||
/// dispatcher thread is no longer held while the script runs. The dependency map is not touched while a run
|
||||
/// is in flight (the messages that would touch it are stashed), which is what makes handing it to the
|
||||
/// script on another thread safe.
|
||||
/// Roslyn script run, up to its 2 s budget — switches the actor into an <i>evaluating</i> behaviour, and the
|
||||
/// result comes back as a private completion message. The dependency map is not touched while a run is in
|
||||
/// flight, which is what makes handing it to the script on another thread safe.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Inputs that arrive during a run are coalesced (#995, review R-19).</b> They are held one slot per input —
|
||||
/// the newest value wins — and when the run completes they are applied together and evaluated <b>once</b>, stamped
|
||||
/// with the newest arrival's timestamp (the rule a batched mux burst already follows). They used to be stashed one
|
||||
/// message per trigger and replayed as one script run each, so a slow script (or the out-of-process runner under
|
||||
/// load) built an unbounded backlog of evaluations against inputs that were already superseded, with O(M²)
|
||||
/// re-stash hops. The backlog is now bounded by the tag's input count. Other messages (reassert, runner recovery,
|
||||
/// source-binding retry, projected wakes) are still stashed and run after the coalesced evaluation starts.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The value dedup compares one-dimensional arrays element-wise (#995), so an array-typed tag whose output did not
|
||||
/// change is not republished, re-routed to its dependents and historized on every evaluation.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
@@ -135,6 +143,10 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
private readonly Dictionary<string, DataValueSnapshot> _dependencies = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, Core.Abstractions.DataConnections.IProjectedSamplePublicationProof> _projectedDependencyProofs = new(StringComparer.Ordinal);
|
||||
|
||||
// #995 (R-19): inputs that arrived while a run was in flight, latest per input; applied when it completes.
|
||||
private readonly Dictionary<string, DependencyValueChanged> _heldInputs = new(StringComparer.Ordinal);
|
||||
private DateTime _heldTimestampUtc;
|
||||
|
||||
private bool _hasLastValue;
|
||||
private object? _lastValue;
|
||||
|
||||
@@ -436,14 +448,75 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
if (msg.ActorIncarnation != _actorIncarnation) return;
|
||||
UnbecomeStacked();
|
||||
ApplyEvaluation(msg.Evaluation, msg.WorstInputStatus, msg.TimestampUtc);
|
||||
// #995 (R-19): every input that arrived during the run lands now, at once, and is evaluated ONCE —
|
||||
// before the stashed control messages, so a reassert queued behind the run re-emits the newest state.
|
||||
ReleaseHeldInputs();
|
||||
Stash.UnstashAll();
|
||||
});
|
||||
// A timer tick during a run is dropped, not stashed: the run in flight IS this interval's evaluation,
|
||||
// and stashing would replay a backlog of ticks (one script run each) after a slow script (#783).
|
||||
Receive<TimerTick>(_ => { });
|
||||
// #995 (R-19): inputs are folded, latest value per input wins, instead of stashed one message per trigger.
|
||||
Receive<DependencyValueChanged>(HoldInput);
|
||||
Receive<DependencyValueBatch>(msg =>
|
||||
{
|
||||
var items = msg.Items;
|
||||
for (var i = 0; i < items.Count; i++) HoldInput(items[i]);
|
||||
});
|
||||
ReceiveAny(_ => Stash.Stash());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 (R-19): an input that arrived while a run is in flight. The dependency map cannot change under the
|
||||
/// running script (it is handed to it on another thread), so the value is held here — one slot per input,
|
||||
/// the newest wins — and applied when the run completes. This bounds the backlog by the tag's input count,
|
||||
/// where stashing grew it by one message per trigger and replayed them as one script run each (O(M²)
|
||||
/// re-stash hops under a slow script).
|
||||
/// </summary>
|
||||
/// <param name="item">The arrived input.</param>
|
||||
private void HoldInput(DependencyValueChanged item)
|
||||
{
|
||||
_heldInputs[item.TagId] = item;
|
||||
_heldTimestampUtc = item.TimestampUtc;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies every held input (see <see cref="HoldInput"/>) to the dependency map and, for a change-triggered tag,
|
||||
/// evaluates once against the result — stamped with the newest arrival's timestamp, the same rule
|
||||
/// <see cref="OnDependencyBatch"/> applies to a mux burst. No-op when nothing arrived during the run.
|
||||
/// </summary>
|
||||
private void ReleaseHeldInputs()
|
||||
{
|
||||
if (_heldInputs.Count == 0) return;
|
||||
foreach (var item in _heldInputs.Values)
|
||||
{
|
||||
SetDependencyProof(item);
|
||||
_dependencies[item.TagId] = new DataValueSnapshot(item.Value, item.StatusCode, item.TimestampUtc, item.TimestampUtc);
|
||||
}
|
||||
_heldInputs.Clear();
|
||||
if (_changeTriggered) Evaluate(_heldTimestampUtc);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The value dedup's equality: <see cref="object.Equals(object?, object?)"/>, except that two one-dimensional
|
||||
/// arrays compare element by element (#995, R-19). Each evaluation result is a fresh copy, so reference equality
|
||||
/// made an array-typed tag publish — and re-trigger its dependents and historize — on every evaluation even when
|
||||
/// its output never changed. Arrays of different element types never compare equal.
|
||||
/// </summary>
|
||||
/// <param name="a">The last published value.</param>
|
||||
/// <param name="b">The new value.</param>
|
||||
/// <returns>True when the two values are the same output.</returns>
|
||||
internal static bool SameValue(object? a, object? b)
|
||||
{
|
||||
if (a is Array x && b is Array y)
|
||||
{
|
||||
if (ReferenceEquals(x, y)) return true;
|
||||
if (x.Rank != 1 || y.Rank != 1 || x.GetType() != y.GetType()) return false;
|
||||
return System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(x, y);
|
||||
}
|
||||
return Equals(a, b);
|
||||
}
|
||||
|
||||
private static Task<VirtualTagEvalResult> FreezeEvaluation(Task<VirtualTagEvalResult> task)
|
||||
{
|
||||
if (!task.IsCompletedSuccessfully || !task.Result.Success || ReferenceEquals(task.Result, VirtualTagEvalResult.NoChange))
|
||||
@@ -542,7 +615,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
// Dedup on (value, STATUS) — 02/S14 generalising 02/S13's recover-from-Bad bypass. Keying on
|
||||
// value alone swallows every recovery whose value is unchanged, which is what a device coming
|
||||
// back usually produces, and the node then stays Bad forever.
|
||||
if (_hasPublished && _lastPublishedStatus == worst && _hasLastValue && Equals(_lastValue, result.Value))
|
||||
if (_hasPublished && _lastPublishedStatus == worst && _hasLastValue && SameValue(_lastValue, result.Value))
|
||||
{
|
||||
OtOpcUaTelemetry.VirtualTagEval.Add(1, new KeyValuePair<string, object?>("outcome", "skip"));
|
||||
return;
|
||||
|
||||
@@ -61,6 +61,22 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
|
||||
private VirtualTagHostRestarted() { }
|
||||
}
|
||||
/// <summary>
|
||||
/// #995 (review R-17): re-attempt the data-plane source binding of the tags the last apply could not bind —
|
||||
/// and nothing else. The retry used to re-deliver the whole <see cref="ApplyVirtualTags"/> every 250 ms with no
|
||||
/// backoff, so every attempt lifted the run guard's quarantines (re-running a runaway script), re-asserted every
|
||||
/// surviving child, republished every disabled tag's <c>BadOutOfService</c> and recomputed the cycle graph.
|
||||
/// </summary>
|
||||
/// <param name="Attempt">Zero-based attempt number; the delay before the next attempt doubles with it.</param>
|
||||
private sealed record RetrySourceBindings(int Attempt);
|
||||
|
||||
private const string SourceBindingRetryTimerKey = "source-binding-retry";
|
||||
|
||||
/// <summary>First source-binding retry delay (#995). Doubles per failed attempt up to <see cref="SourceBindingRetryCap"/>.</summary>
|
||||
internal static readonly TimeSpan SourceBindingRetryInitial = TimeSpan.FromMilliseconds(250);
|
||||
|
||||
/// <summary>Longest source-binding retry delay (#995).</summary>
|
||||
internal static readonly TimeSpan SourceBindingRetryCap = TimeSpan.FromSeconds(5);
|
||||
|
||||
private readonly IActorRef? _publishActor;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
|
||||
@@ -86,6 +102,11 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
private readonly HashSet<string> _deployedKeys = new(StringComparer.Ordinal);
|
||||
// Keys on a VirtualTag dependency cycle (lmxopcua#791 runtime backstop): their outputs are never routed.
|
||||
private readonly HashSet<string> _unroutedKeys = new(StringComparer.Ordinal);
|
||||
// #995 (R-17): enabled tags of the current apply whose source binding failed, so no child was spawned yet.
|
||||
private readonly HashSet<string> _unboundEnabled = new(StringComparer.Ordinal);
|
||||
// #995 (R-17): disabled tags of the current apply whose source binding failed, so their BadOutOfService did not
|
||||
// reach the data plane yet (the OPC UA node and the mux already have it).
|
||||
private readonly HashSet<string> _unboundDisabled = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Factory method to create Props for a VirtualTagHostActor.</summary>
|
||||
/// <param name="publishActor">The OPC UA publish actor that consumes
|
||||
@@ -124,6 +145,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
_telemetryHub = telemetryHub;
|
||||
|
||||
Receive<ApplyVirtualTags>(OnApply);
|
||||
Receive<RetrySourceBindings>(OnRetrySourceBindings);
|
||||
Receive<VirtualTagActor.EvaluationResult>(OnResult);
|
||||
Receive<Terminated>(OnChildTerminated);
|
||||
}
|
||||
@@ -138,7 +160,9 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
|
||||
private void OnApply(ApplyVirtualTags msg)
|
||||
{
|
||||
Timers.Cancel("source-binding-retry");
|
||||
Timers.Cancel(SourceBindingRetryTimerKey);
|
||||
_unboundEnabled.Clear();
|
||||
_unboundDisabled.Clear();
|
||||
// lmxopcua#978 (review R-5): drop a plan whose NodeId cannot be built BEFORE anything is stopped or
|
||||
// spawned. Unguarded, one illegal name threw here, supervision restarted the host (stopping every
|
||||
// child), and nothing re-sent ApplyVirtualTags — every VirtualTag on the node stopped evaluating, on
|
||||
@@ -236,42 +260,8 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
foreach (var p in evaluated)
|
||||
{
|
||||
if (_children.ContainsKey(p.VirtualTagId)) continue;
|
||||
|
||||
// Auto-name the child: vtagIds can contain characters illegal in actor names, so let Akka
|
||||
// assign a safe unique name. The child self-registers with the mux in PreStart.
|
||||
long? sourceIncarnation = null;
|
||||
if (_sourcePublisher is not null)
|
||||
{
|
||||
if (!_virtualSourceIncarnations.TryGetValue(p.VirtualTagId, out var currentToken))
|
||||
currentToken = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
|
||||
sourceIncarnation = currentToken;
|
||||
}
|
||||
if (sourceIncarnation is { } token)
|
||||
{
|
||||
_virtualSourceIncarnations[p.VirtualTagId] = token;
|
||||
if (!_sourcePublisher!.EnsureVirtualBinding(p.VirtualTagId, token))
|
||||
{
|
||||
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
var child = Context.ActorOf(VirtualTagActor.Props(
|
||||
virtualTagId: p.VirtualTagId,
|
||||
expression: p.Expression,
|
||||
evaluator: _evaluator,
|
||||
scriptId: p.VirtualTagId,
|
||||
publisherFactory: null,
|
||||
dependencyRefs: p.DependencyRefs,
|
||||
mux: _mux,
|
||||
telemetryHub: _telemetryHub,
|
||||
changeTriggered: p.ChangeTriggered,
|
||||
timerIntervalMs: p.TimerIntervalMs,
|
||||
sourcePublisher: _sourcePublisher,
|
||||
sourceIncarnation: sourceIncarnation));
|
||||
Context.Watch(child);
|
||||
_children[p.VirtualTagId] = child;
|
||||
newlySpawned.Add(p.VirtualTagId);
|
||||
_log.Debug("VirtualTagHost: spawned child for vtag {VirtualTagId}", p.VirtualTagId);
|
||||
if (TrySpawnChild(p)) newlySpawned.Add(p.VirtualTagId);
|
||||
else _unboundEnabled.Add(p.VirtualTagId);
|
||||
}
|
||||
|
||||
// Refresh the plan map to exactly the desired set so the next apply can detect in-place
|
||||
@@ -319,7 +309,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
if (_sourcePublisher is not null &&
|
||||
!_sourcePublisher.EnsureVirtualBinding(p.VirtualTagId, _virtualSourceIncarnations[p.VirtualTagId]))
|
||||
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
|
||||
_unboundDisabled.Add(p.VirtualTagId);
|
||||
var nodeId = NodeIdFor(p);
|
||||
var now = DateTime.UtcNow;
|
||||
if (_sourcePublisher?.TryCaptureVirtual(p.VirtualTagId, out var ticket) == true)
|
||||
@@ -329,10 +319,102 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
_mux?.Tell(new DependencyMuxActor.VirtualTagOutput(nodeId, null, now, OpcUaStatus.BadOutOfService));
|
||||
}
|
||||
|
||||
if (_unboundEnabled.Count + _unboundDisabled.Count > 0)
|
||||
{
|
||||
// One degraded line per apply; the retries themselves log only at Debug, and once more on recovery.
|
||||
_log.Warning("VirtualTagHost: {0} VirtualTag(s) could not bind their data-plane source ({1}); " +
|
||||
"retrying only those, with backoff up to {2}",
|
||||
_unboundEnabled.Count + _unboundDisabled.Count,
|
||||
string.Join(", ", _unboundEnabled.Concat(_unboundDisabled).Take(10)), SourceBindingRetryCap);
|
||||
Timers.StartSingleTimer(SourceBindingRetryTimerKey, new RetrySourceBindings(0), SourceBindingRetryInitial);
|
||||
}
|
||||
|
||||
_log.Debug("VirtualTagHost: applied (desired={Desired}, children={Children}, disabled={Disabled})",
|
||||
desired.Count, _children.Count, plans.Count - evaluated.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spawns the child for <paramref name="p"/> once its data-plane source binding (when a source publisher is
|
||||
/// wired) is established. Returns false — and spawns nothing — when the binding failed; the caller retries.
|
||||
/// </summary>
|
||||
/// <param name="p">An enabled plan with no live child.</param>
|
||||
/// <returns>True when the child was spawned.</returns>
|
||||
private bool TrySpawnChild(EquipmentVirtualTagPlan p)
|
||||
{
|
||||
long? sourceIncarnation = null;
|
||||
if (_sourcePublisher is not null)
|
||||
{
|
||||
if (!_virtualSourceIncarnations.TryGetValue(p.VirtualTagId, out var token))
|
||||
token = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
|
||||
_virtualSourceIncarnations[p.VirtualTagId] = token;
|
||||
sourceIncarnation = token;
|
||||
if (!_sourcePublisher.EnsureVirtualBinding(p.VirtualTagId, token)) return false;
|
||||
}
|
||||
|
||||
// Auto-name the child: vtagIds can contain characters illegal in actor names, so let Akka
|
||||
// assign a safe unique name. The child self-registers with the mux in PreStart.
|
||||
var child = Context.ActorOf(VirtualTagActor.Props(
|
||||
virtualTagId: p.VirtualTagId,
|
||||
expression: p.Expression,
|
||||
evaluator: _evaluator,
|
||||
scriptId: p.VirtualTagId,
|
||||
publisherFactory: null,
|
||||
dependencyRefs: p.DependencyRefs,
|
||||
mux: _mux,
|
||||
telemetryHub: _telemetryHub,
|
||||
changeTriggered: p.ChangeTriggered,
|
||||
timerIntervalMs: p.TimerIntervalMs,
|
||||
sourcePublisher: _sourcePublisher,
|
||||
sourceIncarnation: sourceIncarnation));
|
||||
Context.Watch(child);
|
||||
_children[p.VirtualTagId] = child;
|
||||
_log.Debug("VirtualTagHost: spawned child for vtag {VirtualTagId}", p.VirtualTagId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 (R-17): re-attempts only the bindings the last apply could not make. An enabled tag that binds gets its
|
||||
/// child (fresh, so nothing to re-assert); a disabled tag that binds gets its <c>BadOutOfService</c> on the data
|
||||
/// plane. Nothing else of the apply is repeated. Still-unbound tags are retried after a doubling delay, capped at
|
||||
/// <see cref="SourceBindingRetryCap"/>; a new apply cancels the retry and starts over from its own failures.
|
||||
/// </summary>
|
||||
/// <param name="msg">The attempt.</param>
|
||||
private void OnRetrySourceBindings(RetrySourceBindings msg)
|
||||
{
|
||||
if (_sourcePublisher is null) { _unboundEnabled.Clear(); _unboundDisabled.Clear(); return; }
|
||||
|
||||
foreach (var id in _unboundEnabled.ToList())
|
||||
{
|
||||
// Gone from the plan set (a child terminated and was pruned) or already hosted: nothing left to bind.
|
||||
if (!_planByVtag.TryGetValue(id, out var plan) || _children.ContainsKey(id)) { _unboundEnabled.Remove(id); continue; }
|
||||
if (TrySpawnChild(plan)) _unboundEnabled.Remove(id);
|
||||
}
|
||||
|
||||
foreach (var id in _unboundDisabled.ToList())
|
||||
{
|
||||
if (!_virtualSourceIncarnations.TryGetValue(id, out var token)) { _unboundDisabled.Remove(id); continue; }
|
||||
if (!_sourcePublisher.EnsureVirtualBinding(id, token)) continue;
|
||||
_unboundDisabled.Remove(id);
|
||||
if (_sourcePublisher.TryCaptureVirtual(id, out var ticket))
|
||||
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(null, OpcUaStatus.BadOutOfService, null, null));
|
||||
}
|
||||
|
||||
var remaining = _unboundEnabled.Count + _unboundDisabled.Count;
|
||||
if (remaining == 0)
|
||||
{
|
||||
_log.Info("VirtualTagHost: every VirtualTag source binding is established (after {0} retry attempt(s))",
|
||||
msg.Attempt + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
var next = msg.Attempt + 1;
|
||||
var delay = TimeSpan.FromTicks(Math.Min(
|
||||
SourceBindingRetryCap.Ticks, SourceBindingRetryInitial.Ticks << Math.Min(next, 16)));
|
||||
_log.Debug("VirtualTagHost: {0} VirtualTag source binding(s) still unbound; retry {1} in {2}",
|
||||
remaining, next, delay);
|
||||
Timers.StartSingleTimer(SourceBindingRetryTimerKey, new RetrySourceBindings(next), delay);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#791 bookkeeping for the mux leg: release the keys that left the deployed set, and recompute which
|
||||
/// keys sit on a VirtualTag dependency cycle (an edge runs from a tag to every dependency that is itself a
|
||||
|
||||
Reference in New Issue
Block a user