diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs index 7be3e979c..03bc12fb8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs @@ -6,7 +6,9 @@ using ZB.MOM.WW.OtOpcUa.OpcUaServer; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// One chunk of a root-scoped condition item, ready to become a frame. -internal sealed record ConditionChunk(bool IsSnapshot, int? Total, IReadOnlyList Items, bool SnapshotComplete); +/// The last chunk of snapshot number (its delivery is reported back). +internal sealed record ConditionChunk(bool IsSnapshot, int? Total, IReadOnlyList Items, bool SnapshotComplete, + int Snapshot = 0, bool EndsSnapshot = false); /// The condition set an item may currently see: the catalog it was listed from and the listing (null = revoked). internal sealed record ConditionItemScope(object Catalog, IReadOnlyList? Conditions); @@ -54,7 +56,8 @@ internal sealed class ConditionItemStream private long[] _cursors = []; private object? _catalog; private State _state = State.NeedSnapshot; - private bool _beginSent, _snapshotComplete, _retakeWhenReady, _readSinceSnapshot; + private bool _beginSent, _snapshotComplete, _retakeWhenReady; + private int _deliveredSnapshot; private int _total; private long _lastSnapshotAt = long.MinValue; @@ -93,6 +96,14 @@ internal sealed class ConditionItemStream /// internal bool Overflowed { get; private set; } + /// The session delivered the last chunk of snapshot (any thread). + internal void SnapshotDelivered(int snapshot) + { + int current; + do current = Volatile.Read(ref _deliveredSnapshot); + while (snapshot > current && Interlocked.CompareExchange(ref _deliveredSnapshot, snapshot, current) != current); + } + /// Produce the next chunk, or null when there is nothing to send now. internal ConditionChunk? Next() { @@ -135,7 +146,7 @@ internal sealed class ConditionItemStream _lastSnapshotAt = _clock.GetTimestamp(); _catalog = scope.Catalog; _snapshotRecords.Clear(); _sliceWatermarks.Clear(); _pendingDeltas.Clear(); _sent.Clear(); _inScope.Clear(); - _beginSent = false; _snapshotComplete = false; _retakeWhenReady = false; _readSinceSnapshot = false; + _beginSent = false; _snapshotComplete = false; _retakeWhenReady = false; var listing = scope.Conditions!; if (listing.Count > _limit) { @@ -181,14 +192,15 @@ internal sealed class ConditionItemStream { _beginSent = true; // The begin chunk carries only the count, so the consumer decides capacity before materialising anything. - if (_snapshotRecords.Count == 0) { _state = State.Live; return new ConditionChunk(true, _total, [], _snapshotComplete); } + if (_snapshotRecords.Count == 0) + { _state = State.Live; return new ConditionChunk(true, _total, [], _snapshotComplete, Snapshots, EndsSnapshot: true); } return new ConditionChunk(true, _total, [], false); } var batch = new List(Math.Min(MaxRecordsPerChunk, _snapshotRecords.Count)); while (batch.Count < MaxRecordsPerChunk && _snapshotRecords.TryDequeue(out var record)) batch.Add(record); var last = _snapshotRecords.Count == 0; if (last) _state = State.Live; - return new ConditionChunk(true, null, batch, last && _snapshotComplete); + return new ConditionChunk(true, null, batch, last && _snapshotComplete, Snapshots, EndsSnapshot: last); } /// Reads every partition after its cursor into the pending deltas. False when a reader reset is required. @@ -200,8 +212,8 @@ internal sealed class ConditionItemStream var read = _hub.Read(p, _cursors[p], MaxRecordsPerChunk); if (read.ResetRequired) { - // Evicted before the first read after a snapshot: the consumer could not drain one snapshot in time. - if (!_readSinceSnapshot) Overflowed = true; + // Evicted while the last snapshot was still undelivered: the consumer cannot drain one snapshot in time. + if (Volatile.Read(ref _deliveredSnapshot) < Snapshots) Overflowed = true; return false; } foreach (var record in read.Records) @@ -222,7 +234,6 @@ internal sealed class ConditionItemStream _pendingDeltas.Enqueue(Map(record, scoped, includeInfo: first && _includeInfo)); } } - _readSinceSnapshot = true; return true; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs index a9b14ecd0..af9e9bbd7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs @@ -11,6 +11,14 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Production is pull-based (): 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. /// +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 { private sealed class ConditionItem(string clientItemId, DataItemHandle handle, ConditionItemAuthority authority, @@ -152,6 +160,7 @@ internal sealed partial class DataSubscriptionSession chunk.IsSnapshot, chunk.Total, chunk.Items, chunk.SnapshotComplete), () => Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && _services.CanUseSubscription(_context, _target, serving) && IsConditionItemCurrent(item) && item.Authority.CanPublish(), + commit: () => { if (chunk.EndsSnapshot) item.Stream.SnapshotDelivered(chunk.Snapshot); return true; }, obsolete: () => Volatile.Read(ref _closing) != 0 || !IsConditionItemCurrent(item)); } @@ -161,8 +170,10 @@ internal sealed partial class DataSubscriptionSession } /// - /// The next delivery by priority: a queued control or ack first, then a condition frame, then the queued value. Null - /// when the stream's queues are completed and drained. + /// The next delivery by priority: a control or ack at the head of the v1 queue first, then a condition frame, then the + /// v1 queue in FIFO order (a v1 control never overtakes a value queued before it: snapshot begin/end ordering depends + /// on that). So conditions overtake queued values, and never a control or ack that is next. Null when the stream's + /// queues are completed and drained. /// private async ValueTask NextPendingAsync(CancellationToken token) { @@ -195,6 +206,26 @@ internal sealed partial class DataSubscriptionSession } } + /// Test seam: the stream has processed its Open. + internal bool IsOpenForTests => Volatile.Read(ref _handles) is not null; + + /// + /// Test seam (stream priority): queues an empty value frame and a heartbeat control on the v1 queue (control first + /// when ), then a condition frame. + /// + internal async Task EnqueuePriorityProbesForTests(DataItemHandle conditionHandle, bool controlFirst) + { + 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(); + } + /// Called from the worker's teardown: completes and drains the condition queue, releases condition items. private void TearDownConditions() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs new file mode 100644 index 000000000..31cb83241 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs @@ -0,0 +1,528 @@ +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.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// 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 and a node-manager-faithful snapshot source. +/// +[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); + } + + [Fact] + public async Task Overflow_before_the_snapshot_is_drained_resets_the_stream() + { + // 3,000 records = 24 chunks, more than the 16-frame condition queue: the last chunk is produced only after the + // consumer drained most of them, and the item reads the hub right after producing it — still undelivered. + 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); + for (var i = 0; i < 6; i++) f.Source.Raise(0, active: i % 2 == 0); // the hub evicts above the item's start cursor + var reset = await stream.ReadUntilAsync(f, c => c.Kind == DataStreamControlKind.Reset); + reset.Diagnostic.ShouldNotBeNull().ShouldContain("overflow"); + } + + [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(); + // 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.NextAsync()).ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.Heartbeat); + (await stream.NextAsync()).ShouldBeOfType(); + (await stream.NextAsync()).ShouldBeOfType(); + // 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.NextAsync()).ShouldBeOfType(); + (await stream.NextAsync()).ShouldBeOfType(); + (await stream.NextAsync()).ShouldBeOfType(); + } + + [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().SelectMany(x => x.Items).Count().ShouldBeLessThan(400); + stream.Ended.ShouldBeTrue("a revoked condition item ends the stream, like a revoked v1 value item"); + // Frames already prepared before the revocation are bounded by the queue; nothing is produced after it. + f.StreamOf(stream, allowMissing: true).ShouldBeNull(); + } + + [Fact] + public async Task An_origin_deploy_adding_and_removing_conditions_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 + 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"); + } + } + + [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 Apply(IEnumerable records) + { + var state = new Dictionary(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; + } +} + +/// A snapshot source with the node manager's semantics: one watermark per hold, start cursor before enumeration. +internal sealed class FakeConditionSource(ConditionStateHub hub) : IOriginConditionSource +{ + private readonly object _lock = new(); + private readonly SortedDictionary _active = new(StringComparer.Ordinal); + internal int SliceSize { get; set; } = int.MaxValue; + internal Action? 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)]; } + 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, + new ConditionActivationMarker("inc", 1), ConditionType: "nsu=http://opcfoundation.org/UA/;i=2915", + ConditionName: id[(id.LastIndexOf('/') + 1)..]); + + public IReadOnlyList SnapshotConditions(Func scope, int maxConditionsPerHold) + { + Interlocked.Increment(ref SnapshotCalls); + long start; + lock (_lock) start = hub.Watermark; + List 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(); + 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) { } +} + +/// An origin with N native alarm conditions under the raw folder "Plant" (and, for UNS, under the Area folder). +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 LocalDataServices Services; + internal readonly DataAuthenticatedContext Context; + 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"); + internal readonly ConditionKeys Keys; + private readonly bool _uns; + private readonly int _maxConditions; + private readonly bool _grant; + private readonly HashSet _listed = []; + private volatile LocalExportCatalog _catalog; + internal volatile bool HoldTicks; + private readonly List _streams = []; + + internal ConditionFixture(int conditions, int maxConditions = 1000, bool unsPrincipal = false, string role = "Primary", + bool grantAlarmSubscribe = true, bool secret = true, int partitionCapacity = ConditionStateHub.DefaultPartitionCapacity) + { + _uns = unsPrincipal; _maxConditions = maxConditions; _grant = grantAlarmSubscribe; + 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 }; + Authority.Apply("cluster", "first", [key], + [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.Cluster, + PermissionFlags = NodePermissions.ReadOnly }], new Dictionary>()); + 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)); + LocalDataServices? services = null; + services = new LocalDataServices(() => _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 }; + Services = services; + } + + 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 + { + 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), + }; + var placements = new List(); + 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)); + var uns = $"Area/Line/Equipment/Alarm{i}"; + 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, + ConditionSourceKind.Native, condition, "UnsTagReference", "ref-" + i)); + } + var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe + | (grant ? DataOperations.AlarmSubscribe : DataOperations.None); + return new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes, + [new() { DataExportId = "export", ClusterId = "cluster", Enabled = true, Realm = _uns ? DataRealm.Uns : DataRealm.Raw, + RootKind = _uns ? "UnsArea" : "RawFolder", RootEntityId = _uns ? "area" : "folder", PrincipalId = "peer", + AllowedOperations = operations, MaxConditions = _maxConditions }], conditionPlacements: placements); + } + + /// A redeploy with the same serving identity: condition joins, leaves. + internal void Deploy(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); + + 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 async Task OpenAsync(bool items = true, bool readyReplica = false) + { + 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 requested = items + ? [new("conditions", _uns ? UnsRoot : Root, settings, new DataConditionScope(IncludeInfo: true))] : []; + 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; + } + + /// Drives the session's 100 ms tick (unless held, to let the hub evict without the item reading). + internal void Tick() { if (!HoldTicks) Clock.Advance(TimeSpan.FromMilliseconds(250)); } + + public void Dispose() { ValueHub.Dispose(); } +} + +internal sealed record SnapshotRead(DataSubscriptionConditions Begin, IReadOnlyList Records, bool Complete); + +internal sealed class ConditionStream(ConditionFixture fixture, IDataConnection connection, IDataSubscription subscription, + DataSubscriptionSession session) : IAsyncDisposable +{ + private readonly IAsyncEnumerator _frames = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(); + private bool _ackSeen; + internal DataSubscriptionSession Session => session; + internal bool Ended { get; private set; } + + internal async Task 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 ReadAckAsync() + { + while (true) + { + var frame = await NextAsync() ?? throw new InvalidOperationException("No ack."); + if (frame is DataSubscriptionAck ack) return ack; + } + } + + internal async Task 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 ReadConditionsAsync(ConditionFixture f) => + await TryReadConditionsAsync(f, TimeSpan.FromSeconds(10)) ?? throw new InvalidOperationException("No condition frame."); + + internal async Task ReadUntilAsync(ConditionFixture f, Func 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 ReadSnapshotAsync() + { + DataSubscriptionConditions begin; + do begin = await ReadConditionsAsync(fixture); while (!(begin.IsSnapshot && begin.Total is not null)); + var records = new List(); + var complete = begin.SnapshotComplete; + while (records.Count < begin.Total) + { + var chunk = await ReadConditionsAsync(fixture); + chunk.IsSnapshot.ShouldBeTrue(); + chunk.Total.ShouldBeNull(); + records.AddRange(chunk.Items); + complete = chunk.SnapshotComplete; + } + return new SnapshotRead(begin, records, complete); + } + + internal async Task> ReadDeltasUntilAsync(ConditionFixture f, Func stop, int minimum = 1) + { + var all = new List(); + while (all.Count(stop) < minimum) + { + var frame = await ReadConditionsAsync(f); + frame.IsSnapshot.ShouldBeFalse(); + all.AddRange(frame.Items); + } + return all; + } + + internal async Task> DrainAsync(ConditionFixture f) + { + var frames = new List(); + 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(); + } +}