304 lines
16 KiB
C#
304 lines
16 KiB
C#
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
/// <summary>One chunk of a root-scoped condition item, ready to become a <see cref="DataSubscriptionConditions"/> frame.</summary>
|
|
/// <param name="EndsSnapshot">The last chunk of snapshot number <paramref name="Snapshot"/> (its delivery is reported back).</param>
|
|
internal sealed record ConditionChunk(bool IsSnapshot, int? Total, IReadOnlyList<DataConditionState> Items, bool SnapshotComplete,
|
|
int Snapshot = 0, bool EndsSnapshot = false);
|
|
|
|
/// <summary>The condition set an item may currently see: the catalog it was listed from and the listing (null = revoked).</summary>
|
|
internal sealed record ConditionItemScope(object Catalog, IReadOnlyList<ScopedCondition>? Conditions);
|
|
|
|
/// <summary>
|
|
/// A2 origin producer for ONE root-scoped condition item (plan §5.1 "A2 consumer of a sliced snapshot", §5.5 "Stream
|
|
/// mechanics"). Pull-based and single-threaded (the session's worker calls it): it never buffers more than one chunk, so
|
|
/// the session's bounded condition queue is the only buffer and a slow consumer back-pressures into the hub, whose
|
|
/// bounded partitions then evict — which this producer sees as a reader reset and answers with a fresh snapshot.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para><b>Snapshot.</b> The scope is listed first (export grant + origin ACL per placement, keyed); a listing above
|
|
/// the item's limit is reported as a snapshot-begin chunk carrying <c>total</c> and nothing else, before any record
|
|
/// (§5.5 admission before materialising). Otherwise <see cref="IOriginConditionSource.SnapshotConditions"/> is taken in
|
|
/// slices of at most the limit (the node manager clamps to 5,000 per hold); a begin chunk carries the copied count,
|
|
/// record chunks follow, and the last carries <c>snapshot_complete</c> only when
|
|
/// <see cref="ConditionStateHub.IsSnapshotCompleteFor"/> holds. An incomplete snapshot is retaken (rate-limited) once
|
|
/// the hub reports readiness.</para>
|
|
/// <para><b>Deltas</b> are replayed per hub partition from the snapshot's <c>StartCursor</c>; a delta for a condition
|
|
/// held in a slice at or below that slice's watermark is skipped (the slice already holds it). Versions are global, so
|
|
/// per-partition cursors are exact: a condition always lives in one partition.</para>
|
|
/// <para><b>Scope changes</b> (a deploy, an ACL or grant change that leaves the stream open): conditions that leave the
|
|
/// listing get a removal record; conditions that join it are copied with a small snapshot and sent as ordinary delta
|
|
/// records, so a deploy that adds or removes conditions arrives as delta records.</para>
|
|
/// </remarks>
|
|
internal sealed class ConditionItemStream
|
|
{
|
|
/// <summary>The most records one chunk carries.</summary>
|
|
internal const int MaxRecordsPerChunk = 128;
|
|
|
|
/// <summary>The least time between two snapshots of one item (re-snapshot storms after an overflow).</summary>
|
|
internal static readonly TimeSpan MinResnapshotInterval = TimeSpan.FromSeconds(1);
|
|
|
|
private readonly ConditionStateHub _hub;
|
|
private readonly IOriginConditionSource _source;
|
|
private readonly Func<ConditionItemScope> _scope;
|
|
private readonly int _limit;
|
|
private readonly bool _includeInfo;
|
|
private readonly TimeProvider _clock;
|
|
private readonly Queue<DataConditionState> _snapshotRecords = new();
|
|
private readonly Dictionary<OriginConditionRef, long> _sliceWatermarks = new();
|
|
private readonly Dictionary<OriginConditionRef, ScopedCondition> _inScope = new();
|
|
private readonly HashSet<OriginConditionRef> _sent = new();
|
|
private readonly Queue<DataConditionState> _pendingDeltas = new();
|
|
private long[] _cursors = [];
|
|
private object? _catalog;
|
|
private State _state = State.NeedSnapshot;
|
|
private bool _beginSent, _snapshotComplete, _retakeWhenReady;
|
|
private int _deliveredSnapshot;
|
|
private int _total;
|
|
private long _lastSnapshotAt = long.MinValue;
|
|
|
|
private enum State { NeedSnapshot, Snapshotting, Live, OverCapacity, Revoked }
|
|
|
|
internal ConditionItemStream(ConditionStateHub hub, IOriginConditionSource source, Func<ConditionItemScope> scope, int limit,
|
|
bool includeInfo, TimeProvider clock)
|
|
{
|
|
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
|
|
_source = source ?? throw new ArgumentNullException(nameof(source));
|
|
_scope = scope ?? throw new ArgumentNullException(nameof(scope));
|
|
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
|
ArgumentOutOfRangeException.ThrowIfLessThan(limit, 1);
|
|
_limit = limit;
|
|
_includeInfo = includeInfo;
|
|
}
|
|
|
|
/// <summary>The item's grant was withdrawn (its scope listing became null): the session must stop delivering it.</summary>
|
|
internal bool IsRevoked => _state == State.Revoked;
|
|
|
|
/// <summary>The last listing exceeded the item's limit (only <c>total</c> was reported).</summary>
|
|
internal bool IsOverCapacity => _state == State.OverCapacity;
|
|
|
|
/// <summary>Whether the last snapshot of this item was sent with <c>snapshot_complete</c>.</summary>
|
|
internal bool SnapshotComplete => _snapshotComplete;
|
|
|
|
/// <summary>How many snapshots were taken (the first plus every reset or retake).</summary>
|
|
internal int Snapshots { get; private set; }
|
|
|
|
/// <summary>How many snapshots were forced by a hub reader reset (records evicted before this item read them).</summary>
|
|
internal int Resets { get; private set; }
|
|
|
|
/// <summary>
|
|
/// A reset arrived while the previous snapshot was still being delivered: the consumer cannot drain one snapshot
|
|
/// before the hub evicts. The session answers it with a stream Reset.
|
|
/// </summary>
|
|
internal bool Overflowed { get; private set; }
|
|
|
|
/// <summary>The session delivered the last chunk of snapshot <paramref name="snapshot"/> (any thread).</summary>
|
|
internal void SnapshotDelivered(int snapshot)
|
|
{
|
|
int current;
|
|
do current = Volatile.Read(ref _deliveredSnapshot);
|
|
while (snapshot > current && Interlocked.CompareExchange(ref _deliveredSnapshot, snapshot, current) != current);
|
|
}
|
|
|
|
/// <summary>Produce the next chunk, or null when there is nothing to send now.</summary>
|
|
internal ConditionChunk? Next()
|
|
{
|
|
if (_state is State.Revoked) return null;
|
|
var scope = _scope();
|
|
if (scope.Conditions is null) { _state = State.Revoked; return null; }
|
|
if (_state == State.NeedSnapshot)
|
|
{
|
|
if (!CanSnapshotNow()) return null;
|
|
return TakeSnapshot(scope);
|
|
}
|
|
if (_state == State.OverCapacity)
|
|
{
|
|
// Re-admit only when the listing itself changed (a deploy); otherwise stay parked with total reported.
|
|
if (ReferenceEquals(scope.Catalog, _catalog) || !CanSnapshotNow()) return null;
|
|
return TakeSnapshot(scope);
|
|
}
|
|
if (_state == State.Snapshotting) return NextSnapshotChunk();
|
|
// Live.
|
|
if (_retakeWhenReady && _hub.IsSnapshotComplete && CanSnapshotNow()) return TakeSnapshot(scope);
|
|
if (!ReferenceEquals(scope.Catalog, _catalog)) ApplyScopeChange(scope);
|
|
if (!ReadDeltas()) return ResetSnapshot(scope);
|
|
return NextDeltaChunk();
|
|
}
|
|
|
|
private bool CanSnapshotNow() =>
|
|
_lastSnapshotAt == long.MinValue || _clock.GetElapsedTime(_lastSnapshotAt) >= MinResnapshotInterval;
|
|
|
|
private ConditionChunk? ResetSnapshot(ConditionItemScope scope)
|
|
{
|
|
Resets++;
|
|
OtOpcUaTelemetry.DataConnConditionResyncs.Add(1);
|
|
_state = State.NeedSnapshot;
|
|
return CanSnapshotNow() ? TakeSnapshot(scope) : null;
|
|
}
|
|
|
|
private ConditionChunk TakeSnapshot(ConditionItemScope scope)
|
|
{
|
|
Snapshots++;
|
|
_lastSnapshotAt = _clock.GetTimestamp();
|
|
_catalog = scope.Catalog;
|
|
_snapshotRecords.Clear(); _sliceWatermarks.Clear(); _pendingDeltas.Clear(); _sent.Clear(); _inScope.Clear();
|
|
_beginSent = false; _snapshotComplete = false; _retakeWhenReady = false;
|
|
var listing = scope.Conditions!;
|
|
if (listing.Count > _limit)
|
|
{
|
|
// §5.5: total above the limit is reported at snapshot begin, before (and instead of) any record.
|
|
_state = State.OverCapacity;
|
|
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
|
|
_total = listing.Count;
|
|
return new ConditionChunk(true, listing.Count, [], false);
|
|
}
|
|
foreach (var condition in listing) _inScope[condition.Ref] = condition;
|
|
var slices = _source.SnapshotConditions((realm, id) => _inScope.ContainsKey(new(realm, id)), _limit);
|
|
var records = new List<(ConditionStateRecord Record, long Watermark)>();
|
|
foreach (var slice in slices)
|
|
foreach (var record in slice.Records)
|
|
records.Add((record, slice.Watermark));
|
|
if (records.Count > _limit)
|
|
{
|
|
_state = State.OverCapacity;
|
|
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
|
|
_total = records.Count;
|
|
return new ConditionChunk(true, records.Count, [], false);
|
|
}
|
|
var start = slices.Count == 0 ? _hub.Watermark : slices[0].StartCursor;
|
|
_cursors = Enumerable.Repeat(start, _hub.PartitionCount).ToArray();
|
|
foreach (var (record, watermark) in records)
|
|
{
|
|
var key = new OriginConditionRef(record.Realm, record.ConditionId);
|
|
if (!_inScope.TryGetValue(key, out var scoped)) continue;
|
|
_sliceWatermarks[key] = watermark;
|
|
_sent.Add(key);
|
|
_snapshotRecords.Enqueue(Map(record with { Version = watermark }, scoped, includeInfo: _includeInfo));
|
|
}
|
|
_snapshotComplete = _hub.IsSnapshotCompleteFor(slices);
|
|
_retakeWhenReady = !_snapshotComplete;
|
|
_total = _snapshotRecords.Count;
|
|
_state = State.Snapshotting;
|
|
return NextSnapshotChunk();
|
|
}
|
|
|
|
private ConditionChunk NextSnapshotChunk()
|
|
{
|
|
if (!_beginSent)
|
|
{
|
|
_beginSent = true;
|
|
// The begin chunk carries only the count, so the consumer decides capacity before materialising anything.
|
|
if (_snapshotRecords.Count == 0)
|
|
{ _state = State.Live; return new ConditionChunk(true, _total, [], _snapshotComplete, Snapshots, EndsSnapshot: true); }
|
|
return new ConditionChunk(true, _total, [], false);
|
|
}
|
|
var batch = new List<DataConditionState>(Math.Min(MaxRecordsPerChunk, _snapshotRecords.Count));
|
|
while (batch.Count < MaxRecordsPerChunk && _snapshotRecords.TryDequeue(out var record)) batch.Add(record);
|
|
var last = _snapshotRecords.Count == 0;
|
|
if (last) _state = State.Live;
|
|
return new ConditionChunk(true, null, batch, last && _snapshotComplete, Snapshots, EndsSnapshot: last);
|
|
}
|
|
|
|
/// <summary>Reads every partition after its cursor into the pending deltas. False when a reader reset is required.</summary>
|
|
private bool ReadDeltas()
|
|
{
|
|
if (_pendingDeltas.Count >= MaxRecordsPerChunk) return true;
|
|
for (var p = 0; p < _cursors.Length; p++)
|
|
{
|
|
var read = _hub.Read(p, _cursors[p], MaxRecordsPerChunk);
|
|
if (read.ResetRequired)
|
|
{
|
|
// Evicted while the last snapshot was still undelivered: the consumer cannot drain one snapshot in time.
|
|
if (Volatile.Read(ref _deliveredSnapshot) < Snapshots) Overflowed = true;
|
|
return false;
|
|
}
|
|
foreach (var record in read.Records)
|
|
{
|
|
_cursors[p] = record.Version;
|
|
var key = new OriginConditionRef(record.Realm, record.ConditionId);
|
|
if (!_inScope.TryGetValue(key, out var scoped)) continue;
|
|
// A1 replay contract: the slice already holds every change at or below its watermark.
|
|
if (_sliceWatermarks.TryGetValue(key, out var watermark) && record.Version <= watermark) continue;
|
|
if (record.Removed)
|
|
{
|
|
if (!_sent.Remove(key)) continue;
|
|
_sliceWatermarks.Remove(key);
|
|
_pendingDeltas.Enqueue(Map(record, scoped, includeInfo: false));
|
|
continue;
|
|
}
|
|
var first = _sent.Add(key);
|
|
_pendingDeltas.Enqueue(Map(record, scoped, includeInfo: first && _includeInfo));
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private ConditionChunk? NextDeltaChunk()
|
|
{
|
|
if (_pendingDeltas.Count == 0) return null;
|
|
var batch = new List<DataConditionState>(Math.Min(MaxRecordsPerChunk, _pendingDeltas.Count));
|
|
while (batch.Count < MaxRecordsPerChunk && _pendingDeltas.TryDequeue(out var record)) batch.Add(record);
|
|
return new ConditionChunk(false, null, batch, false);
|
|
}
|
|
|
|
/// <summary>A new catalog: conditions leaving the listing get a removal record; joining ones a small snapshot as deltas.</summary>
|
|
private void ApplyScopeChange(ConditionItemScope scope)
|
|
{
|
|
_catalog = scope.Catalog;
|
|
var listing = scope.Conditions!;
|
|
if (listing.Count > _limit)
|
|
{
|
|
// The deploy pushed this root over its limit: report it like a first snapshot would.
|
|
_state = State.NeedSnapshot;
|
|
_lastSnapshotAt = long.MinValue;
|
|
return;
|
|
}
|
|
var next = listing.ToDictionary(x => x.Ref);
|
|
var version = _hub.Watermark;
|
|
foreach (var (key, scoped) in _inScope)
|
|
{
|
|
if (next.ContainsKey(key)) continue;
|
|
_sliceWatermarks.Remove(key);
|
|
if (_sent.Remove(key))
|
|
_pendingDeltas.Enqueue(Removal(scoped, version));
|
|
}
|
|
var added = next.Keys.Where(k => !_inScope.ContainsKey(k)).ToHashSet();
|
|
_inScope.Clear();
|
|
foreach (var (key, scoped) in next) _inScope[key] = scoped;
|
|
if (added.Count == 0) return;
|
|
foreach (var slice in _source.SnapshotConditions((realm, id) => added.Contains(new(realm, id)), _limit))
|
|
foreach (var record in slice.Records)
|
|
{
|
|
var key = new OriginConditionRef(record.Realm, record.ConditionId);
|
|
if (!_inScope.TryGetValue(key, out var scoped)) continue;
|
|
_sliceWatermarks[key] = slice.Watermark;
|
|
_sent.Add(key);
|
|
_pendingDeltas.Enqueue(Map(record with { Version = slice.Watermark }, scoped, includeInfo: _includeInfo));
|
|
}
|
|
}
|
|
|
|
private static DataConditionState Removal(ScopedCondition scoped, long version) =>
|
|
new(scoped.Exported.ConditionKey, version, Removed: true, StateKnown: false, null, false, false, false, false, 0, 0, "",
|
|
0, null, 0, null, false, null);
|
|
|
|
/// <summary>Maps a node-manager record to the wire record. Never carries the origin ConditionId (a RawPath for native).</summary>
|
|
internal static DataConditionState Map(ConditionStateRecord record, ScopedCondition scoped, bool includeInfo)
|
|
{
|
|
var info = includeInfo && !record.Removed
|
|
? new DataConditionInfo(record.ConditionType ?? "", record.ConditionName ?? "",
|
|
(DataConditionSourceKind)(int)scoped.Exported.SourceKind,
|
|
scoped.Exported.Placements.Select(p => p.View).ToArray(), 0)
|
|
: null;
|
|
return new DataConditionState(scoped.Exported.ConditionKey, record.Version, record.Removed, record.StateKnown && !record.Removed,
|
|
info, record.Active, record.Acknowledged, record.Confirmed, record.Enabled, (int)record.Shelving, record.Severity,
|
|
record.Message ?? "", record.Quality,
|
|
record.UnshelveTimeUtc is { } unshelve ? new DateTimeOffset(DateTime.SpecifyKind(unshelve, DateTimeKind.Utc)) : null,
|
|
record.ConditionClass, new DateTimeOffset(DateTime.SpecifyKind(record.TimeUtc, DateTimeKind.Utc)), record.Retain,
|
|
new DataActivationMarker(record.Activation.Incarnation, record.Activation.Sequence), record.Comment, record.ClientUserId);
|
|
}
|
|
}
|