feat(grpc-data): A1 ConditionStateHub — bounded partitions, per-reader reset, snapshot_complete readiness, F5 diagnostic; wired to the node manager

This commit is contained in:
Joseph Doherty
2026-11-24 09:24:28 -05:00
parent 6836efaeb9
commit 923c2511a3
5 changed files with 368 additions and 1 deletions
@@ -61,6 +61,8 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private readonly IProjectedBrowseAccess? _projectedBrowseAccess;
private readonly IProjectedDataAccess? _projectedDataAccess;
private readonly IProjectedHistoryAccess? _projectedHistoryAccess;
// A1 (plan §5.1): the condition-state hub the node manager's delta callback feeds. Invisible until A2.
private readonly IConditionStateSink? _conditionStateSink;
private readonly IFederatedProjectionCatalog? _projectedCatalog;
private readonly DataConnectionOptions _dataConnectionOptions;
@@ -167,9 +169,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
IProjectedBrowseAccess? projectedBrowseAccess = null,
IProjectedDataAccess? projectedDataAccess = null,
IFederatedProjectionCatalog? projectedCatalog = null,
IProjectedHistoryAccess? projectedHistoryAccess = null)
IProjectedHistoryAccess? projectedHistoryAccess = null,
IConditionStateSink? conditionStateSink = null)
{
_projectedHistoryAccess = projectedHistoryAccess;
_conditionStateSink = conditionStateSink;
_dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new();
_projectedBrowseAccess = projectedBrowseAccess;
_projectedDataAccess = projectedDataAccess;
@@ -269,6 +273,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_server.NodeManager.ProjectedBrowseClock = _time;
_server.NodeManager.ProjectedDataAccess = _projectedDataAccess;
_server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess;
_server.NodeManager.ConditionStateSink = _conditionStateSink;
if (_projectedCatalog is { } projectedCatalog)
_server.NodeManager.MappedSubjectResolver = (realm, identifier) =>
projectedCatalog.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns,
@@ -0,0 +1,203 @@
using System.Collections.Concurrent;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>
/// The origin's condition-state hub (plan §5.1, A1): the node manager's SDK-free delta callback lands here, in
/// bounded per-partition buffers, and A2's condition streams read from it. Header-gated and invisible until A2.
/// </summary>
/// <remarks>
/// <para>
/// <b>Never blocks the node manager.</b> <see cref="Append"/> and <see cref="Watermark"/> run under the node
/// manager's <c>Lock</c>: they take one partition's tiny lock, enqueue and return — no I/O, no wait. A full
/// partition evicts its oldest record and raises that partition's <b>floor</b>; a reader whose cursor sits below
/// the floor has lost a record and must reset to a fresh snapshot (<see cref="ConditionDeltaRead.ResetRequired"/>).
/// That is the plan's "partition epoch invalidated", made per reader so a caught-up reader is never reset.
/// </para>
/// <para>
/// <b>Versions are global.</b> One monotonically increasing version across partitions, so a snapshot slice's
/// watermark (taken under the same <c>Lock</c>) orders every delta for every condition in that slice.
/// </para>
/// <para>
/// <b><c>snapshot_complete</c> readiness</b> = the node manager's current apply has completed
/// (<see cref="OnApplyStateChanged"/>) AND this node holds its Primary verdict
/// (<see cref="IDriverPrimaryRoleSource.ShouldActAsPrimary"/>). Until both hold, A2 sends a Control <c>NotReady</c>.
/// </para>
/// <para>
/// <b>Unsignalled-state diagnostic (F5).</b> <see cref="ReportUnsignalled"/> records "initial alarm state not
/// signalled" per driver instance (elapsed time, condition count) and counts
/// <c>otopcua.dataconn.conditions.unsignalled</c>; a later signal clears it (<see cref="ClearUnsignalled"/>).
/// </para>
/// </remarks>
public sealed class ConditionStateHub : IConditionStateSink
{
/// <summary>Default partition count.</summary>
public const int DefaultPartitionCount = 16;
/// <summary>Default per-partition buffer capacity (records).</summary>
public const int DefaultPartitionCapacity = 8192;
private sealed class Partition
{
public readonly object Gate = new();
public readonly Queue<ConditionStateRecord> Buffer = new();
public long Floor;
}
private readonly Partition[] _partitions;
private readonly int _capacity;
private readonly IDriverPrimaryRoleSource? _primary;
private readonly ConcurrentDictionary<string, UnsignalledConditionState> _unsignalled = new(StringComparer.Ordinal);
private long _version;
private volatile bool _applyComplete;
/// <summary>Creates the hub.</summary>
/// <param name="primary">The node's Primary verdict, or null (never Primary ⇒ never snapshot-complete).</param>
/// <param name="partitionCount">Partition count (≥ 1).</param>
/// <param name="partitionCapacity">Records each partition retains (≥ 1).</param>
public ConditionStateHub(IDriverPrimaryRoleSource? primary = null, int partitionCount = DefaultPartitionCount,
int partitionCapacity = DefaultPartitionCapacity)
{
ArgumentOutOfRangeException.ThrowIfLessThan(partitionCount, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(partitionCapacity, 1);
_primary = primary;
_capacity = partitionCapacity;
_partitions = new Partition[partitionCount];
for (var i = 0; i < partitionCount; i++) _partitions[i] = new Partition();
}
/// <summary>The partition count.</summary>
public int PartitionCount => _partitions.Length;
/// <inheritdoc />
public long Watermark => Interlocked.Read(ref _version);
/// <summary>Whether the current address-space apply has completed.</summary>
public bool IsApplyComplete => _applyComplete;
/// <summary><c>snapshot_complete</c> may be sent: apply complete AND this node is Primary.</summary>
public bool IsSnapshotComplete => _applyComplete && _primary?.ShouldActAsPrimary == true;
/// <inheritdoc />
public long Append(ConditionStateRecord record)
{
ArgumentNullException.ThrowIfNull(record);
var p = _partitions[PartitionOf(record.Realm, record.ConditionId, _partitions.Length)];
lock (p.Gate)
{
// The version is taken inside the partition gate so each partition's buffer is in version order.
var version = Interlocked.Increment(ref _version);
if (p.Buffer.Count >= _capacity)
{
p.Floor = p.Buffer.Dequeue().Version;
OtOpcUaTelemetry.DataConnConditionPartitionOverflows.Add(1);
}
p.Buffer.Enqueue(record with { Version = version });
return version;
}
}
/// <inheritdoc />
public void OnApplyStateChanged(bool complete) => _applyComplete = complete;
/// <summary>The stable partition of a condition (FNV-1a over realm + id).</summary>
/// <param name="realm">The condition's realm.</param>
/// <param name="conditionId">The condition id.</param>
/// <param name="partitionCount">The partition count.</param>
/// <returns>The partition index.</returns>
public static int PartitionOf(AddressSpaceRealm realm, string conditionId, int partitionCount)
{
unchecked
{
var h = 2166136261u ^ (uint)realm;
h *= 16777619u;
foreach (var c in conditionId)
{
h = (h ^ c) * 16777619u;
}
return (int)(h % (uint)partitionCount);
}
}
/// <summary>
/// Read a partition's records with a version above <paramref name="afterVersion"/>, at most
/// <paramref name="max"/>. <see cref="ConditionDeltaRead.ResetRequired"/> when a record above the cursor was
/// already evicted — the reader must take a fresh snapshot of that partition.
/// </summary>
/// <param name="partition">The partition index.</param>
/// <param name="afterVersion">The reader's cursor (the slice watermark or the last version it applied).</param>
/// <param name="max">The most records to return.</param>
/// <returns>The read.</returns>
public ConditionDeltaRead Read(int partition, long afterVersion, int max = int.MaxValue)
{
var p = _partitions[partition];
lock (p.Gate)
{
if (afterVersion < p.Floor) return new ConditionDeltaRead(true, p.Floor, []);
var records = new List<ConditionStateRecord>();
foreach (var r in p.Buffer)
{
if (r.Version <= afterVersion) continue;
if (records.Count >= max) break;
records.Add(r);
}
return new ConditionDeltaRead(false, p.Floor, records);
}
}
/// <summary>Read every partition after one cursor (tests and diagnostics), in version order.</summary>
/// <param name="afterVersion">The cursor.</param>
/// <returns>The records, or null when any partition requires a reset.</returns>
public IReadOnlyList<ConditionStateRecord>? ReadAll(long afterVersion)
{
var all = new List<ConditionStateRecord>();
for (var i = 0; i < _partitions.Length; i++)
{
var read = Read(i, afterVersion);
if (read.ResetRequired) return null;
all.AddRange(read.Records);
}
all.Sort((a, b) => a.Version.CompareTo(b.Version));
return all;
}
/// <summary>F5: a driver's initial alarm state was not signalled in time — its conditions stay unknown.</summary>
/// <param name="driverInstanceId">The driver instance.</param>
/// <param name="elapsed">Time since its quality went Good.</param>
/// <param name="conditions">How many of its conditions are still unsignalled.</param>
public void ReportUnsignalled(string driverInstanceId, TimeSpan elapsed, int conditions)
{
ArgumentException.ThrowIfNullOrEmpty(driverInstanceId);
_unsignalled[driverInstanceId] = new UnsignalledConditionState(driverInstanceId, elapsed, conditions);
OtOpcUaTelemetry.DataConnConditionsUnsignalled.Add(conditions,
new KeyValuePair<string, object?>("driver", driverInstanceId));
}
/// <summary>A later signal (or the driver's removal) clears the diagnostic.</summary>
/// <param name="driverInstanceId">The driver instance.</param>
/// <returns>Whether a diagnostic was cleared.</returns>
public bool ClearUnsignalled(string driverInstanceId) => _unsignalled.TryRemove(driverInstanceId, out _);
/// <summary>The current "initial alarm state not signalled" diagnostics, by driver instance.</summary>
public IReadOnlyDictionary<string, UnsignalledConditionState> Unsignalled => _unsignalled;
}
/// <summary>One partition read.</summary>
/// <param name="ResetRequired">A record above the cursor was evicted; resnapshot the partition.</param>
/// <param name="Floor">The version of the last evicted record.</param>
/// <param name="Records">The records above the cursor, in version order.</param>
public sealed record ConditionDeltaRead(bool ResetRequired, long Floor, IReadOnlyList<ConditionStateRecord> Records);
/// <summary>The F5 data-connection diagnostic "initial alarm state not signalled".</summary>
/// <param name="DriverInstanceId">The driver instance.</param>
/// <param name="Elapsed">Time since its quality went Good when the timeout fired.</param>
/// <param name="Conditions">How many of its conditions were still unsignalled.</param>
public sealed record UnsignalledConditionState(string DriverInstanceId, TimeSpan Elapsed, int Conditions);
@@ -95,6 +95,12 @@ public static class ServiceCollectionExtensions
// publishes two verdicts into the same object rather than into two that disagree.
services.TryAddSingleton<RedundancyRoleView>();
services.TryAddSingleton<IDriverPrimaryRoleSource>(sp => sp.GetRequiredService<RedundancyRoleView>());
// A1 (grpc-data plan §5.1): the origin condition-state hub. The node manager's SDK-free delta callback feeds it;
// its snapshot_complete readiness reads the same Primary verdict. Header-gated and unread until A2.
services.TryAddSingleton(sp => new ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub(
sp.GetRequiredService<IDriverPrimaryRoleSource>()));
services.TryAddSingleton<ZB.MOM.WW.OtOpcUa.OpcUaServer.IConditionStateSink>(
sp => sp.GetRequiredService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub>());
// the continuous-historization capture verdict, registered here — unconditionally on
// every driver-role node — for the same reason as the line above, and NOT alongside the alarm