fix(grpc-data): A2 review S2/S3/S4/S5/N1/N2/N4/N5/N6 — bounded, effective-named, fair condition streams
S2: one condition item per (stream, root) (InvalidArgument + diagnostic), SubscriptionSessionLimits
.MaxConditionItems (32) per stream (LimitExceeded), each snapshot's estimated bytes charged against
the principal's snapshot memory budget until its last chunk is delivered (refused ⇒ retried).
S3: a native condition in a UNS listing is named by its placement's browse name (effective name);
a raw-derived message (raw name, raw leaf, RawPath) is replaced by it.
S4: the item limit rides ConditionItemScope and is re-read with every listing.
S5: chunk budget = min(256 KiB, MaxPendingBytes, MaxMessageBytes) − frame overhead; an oversized
record's free text is truncated (no split surrogate); one that cannot fit resets with a diagnostic.
N1: one queued v1 frame after every 8 condition frames. N2: removal/snapshot-begin bypass rule documented.
N4: min(limit, DefaultMaxConditionsPerHold) per Lock hold. N5: losing channel waits are reused.
N6: ConditionTestAssertions deleted; probe seams reduced to three primitives; class doc moved back.
S1 (tests): the fixture 'deploy' test renamed to what it is (a listing swap without an attempt);
a real LocalCatalogCoordinator republish ends the stream.
This commit is contained in:
@@ -10,8 +10,11 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
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>
|
||||
/// The condition set an item may currently see: the catalog it was listed from, the listing (null = revoked) and the
|
||||
/// item's current <c>MaxConditions</c> (A2 review S4: re-read with the listing, never frozen at admission).
|
||||
/// </summary>
|
||||
internal sealed record ConditionItemScope(object Catalog, IReadOnlyList<ScopedCondition>? Conditions, int Limit);
|
||||
|
||||
/// <summary>
|
||||
/// A2 origin producer for ONE root-scoped condition item (plan §5.1 "A2 consumer of a sliced snapshot", §5.5 "Stream
|
||||
@@ -30,11 +33,17 @@ internal sealed record ConditionItemScope(object Catalog, IReadOnlyList<ScopedCo
|
||||
/// <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>
|
||||
/// <para><b>Scope changes.</b> An origin deploy does NOT reach a live item: every deploy begins a catalog attempt, which
|
||||
/// changes the serving identity and ends the stream (§5.5 lifetime rule); the consumer reconnects and takes a complete
|
||||
/// snapshot. What does reach a live item is a listing change under the SAME catalog object being replaced without a
|
||||
/// serving change (today only a test catalog source does that): conditions that leave the listing get a removal record,
|
||||
/// conditions that join it a small snapshot sent as delta records.</para>
|
||||
/// <para><b>Bounds.</b> Each snapshot's estimated bytes are charged against the principal's snapshot memory budget
|
||||
/// until its last chunk is delivered (A2 review S2); a chunk never exceeds <see cref="ChunkBytes"/> (min of 256 KiB and
|
||||
/// the session's pending/message limits, S5), and a record too large for it has its free text (message, comment, user)
|
||||
/// truncated; one that cannot fit even so is reported through <see cref="Oversized"/>.</para>
|
||||
/// </remarks>
|
||||
internal sealed class ConditionItemStream
|
||||
internal sealed class ConditionItemStream : IDisposable
|
||||
{
|
||||
/// <summary>The most records one chunk carries.</summary>
|
||||
internal const int MaxRecordsPerChunk = 128;
|
||||
@@ -42,15 +51,22 @@ internal sealed class ConditionItemStream
|
||||
/// <summary>The most estimated bytes one chunk carries (the transport reserves ≤ the session's pending bytes per frame).</summary>
|
||||
internal const long MaxChunkBytes = 256 * 1024;
|
||||
|
||||
/// <summary>The least chunk budget that can carry a record (its fixed estimate plus a key and a marker).</summary>
|
||||
internal const long MinRecordBytes = 4096;
|
||||
|
||||
/// <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 Func<long, IDisposable?> _reserveSnapshot;
|
||||
private readonly object _leaseGate = new();
|
||||
private IDisposable? _snapshotLease;
|
||||
private int _leaseSnapshot;
|
||||
private int _limit;
|
||||
private readonly Queue<DataConditionState> _snapshotRecords = new();
|
||||
private readonly Dictionary<OriginConditionRef, long> _sliceWatermarks = new();
|
||||
private readonly Dictionary<OriginConditionRef, ScopedCondition> _inScope = new();
|
||||
@@ -66,18 +82,41 @@ internal sealed class ConditionItemStream
|
||||
|
||||
private enum State { NeedSnapshot, Snapshotting, Live, OverCapacity, Revoked }
|
||||
|
||||
internal ConditionItemStream(ConditionStateHub hub, IOriginConditionSource source, Func<ConditionItemScope> scope, int limit,
|
||||
bool includeInfo, TimeProvider clock)
|
||||
/// <param name="hub">The origin's condition-state hub.</param>
|
||||
/// <param name="source">The node manager's snapshot port.</param>
|
||||
/// <param name="scope">The item's current listing and limit.</param>
|
||||
/// <param name="includeInfo">Whether records carry <c>ConditionInfo</c>.</param>
|
||||
/// <param name="clock">The session clock.</param>
|
||||
/// <param name="reserveSnapshot">Charges a snapshot's estimated bytes (null = refused); default: never refused.</param>
|
||||
/// <param name="chunkBytes">The most estimated record bytes one chunk carries (≤ <see cref="MaxChunkBytes"/>).</param>
|
||||
internal ConditionItemStream(ConditionStateHub hub, IOriginConditionSource source, Func<ConditionItemScope> scope,
|
||||
bool includeInfo, TimeProvider clock, Func<long, IDisposable?>? reserveSnapshot = null, long chunkBytes = MaxChunkBytes)
|
||||
{
|
||||
_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;
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(chunkBytes, 1);
|
||||
_includeInfo = includeInfo;
|
||||
_reserveSnapshot = reserveSnapshot ?? NoReservation;
|
||||
ChunkBytes = Math.Min(chunkBytes, MaxChunkBytes);
|
||||
}
|
||||
|
||||
private static IDisposable? NoReservation(long bytes) => EmptyLease.Instance;
|
||||
private sealed class EmptyLease : IDisposable { internal static readonly EmptyLease Instance = new(); public void Dispose() { } }
|
||||
|
||||
/// <summary>The most estimated record bytes one chunk carries.</summary>
|
||||
internal long ChunkBytes { get; }
|
||||
|
||||
/// <summary>A record could not be made to fit <see cref="ChunkBytes"/>; the session ends the stream.</summary>
|
||||
internal bool Oversized { get; private set; }
|
||||
|
||||
/// <summary>Snapshots that could not be charged against the principal's memory budget (retried, rate-limited).</summary>
|
||||
internal int MemoryRejections { get; private set; }
|
||||
|
||||
/// <summary>The estimated bytes the current snapshot holds against the principal's budget (0 once delivered).</summary>
|
||||
internal long ChargedBytes { get; private set; }
|
||||
|
||||
/// <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;
|
||||
|
||||
@@ -105,6 +144,22 @@ internal sealed class ConditionItemStream
|
||||
int current;
|
||||
do current = Volatile.Read(ref _deliveredSnapshot);
|
||||
while (snapshot > current && Interlocked.CompareExchange(ref _deliveredSnapshot, snapshot, current) != current);
|
||||
lock (_leaseGate)
|
||||
if (_leaseSnapshot == snapshot) ReleaseLease();
|
||||
}
|
||||
|
||||
private void ReleaseLease()
|
||||
{
|
||||
var lease = _snapshotLease;
|
||||
_snapshotLease = null;
|
||||
ChargedBytes = 0;
|
||||
lease?.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Releases the snapshot memory charge (the item was removed or the stream ended).</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_leaseGate) ReleaseLease();
|
||||
}
|
||||
|
||||
/// <summary>Produce the next chunk, or null when there is nothing to send now.</summary>
|
||||
@@ -143,11 +198,48 @@ internal sealed class ConditionItemStream
|
||||
return CanSnapshotNow() ? TakeSnapshot(scope) : null;
|
||||
}
|
||||
|
||||
private ConditionChunk TakeSnapshot(ConditionItemScope scope)
|
||||
private int PerHold => Math.Min(_limit, OtOpcUaNodeManager.DefaultMaxConditionsPerHold);
|
||||
|
||||
/// <summary>Fits <paramref name="record"/> to the chunk budget and queues it; false (and <see cref="Oversized"/>) when it cannot fit.</summary>
|
||||
private bool Enqueue(Queue<DataConditionState> queue, DataConditionState record)
|
||||
{
|
||||
if (Fit(record, ChunkBytes) is not { } fitted) { Oversized = true; return false; }
|
||||
queue.Enqueue(fitted);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A2 review S5: a record whose estimate exceeds <paramref name="budget"/> has its free text truncated (message
|
||||
/// first, then comment, then client user id; never splitting a surrogate pair); null when even the fixed part does
|
||||
/// not fit. Key, version, state, marker and placements are never altered.
|
||||
/// </summary>
|
||||
internal static DataConditionState? Fit(DataConditionState record, long budget)
|
||||
{
|
||||
if (EstimatedBytes(record) <= budget) return record;
|
||||
var bare = record with { Message = "", Comment = record.Comment is null ? null : "", ClientUserId = record.ClientUserId is null ? null : "" };
|
||||
var chars = (budget - EstimatedBytes(bare)) / 4;
|
||||
if (chars < 0) return null;
|
||||
var message = Cut(record.Message, ref chars);
|
||||
var comment = record.Comment is null ? null : Cut(record.Comment, ref chars);
|
||||
var user = record.ClientUserId is null ? null : Cut(record.ClientUserId, ref chars);
|
||||
return record with { Message = message, Comment = comment, ClientUserId = user };
|
||||
|
||||
static string Cut(string text, ref long room)
|
||||
{
|
||||
var take = (int)Math.Min(text.Length, Math.Max(0, room));
|
||||
if (take > 0 && take < text.Length && char.IsHighSurrogate(text[take - 1])) take--;
|
||||
room -= take;
|
||||
return take == text.Length ? text : text[..take];
|
||||
}
|
||||
}
|
||||
|
||||
private ConditionChunk? TakeSnapshot(ConditionItemScope scope)
|
||||
{
|
||||
Snapshots++;
|
||||
_lastSnapshotAt = _clock.GetTimestamp();
|
||||
_catalog = scope.Catalog;
|
||||
_limit = scope.Limit;
|
||||
lock (_leaseGate) ReleaseLease();
|
||||
_snapshotRecords.Clear(); _sliceWatermarks.Clear(); _pendingDeltas.Clear(); _sent.Clear(); _inScope.Clear();
|
||||
_beginSent = false; _snapshotComplete = false; _retakeWhenReady = false;
|
||||
var listing = scope.Conditions!;
|
||||
@@ -160,7 +252,8 @@ internal sealed class ConditionItemStream
|
||||
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);
|
||||
// A2 review N4: at most DefaultMaxConditionsPerHold per node-manager Lock hold, so a large root slices.
|
||||
var slices = _source.SnapshotConditions((realm, id) => _inScope.ContainsKey(new(realm, id)), PerHold);
|
||||
var records = new List<(ConditionStateRecord Record, long Watermark)>();
|
||||
foreach (var slice in slices)
|
||||
foreach (var record in slice.Records)
|
||||
@@ -180,7 +273,21 @@ internal sealed class ConditionItemStream
|
||||
if (!_inScope.TryGetValue(key, out var scoped)) continue;
|
||||
_sliceWatermarks[key] = watermark;
|
||||
_sent.Add(key);
|
||||
_snapshotRecords.Enqueue(Map(record with { Version = watermark }, scoped, includeInfo: _includeInfo));
|
||||
if (!Enqueue(_snapshotRecords, Map(record with { Version = watermark }, scoped, includeInfo: _includeInfo))) return null;
|
||||
}
|
||||
// A2 review S2: the copied snapshot is charged against the principal's snapshot memory until it is delivered.
|
||||
var bytes = _snapshotRecords.Sum(EstimatedBytes);
|
||||
if (bytes > 0)
|
||||
{
|
||||
if (_reserveSnapshot(bytes) is not { } lease)
|
||||
{
|
||||
MemoryRejections++;
|
||||
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
|
||||
_snapshotRecords.Clear(); _sliceWatermarks.Clear(); _sent.Clear();
|
||||
_state = State.NeedSnapshot; // retried after MinResnapshotInterval
|
||||
return null;
|
||||
}
|
||||
lock (_leaseGate) { _snapshotLease = lease; _leaseSnapshot = Snapshots; ChargedBytes = bytes; }
|
||||
}
|
||||
_snapshotComplete = _hub.IsSnapshotCompleteFor(slices);
|
||||
_retakeWhenReady = !_snapshotComplete;
|
||||
@@ -229,11 +336,11 @@ internal sealed class ConditionItemStream
|
||||
{
|
||||
if (!_sent.Remove(key)) continue;
|
||||
_sliceWatermarks.Remove(key);
|
||||
_pendingDeltas.Enqueue(Map(record, scoped, includeInfo: false));
|
||||
if (!Enqueue(_pendingDeltas, Map(record, scoped, includeInfo: false))) return true;
|
||||
continue;
|
||||
}
|
||||
var first = _sent.Add(key);
|
||||
_pendingDeltas.Enqueue(Map(record, scoped, includeInfo: first && _includeInfo));
|
||||
if (!Enqueue(_pendingDeltas, Map(record, scoped, includeInfo: first && _includeInfo))) return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -245,15 +352,18 @@ internal sealed class ConditionItemStream
|
||||
return new ConditionChunk(false, null, Take(_pendingDeltas), false);
|
||||
}
|
||||
|
||||
/// <summary>At most <see cref="MaxRecordsPerChunk"/> records and <see cref="MaxChunkBytes"/> estimated bytes (at least one).</summary>
|
||||
private static List<DataConditionState> Take(Queue<DataConditionState> queue)
|
||||
/// <summary>
|
||||
/// At most <see cref="MaxRecordsPerChunk"/> records and <see cref="ChunkBytes"/> estimated bytes (at least one; every
|
||||
/// queued record was fitted to <see cref="ChunkBytes"/> on the way in).
|
||||
/// </summary>
|
||||
private List<DataConditionState> Take(Queue<DataConditionState> queue)
|
||||
{
|
||||
var batch = new List<DataConditionState>(Math.Min(MaxRecordsPerChunk, queue.Count));
|
||||
long bytes = 0;
|
||||
while (batch.Count < MaxRecordsPerChunk && queue.TryPeek(out var next))
|
||||
{
|
||||
var size = EstimatedBytes(next);
|
||||
if (batch.Count > 0 && bytes + size > MaxChunkBytes) break;
|
||||
if (batch.Count > 0 && bytes + size > ChunkBytes) break;
|
||||
batch.Add(queue.Dequeue());
|
||||
bytes += size;
|
||||
}
|
||||
@@ -267,14 +377,17 @@ internal sealed class ConditionItemStream
|
||||
+ info.Placements.Sum(p => 256 + p.Subject.Length + p.Address.Identifier.Length + p.Address.NamespaceUri.Length
|
||||
+ p.Address.OriginClusterId.Length) : 0));
|
||||
|
||||
/// <summary>A new catalog: conditions leaving the listing get a removal record; joining ones a small snapshot as deltas.</summary>
|
||||
/// <summary>
|
||||
/// A new listing under an unchanged serving identity (not reachable by a production deploy, which ends the stream):
|
||||
/// 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)
|
||||
if (listing.Count > scope.Limit || scope.Limit != _limit)
|
||||
{
|
||||
// The deploy pushed this root over its limit: report it like a first snapshot would.
|
||||
// Over (or a changed) limit: re-admit through a fresh snapshot, which reports total like a first one would.
|
||||
_state = State.NeedSnapshot;
|
||||
_lastSnapshotAt = long.MinValue;
|
||||
return;
|
||||
@@ -292,34 +405,59 @@ internal sealed class ConditionItemStream
|
||||
_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 slice in _source.SnapshotConditions((realm, id) => added.Contains(new(realm, id)), PerHold))
|
||||
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));
|
||||
if (!Enqueue(_pendingDeltas, Map(record with { Version = slice.Watermark }, scoped, includeInfo: _includeInfo))) return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A synthesised removal (the condition left the listing, not the address space). Its version is the hub
|
||||
/// watermark, which can EQUAL a version already sent for the key, so the consumer rule (§5.5, A2 review N2) is: a
|
||||
/// <c>removed</c> record and a snapshot begin bypass the per-key version gate.
|
||||
/// </summary>
|
||||
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>
|
||||
/// <remarks>
|
||||
/// A2 review S3: a NATIVE condition listed in a UNS export (its id is a RawPath, its placements are UNS) names
|
||||
/// itself by the placement's browse name (the effective name), never by the raw tag's name, and a message that is
|
||||
/// raw-derived (the raw name the node manager seeds it with, the raw leaf, or text naming the RawPath) is replaced
|
||||
/// by that effective name.
|
||||
/// </remarks>
|
||||
internal static DataConditionState Map(ConditionStateRecord record, ScopedCondition scoped, bool includeInfo)
|
||||
{
|
||||
var name = record.ConditionName ?? "";
|
||||
var message = record.Message ?? "";
|
||||
if (IsUnsNative(scoped))
|
||||
{
|
||||
var effective = scoped.Exported.Placements[0].BrowseName;
|
||||
var leaf = record.ConditionId[(record.ConditionId.LastIndexOf('/') + 1)..];
|
||||
if (message.Length > 0 && (message == record.ConditionName || message == leaf
|
||||
|| message.Contains(record.ConditionId, StringComparison.OrdinalIgnoreCase)))
|
||||
message = effective;
|
||||
name = effective;
|
||||
}
|
||||
var info = includeInfo && !record.Removed
|
||||
? new DataConditionInfo(record.ConditionType ?? "", record.ConditionName ?? "",
|
||||
? new DataConditionInfo(record.ConditionType ?? "", name,
|
||||
(DataConditionSourceKind)(int)scoped.Exported.SourceKind,
|
||||
scoped.Exported.Placements.Select(p => p.View).ToArray(), (uint)scoped.Methods)
|
||||
: 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,
|
||||
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);
|
||||
}
|
||||
|
||||
private static bool IsUnsNative(ScopedCondition scoped) => scoped.Ref.Realm == AddressSpaceRealm.Raw
|
||||
&& scoped.Exported.Placements.Count > 0 && scoped.Exported.Placements.All(p => p.View.Realm == DataRealm.Uns);
|
||||
}
|
||||
|
||||
+71
-29
@@ -7,20 +7,19 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
/// <summary>
|
||||
/// A2: root-scoped condition items (plan §5.5). They share the stream, the handle table (one monitored item each) and the
|
||||
/// principal's interest capacity with value items, but have their own non-coalescing bounded queue: the delivery loop
|
||||
/// takes a queued control/ack first, then a condition frame, then a value (priority control > condition > value).
|
||||
/// Production is pull-based (<see cref="ConditionItemStream"/>): an item produces only while the queue has room, so a slow
|
||||
/// consumer back-pressures into the hub, whose eviction resets the item to a fresh snapshot.
|
||||
/// takes a queued control/ack first, then a condition frame, then a value (priority control > condition > value,
|
||||
/// with a fairness cap: after <see cref="ConditionFramesPerValueFrame"/> condition frames in a row a queued v1 frame goes
|
||||
/// next). Production is pull-based (<see cref="ConditionItemStream"/>): an item produces only while the queue has room,
|
||||
/// so a slow consumer back-pressures into the hub, whose eviction resets the item to a fresh snapshot.
|
||||
/// </summary>
|
||||
internal static class ConditionTestAssertions
|
||||
{
|
||||
internal static void ShouldBeTrueForTests(this bool value)
|
||||
{
|
||||
if (!value) throw new InvalidOperationException("Test probe could not be queued.");
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed partial class DataSubscriptionSession
|
||||
{
|
||||
/// <summary>A2 review N1: after this many condition frames in a row, a queued value/heartbeat frame is delivered next.</summary>
|
||||
internal const int ConditionFramesPerValueFrame = 8;
|
||||
|
||||
/// <summary>The frame bytes a condition chunk's records must leave free (the sink's frame charge plus wire fields).</summary>
|
||||
private long ConditionFrameOverhead => 2048L + 4L * (_subscriptionId?.Length ?? 0) + 1024L;
|
||||
|
||||
private sealed class ConditionItem(string clientItemId, DataItemHandle handle, ConditionItemAuthority authority,
|
||||
ConditionItemStream stream, IDisposable reservation) : IDisposable
|
||||
{
|
||||
@@ -34,6 +33,7 @@ internal sealed partial class DataSubscriptionSession
|
||||
{
|
||||
if (Interlocked.Exchange(ref _reservation, null) is { } r)
|
||||
{
|
||||
Stream.Dispose(); // releases the snapshot memory charge
|
||||
r.Dispose();
|
||||
OtOpcUaTelemetry.DataConnConditionItems.Add(-1);
|
||||
}
|
||||
@@ -44,6 +44,8 @@ internal sealed partial class DataSubscriptionSession
|
||||
private readonly Dictionary<string, List<ConditionItem>> _conditionActivations = new(StringComparer.Ordinal);
|
||||
private Channel<PendingDelivery>? _conditionOutboundChannel;
|
||||
private int _conditionCursor;
|
||||
private int _conditionStreak;
|
||||
private Task<bool>? _valuesWait, _conditionsWait;
|
||||
|
||||
/// <summary>The bounded condition queue (created lazily on the first condition item; v1 streams never allocate it).</summary>
|
||||
private Channel<PendingDelivery> ConditionOutbound
|
||||
@@ -76,8 +78,23 @@ internal sealed partial class DataSubscriptionSession
|
||||
if (status != DataItemStatus.Good || authority is null) return new(request.ClientItemId, status, null, null, null);
|
||||
if (authority.Serving != _serving) return new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_conditionItems.Values.Any(x => x.ClientItemId == request.ClientItemId) || _itemsByClient.ContainsKey(request.ClientItemId))
|
||||
return new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, "Duplicate client item id.");
|
||||
// A2 review S2: one condition item per (stream, root) — a second would materialise the same listing again.
|
||||
if (_conditionItems.Values.Any(x => x.Authority.Root.Address == authority.Root.Address && x.Authority.Root.Realm == authority.Root.Realm))
|
||||
return new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, "A condition item for this root is already open on this stream.");
|
||||
// …and at most MaxConditionItems per stream (SubscriptionSessionLimits.DefaultMaxConditionItems).
|
||||
if (_conditionItems.Count >= _limits.MaxConditionItems)
|
||||
return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null,
|
||||
$"At most {_limits.MaxConditionItems} condition items per stream.");
|
||||
}
|
||||
// A2 review S5: a chunk fits both the session's pending bytes and the message limit, after the frame's own overhead.
|
||||
var chunkBytes = Math.Min(ConditionItemStream.MaxChunkBytes,
|
||||
Math.Min(_limits.MaxPendingBytes, services.SubscriptionLimits.MaxMessageBytes) - ConditionFrameOverhead);
|
||||
if (chunkBytes < ConditionItemStream.MinRecordBytes)
|
||||
return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null,
|
||||
"The stream's message limits are too small for condition records.");
|
||||
var fixedBytes = checked(4096L + 2L * (request.ClientItemId.Length + authority.Root.Subject.Length
|
||||
+ authority.Root.Address.Identifier.Length + authority.Root.Address.NamespaceUri.Length));
|
||||
var itemLimit = services.SubscriptionItemLimit(_context);
|
||||
@@ -88,8 +105,10 @@ internal sealed partial class DataSubscriptionSession
|
||||
catch (Exception ex) when (ex is InvalidOperationException or OverflowException)
|
||||
{ reservation!.Dispose(); return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null); }
|
||||
_ = ConditionOutbound; // exists before the ack is queued, so the delivery loop waits on it from then on
|
||||
var stream = new ConditionItemStream(hub, source, authority.Scope, authority.Limit,
|
||||
request.ConditionScope!.IncludeInfo, services.Clock);
|
||||
var principal = _context.PrincipalId;
|
||||
var snapshots = _capacity.Snapshots;
|
||||
var stream = new ConditionItemStream(hub, source, authority.Scope, request.ConditionScope!.IncludeInfo, services.Clock,
|
||||
reserveSnapshot: bytes => snapshots.TryAcquire(principal, bytes, out var lease) ? lease : null, chunkBytes: chunkBytes);
|
||||
var item = new ConditionItem(request.ClientItemId, handle, authority, stream, reservation!);
|
||||
OtOpcUaTelemetry.DataConnConditionItems.Add(1);
|
||||
lock (_gate)
|
||||
@@ -146,6 +165,7 @@ internal sealed partial class DataSubscriptionSession
|
||||
if (!item.Authority.CanPublish()) { Stop(); break; }
|
||||
var chunk = item.Stream.Next();
|
||||
if (item.Stream.Overflowed) { CloseWithReset("Condition stream overflow; retry later."); break; }
|
||||
if (item.Stream.Oversized) { CloseWithReset("A condition record exceeds the stream's message limits."); break; }
|
||||
if (item.Stream.IsRevoked) { Stop(); break; }
|
||||
if (chunk is null) { idle++; continue; }
|
||||
idle = 0;
|
||||
@@ -187,19 +207,26 @@ internal sealed partial class DataSubscriptionSession
|
||||
if (_outbound.Reader.TryRead(out var control)) { Dequeued(control); return control; }
|
||||
continue;
|
||||
}
|
||||
// A2 review N1: strict condition priority would starve values and heartbeats during a long snapshot.
|
||||
if (_conditionStreak >= ConditionFramesPerValueFrame && _outbound.Reader.TryRead(out var fair))
|
||||
{ _conditionStreak = 0; Dequeued(fair); return fair; }
|
||||
if (_conditionOutboundChannel is { } conditions && conditions.Reader.TryRead(out var condition))
|
||||
{
|
||||
_conditionStreak++;
|
||||
QueueTick();
|
||||
return condition;
|
||||
}
|
||||
if (_outbound.Reader.TryRead(out var value)) { Dequeued(value); return value; }
|
||||
if (_outbound.Reader.TryRead(out var value)) { _conditionStreak = 0; Dequeued(value); return value; }
|
||||
if (_conditionOutboundChannel is null)
|
||||
{
|
||||
if (!await _outbound.Reader.WaitToReadAsync(token).ConfigureAwait(false)) return null;
|
||||
continue;
|
||||
}
|
||||
var values = _outbound.Reader.WaitToReadAsync(token).AsTask();
|
||||
var conditionsReady = _conditionOutboundChannel.Reader.WaitToReadAsync(token).AsTask();
|
||||
// A2 review N5: a wait that lost the race stays pending on its channel; reuse it rather than registering a new
|
||||
// waiter on every pass (values flowing while conditions idle would otherwise pile up condition waiters).
|
||||
var values = _valuesWait is { IsCompleted: false } pendingValues ? pendingValues : _valuesWait = StartWait(_outbound.Reader, token);
|
||||
var conditionsReady = _conditionsWait is { IsCompleted: false } pendingConditions
|
||||
? pendingConditions : _conditionsWait = StartWait(_conditionOutboundChannel.Reader, token);
|
||||
await Task.WhenAny(values, conditionsReady).ConfigureAwait(false);
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (values.IsCompletedSuccessfully && !values.Result && (!conditionsReady.IsCompletedSuccessfully || !conditionsReady.Result)
|
||||
@@ -208,26 +235,41 @@ internal sealed partial class DataSubscriptionSession
|
||||
}
|
||||
}
|
||||
|
||||
private Task<bool> StartWait(ChannelReader<PendingDelivery> reader, CancellationToken token)
|
||||
{
|
||||
Interlocked.Increment(ref _conditionWaitsStarted);
|
||||
return reader.WaitToReadAsync(token).AsTask();
|
||||
}
|
||||
|
||||
private int _conditionWaitsStarted;
|
||||
|
||||
/// <summary>Test seam (N5): how many channel waits the delivery loop has registered.</summary>
|
||||
internal int ConditionWaitsStartedForTests => Volatile.Read(ref _conditionWaitsStarted);
|
||||
|
||||
/// <summary>Test seam: the stream has processed its Open.</summary>
|
||||
internal bool IsOpenForTests => Volatile.Read(ref _handles) is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Test seam (stream priority): queues an empty value frame and a heartbeat control on the v1 queue (control first
|
||||
/// when <paramref name="controlFirst"/>), then a condition frame.
|
||||
/// </summary>
|
||||
internal async Task EnqueuePriorityProbesForTests(DataItemHandle conditionHandle, bool controlFirst)
|
||||
// Test seams (stream priority, fairness, waiters). Internal, reached only through InternalsVisibleTo: they queue empty
|
||||
// frames directly, bypassing items, so the delivery order can be asserted without a producer.
|
||||
|
||||
/// <summary>Test seam: queues an empty value frame on the v1 queue.</summary>
|
||||
internal Task EnqueueValueProbeForTests() =>
|
||||
EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, false, []),
|
||||
() => true, isValue: true));
|
||||
|
||||
/// <summary>Test seam: queues a heartbeat control on the v1 queue.</summary>
|
||||
internal Task EnqueueHeartbeatProbeForTests()
|
||||
{
|
||||
var serving = _serving!;
|
||||
PendingDelivery Value() => new(sequence => new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, false, []),
|
||||
() => true, isValue: true);
|
||||
PendingDelivery Control() => new(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence,
|
||||
DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), () => true);
|
||||
await EnqueueAsync(controlFirst ? Control() : Value()).ConfigureAwait(false);
|
||||
await EnqueueAsync(controlFirst ? Value() : Control()).ConfigureAwait(false);
|
||||
ConditionOutbound.Writer.TryWrite(new PendingDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch,
|
||||
sequence, conditionHandle, false, null, [], false), () => true)).ShouldBeTrueForTests();
|
||||
return EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence,
|
||||
DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), () => true));
|
||||
}
|
||||
|
||||
/// <summary>Test seam: queues an empty condition frame for <paramref name="handle"/>; false when the queue is full.</summary>
|
||||
internal bool TryEnqueueConditionProbeForTests(DataItemHandle handle) =>
|
||||
ConditionOutbound.Writer.TryWrite(new PendingDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch,
|
||||
sequence, handle, false, null, [], false), () => true));
|
||||
|
||||
/// <summary>Called from the worker's teardown: completes and drains the condition queue, releases condition items.</summary>
|
||||
private void TearDownConditions()
|
||||
{
|
||||
|
||||
+7
-5
@@ -6,7 +6,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>An admitted root-scoped condition item's authority (plan §5.5, service-principal model).</summary>
|
||||
/// <param name="Root">The export root the item listens under (canonical catalog view).</param>
|
||||
/// <param name="Limit">The item's <c>MaxConditions</c> (min over the AlarmSubscribe exports that contain the root).</param>
|
||||
/// <param name="Limit">The item's <c>MaxConditions</c> at admission (min over the AlarmSubscribe exports that contain the
|
||||
/// root); the stream re-reads it with every listing (<see cref="ConditionItemScope.Limit"/>, A2 review S4).</param>
|
||||
/// <param name="Serving">The serving identity it was admitted under.</param>
|
||||
/// <param name="Scope">The current listing (null once the grant is gone), recomputed only when the catalog changes.</param>
|
||||
/// <param name="CanPublish">Whether a frame of this item may still be delivered.</param>
|
||||
@@ -66,16 +67,17 @@ public sealed partial class LocalDataServices
|
||||
ConditionItemScope Scope()
|
||||
{
|
||||
var current = _catalog();
|
||||
if (current is null) return cached ??= new ConditionItemScope(new object(), null);
|
||||
if (current is null) return cached ??= new ConditionItemScope(new object(), null, limit);
|
||||
if (ReferenceEquals(current, listedFrom) && cached is not null) return cached;
|
||||
listedFrom = current;
|
||||
var allowed = Ready(current) && current.Serving == serving && current.TryResolve(root, out _)
|
||||
&& current.ConditionLimitFor(context.PrincipalId, root) is not null && _policy.IsCallerUsable(Caller(context));
|
||||
// A2 review S4: the limit is re-read from the catalog the listing comes from, never frozen at admission.
|
||||
var currentLimit = current.TryResolve(root, out _) ? current.ConditionLimitFor(context.PrincipalId, root) : null;
|
||||
var allowed = Ready(current) && current.Serving == serving && currentLimit is not null && _policy.IsCallerUsable(Caller(context));
|
||||
cached = new ConditionItemScope(current, allowed
|
||||
? current.ListConditionScope(context.PrincipalId, root, DataOperations.AlarmSubscribe, ConditionKeysSource(),
|
||||
placement => _policy.AuthorizeLocal(Caller(context), OpcUaOperation.CreateMonitoredItems, placement.Scope),
|
||||
methods: ConditionMethodsServable)
|
||||
: null);
|
||||
: null, currentLimit ?? limit);
|
||||
return cached;
|
||||
}
|
||||
authority = new ConditionItemAuthority(root, limit, serving, Scope, () =>
|
||||
|
||||
@@ -16,12 +16,17 @@ internal interface ISubscriptionDemandSource
|
||||
internal sealed record SubscriptionDemandResult(DataItemStatus Status, DataSubscriptionSettings? RevisedSettings,
|
||||
long Boundary, IDisposable? Lease);
|
||||
|
||||
/// <param name="MaxConditionItems">A2 review S2: the most root-scoped condition items one stream may hold.</param>
|
||||
internal sealed record SubscriptionSessionLimits(int MaxCommands, int MaxPendingFrames, long MaxPendingBytes,
|
||||
TimeSpan MaxSessionLifetime, TimeSpan? PreOpenTimeout = null)
|
||||
TimeSpan MaxSessionLifetime, TimeSpan? PreOpenTimeout = null,
|
||||
int MaxConditionItems = SubscriptionSessionLimits.DefaultMaxConditionItems)
|
||||
{
|
||||
/// <summary>The default per-stream condition-item cap (A3 opens one item per condition-bearing mapping).</summary>
|
||||
internal const int DefaultMaxConditionItems = 32;
|
||||
|
||||
internal void Validate()
|
||||
{
|
||||
if (MaxCommands <= 0 || MaxPendingFrames <= 0 || MaxPendingBytes <= 0 || MaxSessionLifetime <= TimeSpan.Zero ||
|
||||
if (MaxCommands <= 0 || MaxPendingFrames <= 0 || MaxPendingBytes <= 0 || MaxSessionLifetime <= TimeSpan.Zero || MaxConditionItems <= 0 ||
|
||||
PreOpenTimeout is { } timeout && (timeout <= TimeSpan.Zero || timeout > TimeSpan.FromMilliseconds(uint.MaxValue - 1)))
|
||||
throw new ArgumentOutOfRangeException(nameof(MaxCommands));
|
||||
}
|
||||
|
||||
+307
-28
@@ -10,6 +10,7 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
@@ -136,19 +137,165 @@ public sealed class GrpcDataConditionStreamTests
|
||||
f.StreamOf(stream)!.Snapshots.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>A2 review S1: an origin deploy begins a catalog attempt (serving identity changes) — the stream ends.</summary>
|
||||
[Fact]
|
||||
public async Task A_real_catalog_republish_ends_the_condition_stream()
|
||||
{
|
||||
using var f = new CoordinatorConditionFixture();
|
||||
await using var stream = await f.Conditions.OpenAsync();
|
||||
(await stream.ReadSnapshotAsync()).Records.Count.ShouldBe(1);
|
||||
f.Republish(); // LocalCatalogCoordinator.BeginAttempt + InstallAuthority + Stage + Complete, as DriverHostActor does
|
||||
var after = await stream.DrainAsync(f.Conditions);
|
||||
after.OfType<DataSubscriptionConditions>().ShouldBeEmpty("no delta record crosses a deploy: the consumer re-snapshots");
|
||||
stream.Ended.ShouldBeTrue("a deploy ends the condition stream; the consumer reconnects and takes a complete snapshot");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_second_condition_item_on_the_same_root_is_refused_and_the_per_stream_cap_holds()
|
||||
{
|
||||
using var f = new ConditionFixture(conditions: 1, maxConditionItems: 1);
|
||||
await using var stream = await f.OpenAsync(requestedItems:
|
||||
[ConditionFixture.ConditionItem("a", f.Root), ConditionFixture.ConditionItem("b", f.Root), ConditionFixture.ConditionItem("c", f.SubRoot)]);
|
||||
var acks = (await stream.ReadAckAsync()).Items;
|
||||
acks.Single(a => a.ClientItemId == "a").Status.ShouldBe(DataItemStatus.Good);
|
||||
var duplicate = acks.Single(a => a.ClientItemId == "b");
|
||||
duplicate.Status.ShouldBe(DataItemStatus.InvalidArgument);
|
||||
duplicate.Diagnostic.ShouldNotBeNull().ShouldContain("already open");
|
||||
var capped = acks.Single(a => a.ClientItemId == "c");
|
||||
capped.Status.ShouldBe(DataItemStatus.LimitExceeded, "a different root, but the stream already holds its one condition item");
|
||||
stream.Session.ConditionStreamsForTests.Count.ShouldBe(1);
|
||||
|
||||
using var roomy = new ConditionFixture(conditions: 1);
|
||||
await using var two = await roomy.OpenAsync(requestedItems:
|
||||
[ConditionFixture.ConditionItem("a", roomy.Root), ConditionFixture.ConditionItem("c", roomy.SubRoot)]);
|
||||
(await two.ReadAckAsync()).Items.ShouldAllBe(a => a.Status == DataItemStatus.Good); // positive control
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_snapshot_is_charged_against_the_principals_memory_budget()
|
||||
{
|
||||
// 50 records ≈ 50 × 2.3 KB, above a 20 KB principal snapshot budget: nothing is materialised on the stream.
|
||||
using var tight = new ConditionFixture(conditions: 50, principalSnapshotBytes: 20_000);
|
||||
await using var refused = await tight.OpenAsync();
|
||||
await refused.ReadAckAsync();
|
||||
(await refused.TryReadConditionsAsync(tight, TimeSpan.FromSeconds(2))).ShouldBeNull();
|
||||
tight.StreamOf(refused)!.MemoryRejections.ShouldBeGreaterThan(0);
|
||||
refused.Ended.ShouldBeFalse("refused memory is retried, not a stream fault");
|
||||
|
||||
// Within budget: the charge is held while the snapshot is undelivered and released once it is delivered.
|
||||
using var f = new ConditionFixture(conditions: 50, principalSnapshotBytes: 1_000_000);
|
||||
await using var stream = await f.OpenAsync();
|
||||
var snapshot = await stream.ReadSnapshotAsync();
|
||||
snapshot.Records.Count.ShouldBe(50);
|
||||
await Task.Delay(100, Ct);
|
||||
f.StreamOf(stream)!.ChargedBytes.ShouldBe(0, "the last chunk was delivered");
|
||||
f.Capacity.Snapshots.TryAcquire("peer", 1_000_000, out var whole).ShouldBeTrue("the principal's budget is whole again");
|
||||
whole!.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_item_limit_is_re_read_with_the_listing_not_frozen_at_admission()
|
||||
{
|
||||
using var f = new ConditionFixture(conditions: 3, maxConditions: 1000);
|
||||
await using var stream = await f.OpenAsync();
|
||||
(await stream.ReadSnapshotAsync()).Records.Count.ShouldBe(3);
|
||||
f.SetMaxConditions(2); // the export's limit drops below the listing
|
||||
f.Clock.Advance(TimeSpan.FromSeconds(2)); // past the re-snapshot interval
|
||||
var begin = await stream.ReadConditionsAsync(f);
|
||||
begin.IsSnapshot.ShouldBeTrue();
|
||||
begin.Total.ShouldBe(3);
|
||||
begin.Items.ShouldBeEmpty("over the new limit: total only, no record");
|
||||
f.StreamOf(stream)!.IsOverCapacity.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Chunks_fit_small_pending_and_message_limits_and_an_oversized_message_is_truncated()
|
||||
{
|
||||
// MaxMessageBytes 20,000 ⇒ chunk budget 20,000 − overhead; a 50,000-char message alone would be ~200 KB.
|
||||
using var f = new ConditionFixture(conditions: 40, maxPendingBytes: 40_000, maxMessageBytes: 20_000);
|
||||
f.Source.MessageOf = id => id.EndsWith("Alarm7", StringComparison.Ordinal) ? new string('x', 50_000) : "ok";
|
||||
f.Source.Raise(7, active: false); // re-record condition 7 with its long message
|
||||
await using var stream = await f.OpenAsync();
|
||||
var snapshot = await stream.ReadSnapshotAsync();
|
||||
snapshot.Complete.ShouldBeTrue();
|
||||
snapshot.Records.Count.ShouldBe(40);
|
||||
var budget = f.StreamOf(stream)!.ChunkBytes;
|
||||
budget.ShouldBeLessThan(20_000);
|
||||
snapshot.Chunks.ShouldAllBe(c => c.Items.Sum(ConditionItemStream.EstimatedBytes) <= budget);
|
||||
snapshot.Chunks.Count.ShouldBeGreaterThan(1);
|
||||
var truncated = snapshot.Records.Single(r => r.ConditionKey == f.KeyOf(7));
|
||||
truncated.Message.Length.ShouldBeLessThan(50_000);
|
||||
truncated.Message.ShouldAllBe(c => c == 'x');
|
||||
stream.Ended.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_record_that_cannot_fit_even_without_free_text_is_reported_not_queued()
|
||||
{
|
||||
var record = new DataConditionState("key", 1, false, true, null, true, false, true, true, 0, 500, new string('m', 10_000), 0, null, 0,
|
||||
DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1), "comment", "user");
|
||||
var fitted = ConditionItemStream.Fit(record, 3_000).ShouldNotBeNull();
|
||||
ConditionItemStream.EstimatedBytes(fitted).ShouldBeLessThanOrEqualTo(3_000);
|
||||
fitted.ConditionKey.ShouldBe("key");
|
||||
ConditionItemStream.Fit(record, 1_000).ShouldBeNull("2,048 bytes of fixed estimate cannot fit 1,000");
|
||||
var pair = record with { Message = "ab" + "\uD83D\uDE00", Comment = null, ClientUserId = null };
|
||||
var cut = ConditionItemStream.Fit(pair, ConditionItemStream.EstimatedBytes(pair with { Message = "" }) + 12).ShouldNotBeNull();
|
||||
cut.Message.ShouldBe("ab", "a surrogate pair is never split");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Condition_frames_do_not_starve_queued_values()
|
||||
{
|
||||
using var f = new ConditionFixture(conditions: 1);
|
||||
await using var stream = await f.OpenAsync(items: false);
|
||||
await stream.ReadAckAsync();
|
||||
var handle = new DataItemHandle("s", 1, 99, 1);
|
||||
for (var i = 0; i < 12; i++) stream.Session.TryEnqueueConditionProbeForTests(handle).ShouldBeTrue();
|
||||
await stream.Session.EnqueueValueProbeForTests();
|
||||
var order = new List<DataSubscriptionFrame>();
|
||||
for (var i = 0; i < 13; i++) order.Add((await stream.NextAsync()).ShouldNotBeNull());
|
||||
var valueAt = order.FindIndex(x => x is DataSubscriptionValues);
|
||||
valueAt.ShouldBe(DataSubscriptionSession.ConditionFramesPerValueFrame, "one value after every N condition frames");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_delivery_loop_does_not_pile_up_channel_waiters()
|
||||
{
|
||||
using var f = new ConditionFixture(conditions: 1);
|
||||
await using var stream = await f.OpenAsync(items: false);
|
||||
await stream.ReadAckAsync();
|
||||
_ = stream.Session.TryEnqueueConditionProbeForTests(new DataItemHandle("s", 1, 99, 1)); // creates the condition queue
|
||||
(await stream.NextAsync()).ShouldBeOfType<DataSubscriptionConditions>();
|
||||
var before = stream.Session.ConditionWaitsStartedForTests;
|
||||
for (var i = 0; i < 40; i++)
|
||||
{
|
||||
var next = stream.NextAsync(TimeSpan.FromSeconds(5));
|
||||
await Task.Delay(5, Ct); // the loop is waiting on both queues
|
||||
await stream.Session.EnqueueValueProbeForTests();
|
||||
(await next).ShouldNotBeNull();
|
||||
}
|
||||
// Each value wakes the loop once; the idle condition wait must be reused, not re-registered every pass.
|
||||
(stream.Session.ConditionWaitsStartedForTests - before).ShouldBeLessThan(50);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delivery_priority_is_control_then_condition_then_value()
|
||||
{
|
||||
using var f = new ConditionFixture(conditions: 1);
|
||||
await using var stream = await f.OpenAsync(items: false);
|
||||
await stream.ReadAckAsync();
|
||||
var handle = new DataItemHandle("s", 1, 99, 1);
|
||||
// A control at the head goes first; the condition overtakes the queued value.
|
||||
await stream.Session.EnqueuePriorityProbesForTests(new DataItemHandle("s", 1, 99, 1), controlFirst: true);
|
||||
await stream.Session.EnqueueHeartbeatProbeForTests();
|
||||
await stream.Session.EnqueueValueProbeForTests();
|
||||
stream.Session.TryEnqueueConditionProbeForTests(handle).ShouldBeTrue();
|
||||
(await stream.NextAsync()).ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.Heartbeat);
|
||||
(await stream.NextAsync()).ShouldBeOfType<DataSubscriptionConditions>();
|
||||
(await stream.NextAsync()).ShouldBeOfType<DataSubscriptionValues>();
|
||||
// Behind a queued value, a v1 control keeps its v1 order; the condition still overtakes both.
|
||||
await stream.Session.EnqueuePriorityProbesForTests(new DataItemHandle("s", 1, 99, 1), controlFirst: false);
|
||||
await stream.Session.EnqueueValueProbeForTests();
|
||||
await stream.Session.EnqueueHeartbeatProbeForTests();
|
||||
stream.Session.TryEnqueueConditionProbeForTests(handle).ShouldBeTrue();
|
||||
(await stream.NextAsync()).ShouldBeOfType<DataSubscriptionConditions>();
|
||||
(await stream.NextAsync()).ShouldBeOfType<DataSubscriptionValues>();
|
||||
(await stream.NextAsync()).ShouldBeOfType<DataSubscriptionControl>();
|
||||
@@ -171,13 +318,18 @@ public sealed class GrpcDataConditionStreamTests
|
||||
f.StreamOf(stream, allowMissing: true).ShouldBeNull();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stream's listing-change path (A2 review S1: NOT a production deploy — a deploy ends the stream, see
|
||||
/// <see cref="A_real_catalog_republish_ends_the_condition_stream"/>). A catalog object swapped under an unchanged
|
||||
/// serving identity sends leaving conditions as removal records and joining ones as delta records.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_origin_deploy_adding_and_removing_conditions_arrives_as_delta_records()
|
||||
public async Task A_listing_change_under_an_unchanged_serving_identity_arrives_as_delta_records()
|
||||
{
|
||||
using var f = new ConditionFixture(conditions: 3);
|
||||
await using var stream = await f.OpenAsync();
|
||||
(await stream.ReadSnapshotAsync()).Records.Count.ShouldBe(3);
|
||||
f.Deploy(add: 3, remove: 0); // condition 3 appears, condition 0 leaves the address space and the catalog
|
||||
f.SwapListingWithoutAttempt(add: 3, remove: 0); // condition 3 joins, condition 0 leaves
|
||||
var deltas = await stream.ReadDeltasUntilAsync(f, r => r.ConditionKey == f.KeyOf(3) || r.Removed, minimum: 2);
|
||||
deltas.ShouldAllBe(r => r.Version > 0);
|
||||
var added = deltas.Single(r => r.ConditionKey == f.KeyOf(3));
|
||||
@@ -202,6 +354,33 @@ public sealed class GrpcDataConditionStreamTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A2 review S3: a UNS-only export whose references carry a display-name override — the raw tag's name (the leaf
|
||||
/// of its RawPath) appears nowhere in the record: <c>ConditionName</c> is the effective name, and the node
|
||||
/// manager's raw-seeded message is replaced by it (snapshot and delta).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_uns_listing_with_a_display_name_override_carries_no_raw_leaf_name()
|
||||
{
|
||||
using var f = new ConditionFixture(conditions: 2, unsPrincipal: true, unsDisplayName: "HeadTemp");
|
||||
await using var stream = await f.OpenAsync();
|
||||
var snapshot = await stream.ReadSnapshotAsync();
|
||||
f.Source.Raise(0, active: true);
|
||||
var delta = (await stream.ReadConditionsAsync(f)).Items.ShouldHaveSingleItem();
|
||||
foreach (var record in snapshot.Records.Append(delta))
|
||||
{
|
||||
var wire = DataConditionProtoMapper.EncodeState(record).ToString();
|
||||
wire.ShouldNotContain("Alarm", Case.Sensitive, "the raw leaf name (Alarm0/Alarm1) must not reach a UNS peer");
|
||||
wire.ShouldNotContain("Plant/");
|
||||
record.Message.ShouldStartWith("HeadTemp");
|
||||
}
|
||||
snapshot.Records.Select(r => r.Info!.ConditionName).ShouldBe(["HeadTemp0", "HeadTemp1"], ignoreOrder: true);
|
||||
// A driver's own message (not raw-derived) passes through untouched.
|
||||
f.Source.MessageOf = _ => "Temperature high";
|
||||
f.Source.Raise(1, active: true);
|
||||
(await stream.ReadConditionsAsync(f)).Items.ShouldHaveSingleItem().Message.ShouldBe("Temperature high");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_non_primary_origin_refuses_condition_items_and_a_missing_grant_is_denied()
|
||||
{
|
||||
@@ -269,8 +448,11 @@ internal sealed class FakeConditionSource(ConditionStateHub hub) : IOriginCondit
|
||||
internal void Remove(int i) { lock (_lock) { _active.Remove(IdOf(i)); hub.Append(Record(IdOf(i), false, true)); } }
|
||||
internal void Raise(int i, bool active) { lock (_lock) { _active[IdOf(i)] = active; hub.Append(Record(IdOf(i), active, false)); } }
|
||||
internal bool IsActive(int i) { lock (_lock) return _active[IdOf(i)]; }
|
||||
private static ConditionStateRecord Record(string id, bool active, bool removed, long version = 0) => new(AddressSpaceRealm.Raw, id, true,
|
||||
version, removed, !removed, active, !active, true, true, AlarmShelvingKind.Unshelved, 500, "msg", 0, null, DateTime.UtcNow, active,
|
||||
/// <summary>The message a record carries (default: the raw tag's name, which is what the node manager seeds it with).</summary>
|
||||
internal Func<string, string>? MessageOf { get; set; }
|
||||
private ConditionStateRecord Record(string id, bool active, bool removed, long version = 0) => new(AddressSpaceRealm.Raw, id, true,
|
||||
version, removed, !removed, active, !active, true, true, AlarmShelvingKind.Unshelved, 500,
|
||||
(MessageOf ?? (x => x[(x.LastIndexOf('/') + 1)..]))(id), 0, null, DateTime.UtcNow, active,
|
||||
new ConditionActivationMarker("inc", 1), ConditionType: "nsu=http://opcfoundation.org/UA/;i=2915",
|
||||
ConditionName: id[(id.LastIndexOf('/') + 1)..]);
|
||||
|
||||
@@ -332,9 +514,12 @@ internal sealed class ConditionFixture : IDisposable
|
||||
internal readonly DataTarget Target;
|
||||
internal readonly DataView Root = new(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant"), DataRealm.Raw, null, 0, "Plant");
|
||||
internal readonly DataView UnsRoot = new(new("cluster", "https://zb.com/otopcua/uns", "string", "Area"), DataRealm.Uns, null, 0, "Area");
|
||||
/// <summary>A second raw root inside the same export (a different root for the per-stream checks).</summary>
|
||||
internal readonly DataView SubRoot = new(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant/Driver"), DataRealm.Raw, null, 0, "Plant/Driver");
|
||||
internal readonly ConditionKeys Keys;
|
||||
private readonly bool _uns;
|
||||
private readonly int _maxConditions;
|
||||
private int _maxConditions;
|
||||
private readonly string? _unsName;
|
||||
private readonly bool _grant;
|
||||
private readonly HashSet<int> _listed = [];
|
||||
private readonly DataOperations _extra;
|
||||
@@ -347,9 +532,12 @@ internal sealed class ConditionFixture : IDisposable
|
||||
internal ConditionFixture(int conditions, int maxConditions = 1000, bool unsPrincipal = false, string role = "Primary",
|
||||
bool grantAlarmSubscribe = true, bool secret = true, int partitionCapacity = ConditionStateHub.DefaultPartitionCapacity,
|
||||
DataOperations extraOperations = DataOperations.None, IReadOnlyList<NodeAcl>? acls = null,
|
||||
Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>? scopePaths = null, string? driverType = null, bool galaxyAck = false)
|
||||
Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>? scopePaths = null, string? driverType = null, bool galaxyAck = false,
|
||||
long maxPendingBytes = 200_000, int maxMessageBytes = 1_000_000, long? principalSnapshotBytes = null,
|
||||
int maxConditionItems = SubscriptionSessionLimits.DefaultMaxConditionItems, string? unsDisplayName = null,
|
||||
byte[]? artifact = null)
|
||||
{
|
||||
_uns = unsPrincipal; _maxConditions = maxConditions; _grant = grantAlarmSubscribe;
|
||||
_uns = unsPrincipal; _maxConditions = maxConditions; _grant = grantAlarmSubscribe; _unsName = unsDisplayName;
|
||||
_extra = extraOperations; _driverType = driverType; _galaxyAck = galaxyAck;
|
||||
Serving = new ServingIdentity("node-a", "serving-1", role, 1, 1);
|
||||
ValueHub = HubTest.Create(clock: Clock, bytes: 1_000_000);
|
||||
@@ -358,22 +546,36 @@ internal sealed class ConditionFixture : IDisposable
|
||||
Source = new FakeConditionSource(Hub);
|
||||
Keys = secret ? ConditionKeys.FromSecret(Secret) : ConditionKeys.Unavailable;
|
||||
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
|
||||
Authority.Apply("cluster", "first", [key],
|
||||
if (artifact is not null)
|
||||
{
|
||||
// The production path: the served catalog comes from a real LocalCatalogCoordinator fed a deployment artifact.
|
||||
Coordinator = new LocalCatalogCoordinator(Activation, Authority, () => Serving with { CatalogEpoch = 0, AuthorityEpoch = 0 });
|
||||
Publish(artifact);
|
||||
}
|
||||
else Authority.Apply("cluster", "first", [key],
|
||||
acls ?? [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.Cluster,
|
||||
PermissionFlags = NodePermissions.ReadOnly }], scopePaths ?? new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
var epoch = Activation.Begin("first");
|
||||
Activation.AuthorityInstalled(epoch, Authority.Current.GenerationId);
|
||||
Activation.Complete(epoch, true);
|
||||
if (artifact is null)
|
||||
{
|
||||
var epoch = Activation.Begin("first");
|
||||
Activation.AuthorityInstalled(epoch, Authority.Current.GenerationId);
|
||||
Activation.Complete(epoch, true);
|
||||
}
|
||||
Context = new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), Clock.GetUtcNow().AddMinutes(10), Authority.Current.GenerationId);
|
||||
Target = new(DataTargetMode.Node, "cluster", "node-a");
|
||||
for (var i = 0; i < conditions; i++) { _listed.Add(i); Source.Add(i); }
|
||||
_catalog = Compile(_grant);
|
||||
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
||||
var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => _catalog.IsActive, limits);
|
||||
var capacity = new SubscriptionTransportCapacity(4, 4, 10_000_000, clock: Clock);
|
||||
var sessionLimits = new SubscriptionSessionLimits(64, 16, 200_000, TimeSpan.FromMinutes(5));
|
||||
var limits = new DataLimits(100, 100, maxMessageBytes, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
||||
var capabilities = Coordinator is { } coordinator
|
||||
? new DataCapabilitiesProvider("cluster", () => coordinator.Serving, () => coordinator.Current?.IsActive == true, limits)
|
||||
: new DataCapabilitiesProvider("cluster", () => Serving, () => _catalog.IsActive, limits);
|
||||
var capacity = new SubscriptionTransportCapacity(4, 4, 10_000_000, clock: Clock, maxSnapshotBytes: 100_000_000,
|
||||
maxPrincipalSnapshotBytes: principalSnapshotBytes,
|
||||
maxSnapshotLifetime: TimeSpan.FromHours(1));
|
||||
Capacity = capacity;
|
||||
var sessionLimits = new SubscriptionSessionLimits(64, 16, maxPendingBytes, TimeSpan.FromMinutes(5), MaxConditionItems: maxConditionItems);
|
||||
LocalDataServices? services = null;
|
||||
services = new LocalDataServices(() => _catalog, ValueHub, new DataOperationPolicy(Authority,
|
||||
services = new LocalDataServices(() => Coordinator is { } c ? c.Current : _catalog, ValueHub, new DataOperationPolicy(Authority,
|
||||
new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock,
|
||||
targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, new DeferredSubscriptionDemand(),
|
||||
sessionLimits, capacity))
|
||||
@@ -381,6 +583,22 @@ internal sealed class ConditionFixture : IDisposable
|
||||
Services = services;
|
||||
}
|
||||
|
||||
internal SubscriptionTransportCapacity Capacity { get; }
|
||||
|
||||
/// <summary>The real catalog coordinator (artifact mode only).</summary>
|
||||
internal LocalCatalogCoordinator? Coordinator { get; }
|
||||
|
||||
/// <summary>A deploy exactly as <c>DriverHostActor</c> drives it: BeginAttempt, InstallAuthority, Stage, Complete.</summary>
|
||||
internal void Publish(byte[] artifact)
|
||||
{
|
||||
var coordinator = Coordinator ?? throw new InvalidOperationException("Not an artifact fixture.");
|
||||
var attempt = coordinator.BeginAttempt(Convert.ToHexStringLower(SHA256.HashData(artifact)));
|
||||
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(artifact, "node-a")).ShouldBeTrue();
|
||||
using (var parsed = DeploymentArtifact.Open(artifact))
|
||||
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!).ShouldBeTrue();
|
||||
coordinator.Complete(attempt, true).ShouldBeTrue();
|
||||
}
|
||||
|
||||
internal string KeyOf(int i) => Keys.Derive("cluster", AddressSpaceRealm.Raw, FakeConditionSource.IdOf(i));
|
||||
|
||||
private LocalExportCatalog Compile(bool grant)
|
||||
@@ -391,6 +609,8 @@ internal sealed class ConditionFixture : IDisposable
|
||||
{
|
||||
new("RawFolder", "folder", folder, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant"] }, null, null),
|
||||
new("UnsArea", "area", unsFolder, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area"] }, null, null),
|
||||
new("RawDriver", "driver", folder with { View = SubRoot, BrowseName = "Driver" },
|
||||
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver"] }, Root, null),
|
||||
};
|
||||
var placements = new List<LocalConditionPlacement>();
|
||||
foreach (var i in _listed)
|
||||
@@ -400,9 +620,11 @@ internal sealed class ConditionFixture : IDisposable
|
||||
placements.Add(new(new(new("cluster", "https://zb.com/otopcua/raw", "string", id), DataRealm.Raw, null, 0, id), Root,
|
||||
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = id.Split('/') }, "Alarm" + i,
|
||||
ConditionSourceKind.Native, condition, "RawTag", "tag-" + i, _driverType));
|
||||
var uns = $"Area/Line/Equipment/Alarm{i}";
|
||||
// A UNS reference's NodeId and browse name are its EFFECTIVE name (a display-name override when one is set).
|
||||
var effective = (_unsName ?? "Alarm") + i;
|
||||
var uns = $"Area/Line/Equipment/{effective}";
|
||||
placements.Add(new(new(new("cluster", "https://zb.com/otopcua/uns", "string", uns), DataRealm.Uns, null, 0, uns), UnsRoot,
|
||||
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = uns.Split('/') }, "Alarm" + i,
|
||||
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = uns.Split('/') }, effective,
|
||||
ConditionSourceKind.Native, condition, "UnsTagReference", "ref-" + i, _driverType));
|
||||
}
|
||||
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe
|
||||
@@ -413,8 +635,13 @@ internal sealed class ConditionFixture : IDisposable
|
||||
AllowedOperations = operations, MaxConditions = _maxConditions, AllowGalaxyServiceAck = _galaxyAck }], conditionPlacements: placements);
|
||||
}
|
||||
|
||||
/// <summary>A redeploy with the same serving identity: condition <paramref name="add"/> joins, <paramref name="remove"/> leaves.</summary>
|
||||
internal void Deploy(int add, int remove)
|
||||
/// <summary>
|
||||
/// Swaps the catalog object WITHOUT a catalog attempt (same serving identity): condition <paramref name="add"/>
|
||||
/// joins, <paramref name="remove"/> leaves. ⚠️ Not what a production deploy does — that begins a catalog attempt,
|
||||
/// changes the serving identity and ends the stream (see the real-coordinator test). This exercises the stream's
|
||||
/// listing-change path only.
|
||||
/// </summary>
|
||||
internal void SwapListingWithoutAttempt(int add, int remove)
|
||||
{
|
||||
_listed.Add(add); _listed.Remove(remove);
|
||||
Source.Add(add); Source.Remove(remove);
|
||||
@@ -423,6 +650,9 @@ internal sealed class ConditionFixture : IDisposable
|
||||
|
||||
internal void Revoke() => _catalog = Compile(grant: false);
|
||||
|
||||
/// <summary>A catalog swap (same serving identity) that changes only the export's <c>MaxConditions</c>.</summary>
|
||||
internal void SetMaxConditions(int maxConditions) { _maxConditions = maxConditions; _catalog = Compile(_grant); }
|
||||
|
||||
internal ConditionItemStream? StreamOf(ConditionStream stream, bool allowMissing = false)
|
||||
{
|
||||
var streams = stream.Session.ConditionStreamsForTests;
|
||||
@@ -430,15 +660,17 @@ internal sealed class ConditionFixture : IDisposable
|
||||
return streams.Values.ShouldHaveSingleItem();
|
||||
}
|
||||
|
||||
internal async Task<ConditionStream> OpenAsync(bool items = true, bool readyReplica = false)
|
||||
internal static DataSubscriptionItem ConditionItem(string clientItemId, DataView root) =>
|
||||
new(clientItemId, root, new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null),
|
||||
new DataConditionScope(IncludeInfo: true));
|
||||
|
||||
internal async Task<ConditionStream> OpenAsync(bool items = true, bool readyReplica = false, IReadOnlyList<DataSubscriptionItem>? requestedItems = null)
|
||||
{
|
||||
var target = readyReplica ? new DataTarget(DataTargetMode.Node, "cluster", "node-a", DataConsistency.ReadyReplica) : Target;
|
||||
var connection = Services.Create(Context, target);
|
||||
var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
var session = (DataSubscriptionSession)subscription;
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
|
||||
IReadOnlyList<DataSubscriptionItem> requested = items
|
||||
? [new("conditions", _uns ? UnsRoot : Root, settings, new DataConditionScope(IncludeInfo: true))] : [];
|
||||
IReadOnlyList<DataSubscriptionItem> requested = requestedItems ?? (items ? [ConditionItem("conditions", _uns ? UnsRoot : Root)] : []);
|
||||
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(30), requested, false,
|
||||
TimeSpan.FromMinutes(5), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
var stream = new ConditionStream(this, connection, subscription, session);
|
||||
@@ -452,7 +684,52 @@ internal sealed class ConditionFixture : IDisposable
|
||||
public void Dispose() { ValueHub.Dispose(); }
|
||||
}
|
||||
|
||||
internal sealed record SnapshotRead(DataSubscriptionConditions Begin, IReadOnlyList<DataConditionState> Records, bool Complete);
|
||||
/// <summary>
|
||||
/// A2 review S1: an origin whose catalog comes from a real <see cref="LocalCatalogCoordinator"/> over a deployment
|
||||
/// artifact (one native alarm tag <c>Plant/Driver/Device/Alarm0</c> under an AlarmSubscribe raw export).
|
||||
/// </summary>
|
||||
internal sealed class CoordinatorConditionFixture : IDisposable
|
||||
{
|
||||
internal readonly ConditionFixture Conditions;
|
||||
private int _revision;
|
||||
|
||||
internal CoordinatorConditionFixture() => Conditions = new ConditionFixture(conditions: 1, artifact: Artifact(0));
|
||||
|
||||
/// <summary>Re-deploys the same configuration under a new revision.</summary>
|
||||
internal void Republish() => Conditions.Publish(Artifact(++_revision));
|
||||
|
||||
private static byte[] Artifact(int revision)
|
||||
{
|
||||
var root = System.Text.Json.Nodes.JsonNode.Parse("""
|
||||
{
|
||||
"Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}],
|
||||
"Nodes":[{"NodeId":"node-a","ClusterId":"cluster","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}],
|
||||
"ApiKeys":[{"ApiKeyId":"peer-key","Name":"peer-key","SecretHash":"hash","Principal":"peer","Enabled":true}],
|
||||
"NodeAcls":[],
|
||||
"RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}],
|
||||
"DriverInstances":[{"DriverInstanceId":"driver","ClusterId":"cluster","RawFolderId":"folder","Name":"Driver","DriverType":"Modbus","DriverConfig":"{}","Enabled":true}],
|
||||
"Devices":[{"DeviceId":"device","DriverInstanceId":"driver","Name":"Device","DeviceConfig":"{}","Enabled":true}],
|
||||
"TagGroups":[],
|
||||
"Tags":[{"TagId":"alarm-tag","DeviceId":"device","Name":"Alarm0","DataType":"Boolean","AccessLevel":0,
|
||||
"TagConfig":"{\"alarm\":{\"alarmType\":\"AlarmCondition\",\"severity\":700}}"}],
|
||||
"UnsAreas":[],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[],
|
||||
"DataConnections":[],"RemoteNamespaceMappings":[]
|
||||
}
|
||||
""")!.AsObject();
|
||||
root["NodeAcls"] = System.Text.Json.JsonSerializer.SerializeToNode(new[] { new NodeAcl { NodeAclId = "grant", ClusterId = "cluster",
|
||||
Principal = "peer", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.ReadOnly } });
|
||||
root["DataExports"] = System.Text.Json.JsonSerializer.SerializeToNode(new[] { new DataExport { DataExportId = "export",
|
||||
ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer",
|
||||
AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe
|
||||
| DataOperations.AlarmSubscribe, MaxConditions = 1000, Revision = revision + 1 } });
|
||||
return System.Text.Encoding.UTF8.GetBytes(root.ToJsonString());
|
||||
}
|
||||
|
||||
public void Dispose() => Conditions.Dispose();
|
||||
}
|
||||
|
||||
internal sealed record SnapshotRead(DataSubscriptionConditions Begin, IReadOnlyList<DataConditionState> Records, bool Complete,
|
||||
IReadOnlyList<DataSubscriptionConditions> Chunks);
|
||||
|
||||
internal sealed class ConditionStream(ConditionFixture fixture, IDataConnection connection, IDataSubscription subscription,
|
||||
DataSubscriptionSession session) : IAsyncDisposable
|
||||
@@ -516,6 +793,7 @@ internal sealed class ConditionStream(ConditionFixture fixture, IDataConnection
|
||||
DataSubscriptionConditions begin;
|
||||
do begin = await ReadConditionsAsync(fixture); while (!(begin.IsSnapshot && begin.Total is not null));
|
||||
var records = new List<DataConditionState>();
|
||||
var chunks = new List<DataSubscriptionConditions>();
|
||||
var complete = begin.SnapshotComplete;
|
||||
while (records.Count < begin.Total)
|
||||
{
|
||||
@@ -523,9 +801,10 @@ internal sealed class ConditionStream(ConditionFixture fixture, IDataConnection
|
||||
chunk.IsSnapshot.ShouldBeTrue();
|
||||
chunk.Total.ShouldBeNull();
|
||||
records.AddRange(chunk.Items);
|
||||
chunks.Add(chunk);
|
||||
complete = chunk.SnapshotComplete;
|
||||
}
|
||||
return new SnapshotRead(begin, records, complete);
|
||||
return new SnapshotRead(begin, records, complete, chunks);
|
||||
}
|
||||
|
||||
internal async Task<List<DataConditionState>> ReadDeltasUntilAsync(ConditionFixture f, Func<DataConditionState, bool> stop, int minimum = 1)
|
||||
|
||||
Reference in New Issue
Block a user