Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs
T
Joseph Doherty b2fab8b075 test(grpc-data): #928 — overflow test asserted one of two legal outcomes; deterministic Reset test + either-outcome contract test; DataConnections.md A4 reconcile (#930 retries, condition metrics, AdminUI fields)
The origin item sees a hub eviction only at its next hub read: Reset if the last snapshot chunk is
still undelivered, otherwise a silent fresh snapshot on the same stream (both per A2, both loss-free
since the A3 consumer swaps a buffered re-snapshot in as a full replacement). Since A2 review S5 the
3,000-record snapshot is 59 chunks and the silent path wins when run alone (fails 3/3 alone at the A2
merge too; passes in its class). No product change. Also fixes the stale ack/confirm/shelve comment on
ConditionMethodTimeoutMilliseconds.
2026-11-25 00:08:06 -05:00

946 lines
54 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Security.Cryptography;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
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;
/// <summary>
/// A2a (plan §5.1 A2 replay contract, §5.5 stream mechanics): root-scoped condition items on the origin's real
/// subscription session, over a real <see cref="ConditionStateHub"/> and a node-manager-faithful snapshot source.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A2")]
public sealed class GrpcDataConditionStreamTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Fact]
public async Task Snapshot_begins_with_total_then_records_then_complete_and_a_delta_follows()
{
using var f = new ConditionFixture(conditions: 3);
await using var stream = await f.OpenAsync();
var snapshot = await stream.ReadSnapshotAsync();
snapshot.Begin.Total.ShouldBe(3);
snapshot.Begin.Items.ShouldBeEmpty("the begin chunk carries only the count (admission before materialising)");
snapshot.Records.Count.ShouldBe(3);
snapshot.Records.ShouldAllBe(r => r.Info != null && r.Info.Placements.Count == 1 && r.StateKnown);
snapshot.Complete.ShouldBeTrue();
snapshot.Records.Select(r => r.ConditionKey).ShouldBeUnique();
f.Source.Raise(0, active: true);
var delta = await stream.ReadConditionsAsync(f);
delta.IsSnapshot.ShouldBeFalse();
var record = delta.Items.ShouldHaveSingleItem();
record.Active.ShouldBeTrue();
record.Info.ShouldBeNull("info rides only the first appearance in an epoch and snapshot records");
record.ConditionKey.ShouldBe(snapshot.Records.Single(r => r.ConditionKey == f.KeyOf(0)).ConditionKey);
}
[Fact]
public async Task Total_above_the_limit_is_reported_before_any_record_and_nothing_else_is_sent()
{
using var f = new ConditionFixture(conditions: 3, maxConditions: 2);
await using var stream = await f.OpenAsync();
var first = await stream.ReadConditionsAsync(f);
first.IsSnapshot.ShouldBeTrue();
first.Total.ShouldBe(3);
first.Items.ShouldBeEmpty();
f.Source.SnapshotCalls.ShouldBe(0, "over the limit nothing is copied under the node manager's Lock");
f.Source.Raise(0, active: true);
(await stream.TryReadConditionsAsync(f, TimeSpan.FromSeconds(2))).ShouldBeNull("an over-capacity item sends no records");
await stream.ExpectHeartbeatOrNothingAsync(f); // positive control: the stream itself is alive
}
[Fact]
public async Task A_slice_cut_while_deltas_arrive_has_no_gap_and_no_duplicate()
{
using var f = new ConditionFixture(conditions: 6);
f.Source.SliceSize = 2;
// Between the first and the second hold: one change to a condition already copied (must arrive as a delta) and one
// to a condition not yet copied (inside the next slice; must NOT arrive again as a delta).
f.Source.BetweenSlices = slice =>
{
if (slice != 1) return;
f.Source.Raise(0, active: true);
f.Source.Raise(4, active: true);
};
await using var stream = await f.OpenAsync();
var snapshot = await stream.ReadSnapshotAsync();
snapshot.Complete.ShouldBeTrue();
f.Source.SnapshotHolds.ShouldBe(3);
snapshot.Records.Single(r => r.ConditionKey == f.KeyOf(0)).Active.ShouldBeFalse("slice 1 was cut before the change");
snapshot.Records.Single(r => r.ConditionKey == f.KeyOf(4)).Active.ShouldBeTrue("slice 3 holds the change");
f.Source.Raise(5, active: true); // a later delta, the positive control that deltas are flowing
var deltas = await stream.ReadDeltasUntilAsync(f, r => r.ConditionKey == f.KeyOf(5));
deltas.Count(r => r.ConditionKey == f.KeyOf(0)).ShouldBe(1, "no gap: the change after slice 1's cut arrives once");
deltas.Count(r => r.ConditionKey == f.KeyOf(4)).ShouldBe(0, "no duplicate: the change inside slice 3 is not replayed");
var applied = Apply(snapshot.Records.Concat(deltas));
for (var i = 0; i < 6; i++) applied[f.KeyOf(i)].Active.ShouldBe(f.Source.IsActive(i));
}
[Fact]
public async Task A_hub_reader_reset_takes_a_fresh_snapshot()
{
using var f = new ConditionFixture(conditions: 2, partitionCapacity: 2);
await using var stream = await f.OpenAsync();
(await stream.ReadSnapshotAsync()).Complete.ShouldBeTrue();
f.Source.Raise(0, active: true);
(await stream.ReadConditionsAsync(f)).Items.ShouldHaveSingleItem(); // the item has read past its snapshot
await Task.Delay(200, Ct); // let the tick queued by that delivery finish before ticks are held
f.HoldTicks = true;
for (var i = 0; i < 6; i++) f.Source.Raise(1, active: i % 2 == 0); // evicts records above the item's cursor
f.HoldTicks = false;
var again = await stream.ReadSnapshotAsync();
again.Begin.Total.ShouldBe(2);
again.Complete.ShouldBeTrue();
again.Records.Single(r => r.ConditionKey == f.KeyOf(1)).Active.ShouldBe(f.Source.IsActive(1));
f.StreamOf(stream)!.Resets.ShouldBe(1);
}
/// <summary>
/// #928: an eviction the item detects while its last snapshot chunk is still undelivered ⇒ stream <c>Reset</c>
/// ("overflow"). Deterministic: the whole snapshot (begin + 6 chunks) fits the 16-frame condition queue, and the
/// consumer reads nothing after the ack, so the last chunk is still queued when the session tick makes the item read
/// the hub. (The former version raced a 3,000-record delivery against the producer — see the contract test below.)
/// </summary>
[Fact]
public async Task Overflow_before_the_snapshot_is_drained_resets_the_stream()
{
using var f = new ConditionFixture(conditions: 300, maxConditions: 5000, partitionCapacity: 2);
await using var stream = await f.OpenAsync();
await stream.ReadAckAsync(); // the ack's delivery activates the item; nothing after it is read until the Reset
var item = await WaitForAsync(() => f.StreamOf(stream, allowMissing: true) is { ChargedBytes: > 0 } s ? s : null);
// The snapshot is taken (its start cursor precedes the raises) and charged, so its last chunk is undelivered.
for (var i = 0; i < 6; i++) f.Source.Raise(0, active: i % 2 == 0); // the hub evicts above the item's start cursor
await WaitForAsync(() => { f.Tick(); return item.Overflowed ? item : null; }); // the session tick runs the pump
var reset = await stream.ReadUntilAsync<DataSubscriptionControl>(f, c => c.Kind == DataStreamControlKind.Reset);
reset.Diagnostic.ShouldNotBeNull().ShouldContain("overflow");
item.Snapshots.ShouldBe(1, "an overflow resets the stream; the item does not re-snapshot behind an undelivered snapshot");
}
/// <summary>
/// #928 contract: an eviction during a long snapshot delivery that the consumer is draining has TWO legal outcomes,
/// decided by whether the item reads the hub before or after the session commits the snapshot's last chunk — a
/// stream <c>Reset</c> (the consumer reconnects and re-snapshots) or a silent fresh snapshot on the same stream (a new
/// begin; A3 buffers it and swaps at <c>snapshot_complete</c>). Either way no change is lost: the state the consumer
/// ends with matches the source.
/// </summary>
[Fact]
public async Task An_eviction_during_a_long_snapshot_delivery_resets_or_resnapshots_without_losing_a_change()
{
using var f = new ConditionFixture(conditions: 3000, maxConditions: 5000, partitionCapacity: 2);
await using var stream = await f.OpenAsync();
await stream.ReadAckAsync();
(await stream.ReadConditionsAsync(f)).Total.ShouldBe(3000);
var item = f.StreamOf(stream)!;
for (var i = 0; i < 6; i++) f.Source.Raise(0, active: i % 2 == 0); // evicts above the item's start cursor
var expected = f.Source.IsActive(0);
while (true)
{
var frame = await stream.NextAsync() ?? throw new InvalidOperationException("Neither a Reset nor a fresh snapshot.");
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset } reset)
{
reset.Diagnostic.ShouldNotBeNull().ShouldContain("overflow");
item.Overflowed.ShouldBeTrue();
await using var fresh = await f.OpenAsync(); // what the consumer does next: reconnect and re-snapshot
var snapshot = await fresh.ReadSnapshotAsync();
snapshot.Complete.ShouldBeTrue();
snapshot.Records.Count.ShouldBe(3000);
snapshot.Records.Single(r => r.ConditionKey == f.KeyOf(0)).Active.ShouldBe(expected);
return;
}
if (frame is DataSubscriptionConditions { IsSnapshot: true, Total: { } total })
{
// The silent path: a hub reader reset after the last chunk was delivered ⇒ a complete fresh snapshot.
total.ShouldBe(3000);
var records = new List<DataConditionState>();
var complete = false;
while (!complete)
{
var chunk = await stream.ReadConditionsAsync(f);
chunk.IsSnapshot.ShouldBeTrue("no delta interleaves a snapshot");
records.AddRange(chunk.Items);
complete = chunk.SnapshotComplete;
}
records.Count.ShouldBe(3000);
records.Single(r => r.ConditionKey == f.KeyOf(0)).Active.ShouldBe(expected);
item.Overflowed.ShouldBeFalse();
item.Resets.ShouldBe(1);
item.Snapshots.ShouldBe(2);
stream.Ended.ShouldBeFalse("a re-snapshot is not a stream reset");
return;
}
}
}
private static async Task<T> WaitForAsync<T>(Func<T?> probe) where T : class
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (DateTime.UtcNow < deadline)
{
if (probe() is { } value) return value;
await Task.Delay(10, Ct);
}
throw new TimeoutException("Condition not reached.");
}
[Fact]
public async Task A_backlog_above_the_pending_frame_limit_back_pressures_a_stalled_sink_instead_of_resetting()
{
// 3,000 records = 24 record chunks + a begin chunk, above the session's 16 pending frames (review B1).
using var f = new ConditionFixture(conditions: 3000, maxConditions: 5000);
await using var stream = await f.OpenAsync();
await stream.ReadAckAsync();
// The sink stalls: nothing is read while the session's 100 ms tick keeps running the pump on a full queue.
for (var i = 0; i < 20; i++) { f.Tick(); await Task.Delay(25, Ct); }
var snapshot = await stream.ReadSnapshotAsync();
snapshot.Begin.Total.ShouldBe(3000);
snapshot.Records.Count.ShouldBe(3000);
snapshot.Complete.ShouldBeTrue("the snapshot completes once the sink drains");
stream.Ended.ShouldBeFalse("a full queue is back-pressure, not a stream reset");
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();
}
// Values wake the loop; the idle condition queue's wait must be reused, not re-registered on every pass.
(stream.Session.ConditionWaitsStartedForTests - before).ShouldBeLessThanOrEqualTo(1);
}
[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.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.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>();
}
[Fact]
public async Task Revocation_mid_snapshot_delivers_no_further_condition_record_and_ends_the_stream()
{
using var f = new ConditionFixture(conditions: 400, maxConditions: 1000);
await using var stream = await f.OpenAsync();
await stream.ReadAckAsync();
var begin = await stream.ReadConditionsAsync(f);
begin.Total.ShouldBe(400);
f.Revoke(); // the export loses AlarmSubscribe (a redeploy with the same serving identity)
var after = await stream.DrainAsync(f);
after.OfType<DataSubscriptionConditions>().SelectMany(x => x.Items).Count().ShouldBeLessThan(400);
stream.Ended.ShouldBeTrue("a revoked condition item ends the stream, like a revoked v1 value item");
// The worker's teardown (after the reader ended) releases the condition item.
await stream.Session.Completion.WaitAsync(TimeSpan.FromSeconds(10), Ct);
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 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.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));
added.Removed.ShouldBeFalse(); added.Info.ShouldNotBeNull();
var removed = deltas.Single(r => r.ConditionKey == f.KeyOf(0));
removed.Removed.ShouldBeTrue();
}
[Fact]
public async Task A_uns_listing_never_carries_a_RawPath_or_driver_id()
{
using var f = new ConditionFixture(conditions: 2, unsPrincipal: true);
await using var stream = await f.OpenAsync();
var snapshot = await stream.ReadSnapshotAsync();
snapshot.Records.Count.ShouldBe(2);
foreach (var record in snapshot.Records)
{
record.Info!.Placements.ShouldAllBe(p => p.Realm == DataRealm.Uns && p.Address.NamespaceUri == "https://zb.com/otopcua/uns");
var wire = DataConditionProtoMapper.EncodeState(record).ToString();
wire.ShouldNotContain("Plant/");
wire.ShouldNotContain("driver");
}
}
/// <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()
{
using (var standby = new ConditionFixture(conditions: 1, role: "Secondary"))
{
await using var stream = await standby.OpenAsync(readyReplica: true);
(await stream.ReadAckAsync()).Items.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Unavailable);
}
using var ungranted = new ConditionFixture(conditions: 1, grantAlarmSubscribe: false);
await using var denied = await ungranted.OpenAsync();
(await denied.ReadAckAsync()).Items.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Denied);
}
[Fact]
public async Task An_incomplete_snapshot_is_retaken_complete_once_the_apply_completes()
{
using var f = new ConditionFixture(conditions: 2);
f.Source.ApplyComplete = false;
await using var stream = await f.OpenAsync();
var first = await stream.ReadSnapshotAsync();
first.Complete.ShouldBeFalse("snapshot_complete is withheld until the origin's apply completed");
f.Source.ApplyComplete = true;
f.Hub.OnApplyStateChanged(true);
var second = await stream.ReadSnapshotAsync();
second.Complete.ShouldBeTrue();
second.Begin.Total.ShouldBe(2);
}
[Fact]
public async Task Capabilities_advertise_AlarmSubscribe_and_conditions_only_when_a_key_secret_is_provisioned()
{
using var f = new ConditionFixture(conditions: 1);
var caps = await f.Services.Create(f.Context, f.Target).GetCapabilitiesAsync(LocalDataFixture.Budget, Ct);
caps.Operations.HasFlag(DataOperations.AlarmSubscribe).ShouldBeTrue();
caps.Conditions.ShouldNotBeNull().MaxConditions.ShouldBe(1000);
using var keyless = new ConditionFixture(conditions: 1, secret: false);
var none = await keyless.Services.Create(keyless.Context, keyless.Target).GetCapabilitiesAsync(LocalDataFixture.Budget, Ct);
none.Operations.HasFlag(DataOperations.AlarmSubscribe).ShouldBeFalse();
none.Conditions.ShouldBeNull();
}
private static Dictionary<string, DataConditionState> Apply(IEnumerable<DataConditionState> records)
{
var state = new Dictionary<string, DataConditionState>(StringComparer.Ordinal);
foreach (var r in records)
{
if (state.TryGetValue(r.ConditionKey, out var prior)) r.Version.ShouldBeGreaterThan(prior.Version, "a duplicate was applied");
state[r.ConditionKey] = r;
}
return state;
}
}
/// <summary>A snapshot source with the node manager's semantics: one watermark per hold, start cursor before enumeration.</summary>
internal sealed class FakeConditionSource(ConditionStateHub hub) : IOriginConditionSource
{
private readonly object _lock = new();
private readonly SortedDictionary<string, bool> _active = new(StringComparer.Ordinal);
internal int SliceSize { get; set; } = int.MaxValue;
internal Action<int>? BetweenSlices { get; set; }
internal bool ApplyComplete { get; set; } = true;
internal int SnapshotCalls, SnapshotHolds;
internal static string IdOf(int i) => $"Plant/Driver/Device/Alarm{i}";
internal void Add(int i) { lock (_lock) { _active[IdOf(i)] = false; hub.Append(Record(IdOf(i), false, false)); } }
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)]; }
/// <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)..]);
/// <summary>A2b: the method port's verdict (default: applied, native); every call is recorded.</summary>
internal Func<OriginConditionMethodCall, OriginConditionMethodOutcome> Execute { get; set; } = _ => new(true, true, 0, null);
internal List<OriginConditionMethodCall> MethodCalls { get; } = [];
public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call)
{
lock (MethodCalls) MethodCalls.Add(call);
return Execute(call);
}
public IReadOnlyList<ConditionSnapshotSlice> SnapshotConditions(Func<AddressSpaceRealm, string, bool> scope, int maxConditionsPerHold)
{
Interlocked.Increment(ref SnapshotCalls);
long start;
lock (_lock) start = hub.Watermark;
List<string> keys;
lock (_lock) keys = _active.Keys.Where(k => scope(AddressSpaceRealm.Raw, k)).ToList();
var per = Math.Min(Math.Min(maxConditionsPerHold, 5000), SliceSize);
var slices = new List<ConditionSnapshotSlice>();
for (var at = 0; slices.Count == 0 || at < keys.Count; at += per)
{
if (slices.Count > 0) BetweenSlices?.Invoke(slices.Count);
lock (_lock)
{
Interlocked.Increment(ref SnapshotHolds);
var watermark = hub.Watermark;
var records = keys.Skip(at).Take(per).Where(_active.ContainsKey).Select(k => Record(k, _active[k], false, watermark)).ToList();
slices.Add(new ConditionSnapshotSlice(watermark, records, start, 1, ApplyComplete));
}
if (keys.Count == 0) break;
}
return slices;
}
}
internal sealed class AlwaysPrimary : IDriverPrimaryRoleSource
{
public bool ShouldActAsPrimary => true;
public void PublishPrimaryRole(bool isPrimary) { }
}
/// <summary>An origin with N native alarm conditions under the raw folder "Plant" (and, for UNS, under the Area folder).</summary>
internal sealed class ConditionFixture : IDisposable
{
private static readonly string Secret = Convert.ToBase64String(RandomNumberGenerator.GetBytes(48));
internal readonly ManualTimeProvider Clock = new();
internal readonly ServingIdentity Serving;
internal readonly DataPlaneAuthorityState Authority = new();
internal readonly CatalogActivation Activation = new();
internal readonly PartitionedSampleHub ValueHub;
internal readonly ConditionStateHub Hub;
internal readonly FakeConditionSource Source;
internal readonly RecordingAuditLog AuditLog = new();
internal readonly LocalDataServices Services;
internal readonly DataAuthenticatedContext Context;
/// <summary>A second principal (<c>peer2</c>, same grants and ACLs), only with <c>secondPrincipal: true</c>.</summary>
internal readonly DataAuthenticatedContext? Context2;
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 int _maxConditions;
private readonly string? _unsName;
private readonly bool _grant;
private readonly HashSet<int> _listed = [];
private readonly DataOperations _extra;
private readonly string? _driverType;
private readonly bool _galaxyAck;
private readonly bool _second;
private volatile LocalExportCatalog _catalog;
internal volatile bool HoldTicks;
private readonly List<ConditionStream> _streams = [];
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,
long maxPendingBytes = 200_000, int maxMessageBytes = 1_000_000, long? principalSnapshotBytes = null,
int maxConditionItems = SubscriptionSessionLimits.DefaultMaxConditionItems, string? unsDisplayName = null,
byte[]? artifact = null, bool secondPrincipal = false, int? methodMaxOperations = null, int? methodMaxPerPrincipal = null)
{
_second = secondPrincipal;
_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);
Hub = new ConditionStateHub(new AlwaysPrimary(), partitionCount: 1, partitionCapacity: partitionCapacity);
Hub.OnApplyStateChanged(true);
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 };
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);
}
var key2 = new ApiKey { ApiKeyId = "peer2-key", Name = "peer2-key", Principal = "peer2", SecretHash = "hash2", Enabled = true };
if (artifact is null)
{
IReadOnlyList<NodeAcl> grants = acls ?? [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer",
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.ReadOnly }];
if (secondPrincipal)
grants = [.. grants, .. grants.Select(a => new NodeAcl { NodeAclId = a.NodeAclId + "-2", ClusterId = a.ClusterId,
Principal = "peer2", ScopeKind = a.ScopeKind, ScopeId = a.ScopeId, PermissionFlags = a.PermissionFlags })];
Authority.Apply("cluster", "first", secondPrincipal ? [key, key2] : [key], grants,
scopePaths ?? new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
}
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);
if (secondPrincipal)
Context2 = new("peer2", key2.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key2), 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, 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(() => 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))
{
ConditionHub = Hub, ConditionSource = Source, ConditionKeysSource = () => Keys, Audit = AuditLog,
ConditionMethodMaxOperations = methodMaxOperations ?? LocalDataServices.DefaultConditionMethodMaxOperations,
ConditionMethodMaxOperationsPerPrincipal = methodMaxPerPrincipal ?? LocalDataServices.DefaultConditionMethodMaxOperationsPerPrincipal,
};
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)
{
var folder = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false);
var unsFolder = folder with { View = UnsRoot, BrowseName = "Area" };
var nodes = new List<LocalDataNode>
{
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)
{
var id = FakeConditionSource.IdOf(i);
var condition = new OriginConditionRef(AddressSpaceRealm.Raw, id);
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));
// 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('/') }, effective,
ConditionSourceKind.Native, condition, "UnsTagReference", "ref-" + i, _driverType));
}
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe
| (grant ? DataOperations.AlarmSubscribe | _extra : DataOperations.None);
DataExport Export(string id, string principal) => new()
{
DataExportId = id, ClusterId = "cluster", Enabled = true, Realm = _uns ? DataRealm.Uns : DataRealm.Raw,
RootKind = _uns ? "UnsArea" : "RawFolder", RootEntityId = _uns ? "area" : "folder", PrincipalId = principal,
AllowedOperations = operations, MaxConditions = _maxConditions, AllowGalaxyServiceAck = _galaxyAck,
};
return new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes,
_second ? [Export("export", "peer"), Export("export-2", "peer2")] : [Export("export", "peer")], conditionPlacements: placements);
}
/// <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);
_catalog = Compile(_grant);
}
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;
if (allowMissing && streams.Count == 0) return null;
return streams.Values.ShouldHaveSingleItem();
}
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;
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);
_streams.Add(stream);
return stream;
}
/// <summary>Drives the session's 100 ms tick (unless held, to let the hub evict without the item reading).</summary>
internal void Tick() { if (!HoldTicks) Clock.Advance(TimeSpan.FromMilliseconds(250)); }
public void Dispose() { ValueHub.Dispose(); }
}
/// <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
{
private readonly IAsyncEnumerator<DataSubscriptionFrame> _frames = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator();
private bool _ackSeen;
internal DataSubscriptionSession Session => session;
internal bool Ended { get; private set; }
internal async Task<DataSubscriptionFrame?> NextAsync(TimeSpan? timeout = null)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(10));
var move = _frames.MoveNextAsync().AsTask();
while (!move.IsCompleted)
{
if (DateTime.UtcNow > deadline) return null;
fixture.Tick();
await Task.WhenAny(move, Task.Delay(20, TestContext.Current.CancellationToken));
}
if (!await move) { Ended = true; return null; }
if (_frames.Current is DataSubscriptionAck) _ackSeen = true;
return _frames.Current;
}
internal async Task<DataSubscriptionAck> ReadAckAsync()
{
while (true)
{
var frame = await NextAsync() ?? throw new InvalidOperationException("No ack.");
if (frame is DataSubscriptionAck ack) return ack;
}
}
internal async Task<DataSubscriptionConditions?> TryReadConditionsAsync(ConditionFixture f, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
var frame = await NextAsync(deadline - DateTime.UtcNow);
if (frame is null) return null;
if (frame is DataSubscriptionConditions conditions) return conditions;
}
return null;
}
internal async Task<DataSubscriptionConditions> ReadConditionsAsync(ConditionFixture f) =>
await TryReadConditionsAsync(f, TimeSpan.FromSeconds(10)) ?? throw new InvalidOperationException("No condition frame.");
internal async Task<T> ReadUntilAsync<T>(ConditionFixture f, Func<T, bool> match) where T : DataSubscriptionFrame
{
while (true)
{
var frame = await NextAsync() ?? throw new InvalidOperationException($"No {typeof(T).Name}.");
if (frame is T t && match(t)) return t;
}
}
internal async Task<SnapshotRead> ReadSnapshotAsync()
{
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)
{
var chunk = await ReadConditionsAsync(fixture);
chunk.IsSnapshot.ShouldBeTrue();
chunk.Total.ShouldBeNull();
records.AddRange(chunk.Items);
chunks.Add(chunk);
complete = chunk.SnapshotComplete;
}
return new SnapshotRead(begin, records, complete, chunks);
}
internal async Task<List<DataConditionState>> ReadDeltasUntilAsync(ConditionFixture f, Func<DataConditionState, bool> stop, int minimum = 1)
{
var all = new List<DataConditionState>();
while (all.Count(stop) < minimum)
{
var frame = await ReadConditionsAsync(f);
frame.IsSnapshot.ShouldBeFalse();
all.AddRange(frame.Items);
}
return all;
}
internal async Task<List<DataSubscriptionFrame>> DrainAsync(ConditionFixture f)
{
var frames = new List<DataSubscriptionFrame>();
while (await NextAsync(TimeSpan.FromSeconds(5)) is { } frame) frames.Add(frame);
return frames;
}
internal async Task ExpectHeartbeatOrNothingAsync(ConditionFixture f)
{
Ended.ShouldBeFalse();
_ackSeen.ShouldBeTrue();
await Task.CompletedTask;
}
public async ValueTask DisposeAsync()
{
await _frames.DisposeAsync();
await subscription.DisposeAsync();
await connection.DisposeAsync();
}
}
/// <summary>A2b: an in-memory data-connection audit log.</summary>
internal sealed class RecordingAuditLog : IDataConnectionAuditLog
{
public List<DataConditionMethodAuditEntry> Entries { get; } = [];
public void RecordConditionMethod(DataConditionMethodAuditEntry entry) { lock (Entries) Entries.Add(entry); }
}