using System.Security.Cryptography; using System.Threading.Channels; using Microsoft.Extensions.Logging.Abstractions; using Opc.Ua; using Shouldly; using Xunit; 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.OpcUaServer.Security; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; /// /// A3a (plan §5.4, §5.5): the consumer condition runtime over a scripted origin stream — the per-mapping capacity /// decision before anything is materialised (and the item removed), the snapshot barrier, the host caps, 2,000 conditions /// without MaxProjectionNodes, the version rule (removal bypasses it and forgets the version), the lifetime rule (a /// stream end re-snapshots and never removes; only a complete re-snapshot does), staleness, the mapping gate with a real /// , primary placement from deployed config, and demand with linger. /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")] public sealed class GrpcDataProjectedConditionAccessTests { private const string Connection = "conn-a"; [Fact] public async Task A_total_over_MaxConditions_is_ConditionCapacity_and_its_item_removed_before_materialising_other_mappings_unaffected() { await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-b", total: 2); stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3)); stream.Begin("map-a", total: 3); // Positive control: the removal is the must-arrive effect of the LAST frame, so every earlier frame was processed. await f.WaitAsync(() => stream.Removed.Count == 1); stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the over-limit item is removed, not held open"); f.Sink.Applied.ShouldBeEmpty("nothing is materialised before the barrier"); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 2); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Complete); f.Sink.Applied.ShouldAllBe(u => u.Placements.All(p => p.MappingId == "map-b")); } [Fact] public async Task Two_thousand_conditions_in_one_mapping_materialise_without_MaxProjectionNodes_and_the_host_cap_rejects_before_materialising() { await using var f = new Fixture(("map-a", DataRealm.Raw, 5000)); f.Mappings.Current[0].Mapping.MaxProjectionNodes = 10; using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 2000); stream.Records("map-a", Enumerable.Range(0, 2000).Select(i => Record(Key("k" + i), 3)).ToArray()); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 2000); f.Sink.Applied.Select(u => u.State.ConditionKey).Distinct().Count().ShouldBe(2000); f.Mappings.Current[0].Mapping.MaxProjectionNodes.ShouldBe(10, "conditions have their own budget"); // Host cap: 1,999 conditions' worth of nodes ⇒ the 2,000-condition mapping is rejected at begin. await using var capped = new Fixture(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 1999 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50)), ("map-a", DataRealm.Raw, 5000)); using var cappedDemand = capped.Access.AcquireEventDemand(null); var cappedStream = await capped.NextStreamAsync(); cappedStream.Ack(); cappedStream.Begin("map-a", total: 2000); await capped.WaitAsync(() => cappedStream.Removed.Count == 1 && capped.Access.BarriersCompleted(Connection) == 1); capped.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); capped.Sink.Applied.ShouldBeEmpty("the barrier (the positive control) passed with nothing to materialise"); } [Fact] public async Task Versions_gate_per_key_but_a_removal_bypasses_the_gate_and_forgets_the_version() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 1); stream.Records("map-a", Record(Key("x"), 5)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); stream.Records("map-a", Record(Key("x"), 4, message: "stale")); // older ⇒ dropped stream.Records("map-a", Record(Key("x"), 5, removed: true)); // removal at the hub watermark (= an applied version) await f.WaitAsync(() => f.Sink.Removed.Count == 1); f.Sink.Applied.ShouldNotContain(u => u.State.Message == "stale"); stream.Records("map-a", Record(Key("x"), 3, message: "re-added")); // the version was forgotten await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Message == "re-added")); } [Fact] public async Task A_stream_end_re_snapshots_without_removing_and_only_a_complete_re_snapshot_removes_staleness_in_between() { // map-b (MaxConditions 0) is the positive control: its begin is refused, which must arrive as an item removal. await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 0)); using var demand = f.Access.AcquireEventDemand(null); var first = await f.NextStreamAsync(); first.Ack(); first.Begin("map-b", total: 1); first.Begin("map-a", total: 2); first.Records("map-a", Record(Key("x"), 3), Record(Key("y"), 3)); first.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 2); first.End(); // an origin deploy ends the stream (A2 S1) var second = await f.NextStreamAsync(); await f.WaitAsync(() => f.Sink.Stale.Count >= 1); // stale timeout (100 ms) passes before the new snapshot completes f.Sink.Removed.ShouldBeEmpty("a stream end is never 'conditions removed'"); second.Ack(); second.Begin("map-a", total: 1); second.Records("map-a", Record(Key("x"), 9)); second.Begin("map-b", total: 1); await f.WaitAsync(() => second.Removed.Count == 1); // positive control: every earlier frame was processed f.Sink.Removed.ShouldBeEmpty("an incomplete snapshot removes nothing"); second.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Count == 1); f.Sink.Removed.Single().ShouldBe(Key("y")); f.Access.BarriersCompleted(Connection).ShouldBe(2, "one barrier per stream: the first snapshot and the re-snapshot"); } [Fact] public async Task A_mapping_whose_snapshot_times_out_is_Unavailable_the_rest_proceed_and_RefreshRequired_follows() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); f.Mappings.Current[0].Mapping.ConditionSnapshotTimeoutMilliseconds = 300; f.Mappings.Current[1].Mapping.ConditionSnapshotTimeoutMilliseconds = 300; using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-b", total: 1); stream.Records("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); f.Sink.RefreshRequired.ShouldBe(1); } [Fact] public async Task The_primary_placement_comes_from_deployed_config_Raw_first_then_mapping_id_and_SourceName_follows_it() { await using var f = new Fixture(("map-u", DataRealm.Uns, 10), ("map-z", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); // Stream order deliberately the reverse of the deployed order. foreach (var mapping in new[] { "map-u", "map-z", "map-b" }) { stream.Begin(mapping, total: 1); stream.Records(mapping, Record(Key("x"), 3, placement: mapping == "map-u" ? f.UnsPlacement : f.RawPlacement)); stream.Complete(mapping); } await f.WaitAsync(() => f.Sink.Applied.Count == 1); var update = f.Sink.Applied.Single(); update.Placements.Select(p => p.MappingId).ShouldBe(["map-b", "map-z", "map-u"]); update.SourceName.ShouldBe("Plant/map-b/dev1/HR200", "the primary mapping's branch path + the address below the remote root"); update.Placements[0].FolderLocalSubject.ShouldBe("Plant/map-b/dev1"); } [Fact] public async Task The_gate_is_the_mapping_Subscribe_grant_on_the_placement_folder_and_needs_the_condition_bits() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, f.RawPlacement, "Plant/map-a/dev1", "dev1/HR200"); f.Grant(NodePermissions.Browse | NodePermissions.Subscribe); f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeTrue(); f.Access.CanSee(f.Identity("someone-else"), [placement]).ShouldBeFalse(); f.Access.CanSee(null, [placement]).ShouldBeFalse(); f.Grant(NodePermissions.Browse); f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("Subscribe is the visibility permission (not AlarmRead)"); f.Grant(NodePermissions.Browse | NodePermissions.Subscribe); f.Mappings.Current[0].Mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe; f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("a mapping without AlarmSubscribe carries no conditions"); } [Fact] public async Task Demand_opens_the_stream_and_the_linger_closes_it_and_removes_what_it_materialised() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); f.Access.IsRunning(Connection).ShouldBeFalse(); var demand = f.Access.AcquireEventDemand(null)!; var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 1); stream.Records("map-a", Record(Key("x"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); demand.Dispose(); f.Access.IsRunning(Connection).ShouldBeTrue("the linger keeps it open"); await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1); } // --------------------------------------------------------------------------------------------------------------------- // Review round 1 (a3a-review-round1.md) // --------------------------------------------------------------------------------------------------------------------- private static async Task CompleteFirstAsync(Fixture f, params (string Mapping, DataConditionState[] Records)[] snapshots) { var stream = await f.NextStreamAsync(); stream.Ack(); foreach (var (mapping, records) in snapshots) { stream.Begin(mapping, records.Length); stream.SnapshotRecords(mapping, records); stream.Complete(mapping); } await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 1); return stream; } [Fact] public async Task B1_an_in_stream_multi_frame_re_snapshot_keeps_every_condition_until_complete_then_removes_only_what_it_dropped() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3), Record(Key("z"), 3)]), ("map-b", [])); await f.WaitAsync(() => f.Sink.Live.Count == 3); // A2 re-snapshots inside a live stream (hub reader reset, retaken incomplete apply): begin, record frames, complete. stream.Begin("map-a", total: 2); stream.SnapshotRecords("map-a", Record(Key("x"), 4)); stream.SnapshotRecords("map-a", Record(Key("y"), 4)); stream.Records("map-b", Record(Key("ctl"), 1)); // positive control: a delta on the other mapping must be applied await f.WaitAsync(() => f.Sink.Live.Contains(Key("ctl"))); f.Sink.Removed.ShouldBeEmpty("a re-snapshot in progress removes nothing (B1)"); f.Sink.Live.ShouldContain(Key("z")); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Count == 1); f.Sink.Removed.Single().ShouldBe(Key("z"), "only the key the COMPLETE re-snapshot no longer lists is removed"); f.Sink.Live.ShouldBe([Key("x"), Key("y"), Key("ctl")], ignoreOrder: true); } [Fact] public async Task B1_an_in_stream_re_snapshot_over_capacity_removes_the_mapping_once_keeps_keys_another_mapping_lists_and_requires_refresh() { await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("y"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 2); var refreshes = f.Sink.RefreshRequired; stream.Begin("map-a", total: 3); // the origin now lists more than MaxConditions await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Count == 1); stream.Removed.Single().ShouldBe(stream.HandleOf("map-a")); f.Sink.Removed.Single().ShouldBe(Key("x"), "y is still listed by map-b"); f.Sink.Live.ShouldBe([Key("y")]); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); f.Sink.RefreshRequired.ShouldBeGreaterThan(refreshes, "clients are told the removal happened (§5.2)"); } private static Fixture TimedFixture(int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) { var f = new Fixture(mappings); foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs; return f; } [Fact] public async Task B2_a_snapshot_completing_after_the_timeout_is_merged_late_and_the_stream_is_kept() { await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-b", total: 1); stream.Records("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); stream.Begin("map-a", total: 1); // 2,000 conditions arriving 1 s late, in miniature stream.SnapshotRecords("map-a", Record(Key("w"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("w"))); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete); (await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(900))).ShouldBeNull("a late completion cancels the retry"); } [Fact] public async Task B2_an_incomplete_barrier_marks_the_incomplete_mappings_materialised_keys_BadNoCommunication_never_removed() { await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]), ("map-b", [Record(Key("y"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 2); first.End(); var second = await f.NextStreamAsync(); second.Ack(); second.Begin("map-b", total: 1); second.SnapshotRecords("map-b", Record(Key("y"), 4)); second.Complete("map-b"); // map-a never answers: the barrier passes at the timeout await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x"))); f.Sink.Removed.ShouldBeEmpty("unknown is not gone"); f.Sink.StaleKeys.ShouldNotContain(Key("y")); f.Sink.RefreshRequired.ShouldBeGreaterThanOrEqualTo(1); } [Fact] public async Task B2_S7_a_refused_item_is_an_incomplete_barrier_RefreshRequired_and_the_stream_is_retried_after_a_bounded_wait() { await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(refused: "map-a"); // e.g. a Secondary that advertises but refuses (A2 N7) stream.Begin("map-b", total: 1); stream.Records("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); f.Sink.RefreshRequired.ShouldBe(1, "S7: an incomplete barrier from a non-Good ack also requires refresh"); (await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("B2: an Unavailable mapping ends the stream; a new one retries it"); } [Fact] public async Task Deviation9_a_condition_stream_served_by_a_Secondary_is_dropped_and_reopened_on_the_Primary() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); f.Connections.Roles.Enqueue("Secondary"); using var demand = f.Access.AcquireEventDemand(null); var secondary = await f.NextStreamAsync(); var primary = await f.NextStreamAsync(); secondary.Disposed.ShouldBeTrue("never opened items on a Secondary"); f.Connections.PrimarySubscribes.ShouldBeGreaterThanOrEqualTo(2, "the Primary-only open is asked for"); primary.Ack(); primary.Begin("map-a", 1); primary.SnapshotRecords("map-a", Record(Key("x"), 3)); primary.Complete("map-a"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); } [Fact] public async Task S6_a_root_whose_metadata_fails_is_Unavailable_and_its_item_is_not_opened() { await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); f.Connections.MetadataFails.Add(0); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Mappings.ShouldBe(["map-b"]); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); } [Fact] public async Task B4_the_host_caps_are_node_wide_across_connections() { var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50)); await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10, "conn-a"), ("map-b", DataRealm.Raw, 10, "conn-b")); using var demand = f.Access.AcquireEventDemand(null); var streams = new[] { await f.NextStreamAsync(), await f.NextStreamAsync() }; foreach (var stream in streams) { var mapping = stream.Mappings.Single(); stream.Ack(); stream.Begin(mapping, 2); stream.SnapshotRecords(mapping, Record(Key(mapping + "1"), 3), Record(Key(mapping + "2"), 3)); stream.Complete(mapping); } await f.WaitAsync(() => f.Access.BarriersCompleted("conn-a") == 1 && f.Access.BarriersCompleted("conn-b") == 1); streams.Sum(x => x.Removed.Count).ShouldBe(1, "two connections of 2 cannot both fit a 3-condition node cap"); f.Sink.Live.Count.ShouldBe(2); f.Access.ChargedConditions.ShouldBeLessThanOrEqualTo(3); } [Fact] public async Task B4_admission_is_order_independent_a_later_ordered_begin_arriving_first_still_counts() { var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50)); await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-b", 2); stream.Begin("map-a", 2); await f.WaitAsync(() => stream.Removed.Count == 1); stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the second begin is decided against the first one's claim"); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); } [Fact] public async Task B4_records_past_the_snapshot_total_reset_the_mapping_to_ConditionCapacity_before_materialising() { await using var f = new Fixture(("map-a", DataRealm.Raw, 100)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 1); stream.SnapshotRecords("map-a", Enumerable.Range(0, 50).Select(i => Record(Key("k" + i), 3)).ToArray()); stream.Complete("map-a"); await f.WaitAsync(() => stream.Removed.Count == 1 && f.Access.BarriersCompleted(Connection) == 1); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); f.Sink.Applied.ShouldBeEmpty("an origin claiming total 1 cannot materialise 50 (the barrier is the positive control)"); f.Access.ChargedConditions.ShouldBe(0); } [Fact] public async Task B4_post_snapshot_delta_growth_past_MaxConditions_resets_the_mapping_and_removes_its_conditions() { await using var f = new Fixture(("map-a", DataRealm.Raw, 2)); using var demand = f.Access.AcquireEventDemand(null); var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 1); stream.Records("map-a", Record(Key("y"), 3), Record(Key("z"), 3)); await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Contains(Key("x"))); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); f.Sink.Live.ShouldBeEmpty(); } [Fact] public async Task S2_an_authority_deactivation_moves_the_authority_generation_so_cached_verdicts_are_re_proved() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); var before = f.Access.AuthorityGeneration; ((ActiveAuthority)f.Mappings.Current[0].Authority).Active = false; // no deploy, no epoch change f.Access.AuthorityGeneration.ShouldNotBe(before); } [Fact] public async Task S3_a_new_runner_waits_for_the_old_runners_removal_so_a_re_materialised_key_survives() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); var demand = f.Access.AcquireEventDemand(null)!; await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 1); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); f.Sink.RemovalGate = gate; // hold the old runner's removal open demand.Dispose(); await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired; its removal is now blocked in the sink using var again = f.Access.AcquireEventDemand(null); _ = Task.Delay(400, TestContext.Current.CancellationToken).ContinueWith(_ => gate.TrySetResult(), TaskScheduler.Default); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", 1); stream.SnapshotRecords("map-a", Record(Key("x"), 4)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Count == 1 && f.Sink.Applied.Count == 2); f.Sink.Live.ShouldContain(Key("x"), "the old runner's removal must not land after the new runner materialised the key"); } [Fact] public async Task S4_a_mapping_change_hands_the_materialised_set_over_after_the_old_loop_stopped() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 1); f.Mappings.Current[0].Mapping.MaxConditions = 11; // a changed signature ⇒ a new runner, a new stream f.Mappings.Raise(); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", 1); stream.SnapshotRecords("map-a", Record(Key("y"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x"))); f.Sink.Live.ShouldBe([Key("y")], "x was handed over (not orphaned) and the new complete set removed it"); } // --------------------------------------------------------------------------------------------------------------------- internal static string Key(string seed) => Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); private static DataConditionState Record(string key, long version, bool removed = false, string message = "high", DataView? placement = null) { var info = removed ? null : new DataConditionInfo("AlarmConditionType", "HR200", DataConditionSourceKind.Native, [placement ?? Fixture.DefaultRawPlacement], 3); return new DataConditionState(key, version, removed, !removed, info, true, false, true, true, 0, 500, message, 0, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1)); } private sealed class Fixture : IAsyncDisposable { internal static readonly DataView DefaultRawPlacement = new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"), DataRealm.Raw, null, 0, "Plant/dev1/HR200"); public DataView RawPlacement => DefaultRawPlacement; public DataView UnsPlacement { get; } = new(new DataAddress("origin", "https://zb.com/otopcua/uns", "string", "Area/Line/Filler/HR200"), DataRealm.Uns, null, 0, "Area/Line/Filler/HR200"); private readonly DataPlaneAuthorityState _state = new(); private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true, ExpiresUtc = DateTime.UtcNow.AddHours(1) }; public FakeMappings Mappings { get; } public FakeSink Sink { get; } = new(); public FakeConnections Connections { get; } = new(); public ProjectedConditionAccess Access { get; } public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings) : this(DefaultOptions, mappings) { } public static ProjectedConditionOptions DefaultOptions => new(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)); public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) : this(options, mappings.Select(m => (m.Id, m.Realm, m.MaxConditions, Connection)).ToArray()) { } public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions, string Connection)[] mappings) { Grant(NodePermissions.Browse | NodePermissions.Subscribe); Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions, m.Connection)).ToList()); var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System); Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance); } public void Grant(NodePermissions permissions) => _state.Apply("c1", "rev-" + (int)permissions, [_key], [new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "folder", PermissionFlags = permissions }], new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); public RoleCarryingUserIdentity Identity(string principal) => new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, _key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5)); private static ProjectedMappingPlacement Placement(string id, DataRealm realm, int maxConditions, string connection) { var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = id, DataConnectionId = connection, Enabled = true, Realm = realm, RemoteRealm = realm, AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe, MaxConditions = maxConditions, ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000, BranchName = id, RemoteNamespaceUri = realm == DataRealm.Raw ? "https://zb.com/otopcua/raw" : "https://zb.com/otopcua/uns", RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "Plant" : "Area", }; var segments = new[] { "Plant", id }; var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", mapping.RemoteIdentifier), realm, id, 1, string.Join('/', segments)); var scope = new NodeScope { ClusterId = "c1", Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = segments }; return new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority()); } public async Task NextStreamAsync() => await Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken); /// The next stream within , or null. public async Task TryNextStreamAsync(TimeSpan within) { using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); cts.CancelAfter(within); try { return await Connections.Streams.Reader.ReadAsync(cts.Token); } catch (OperationCanceledException) when (!TestContext.Current.CancellationToken.IsCancellationRequested) { return null; } } public async Task WaitAsync(Func condition) { var deadline = DateTime.UtcNow.AddSeconds(10); while (!condition()) { if (DateTime.UtcNow > deadline) condition().ShouldBeTrue("condition not met within 10 s"); await Task.Delay(20, TestContext.Current.CancellationToken); } } public ValueTask DisposeAsync() { Access.Dispose(); return ValueTask.CompletedTask; } } private sealed class ActiveAuthority : IDataMappedCatalogAuthority { public long CatalogEpoch => 1; public long AuthorityEpoch => 1; public bool Active { get; set; } = true; public bool IsActive => Active; } internal sealed class FakeMappings(List current) : IProjectedConditionMappings { public IReadOnlyList Current { get; } = current; public event Action? Changed; public void Raise() => Changed?.Invoke(); } internal sealed class FakeSink : IProjectedConditionSink { private readonly object _gate = new(); private readonly List _applied = []; private readonly List _removed = []; private readonly List _stale = []; private readonly List _staleKeys = []; private readonly HashSet _live = new(StringComparer.Ordinal); private int _refresh; public IReadOnlyList Applied { get { lock (_gate) return _applied.ToList(); } } public IReadOnlyList Removed { get { lock (_gate) return _removed.ToList(); } } public IReadOnlyList Stale { get { lock (_gate) return _stale.ToList(); } } public IReadOnlyList StaleKeys { get { lock (_gate) return _staleKeys.ToList(); } } /// The keys the sink holds right now (applied minus removed). public IReadOnlyCollection Live { get { lock (_gate) return _live.ToList(); } } public int RefreshRequired => Volatile.Read(ref _refresh); /// When set, a removal blocks until released (the S3 race window, held open). public TaskCompletionSource? RemovalGate { get; set; } public void ApplyConditions(IReadOnlyList updates) { lock (_gate) { _applied.AddRange(updates); foreach (var u in updates) _live.Add(u.State.ConditionKey); } } public void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys) { RemovalGate?.Task.Wait(TimeSpan.FromSeconds(10)); lock (_gate) { _removed.AddRange(conditionKeys); foreach (var k in conditionKeys) _live.Remove(k); } } public void MarkConnectionStale(string connectionId) { lock (_gate) _stale.Add(connectionId); } public void MarkConditionsStale(string connectionId, IReadOnlyCollection conditionKeys) { lock (_gate) _staleKeys.AddRange(conditionKeys); } public void RequireRefresh(string connectionId) => Interlocked.Increment(ref _refresh); } internal sealed class FakeConnections : IGrpcDataAdapterConnectionSource { public Channel Streams { get; } = Channel.CreateUnbounded(); /// Metadata answers Bad for these root indexes (deployed order). public HashSet MetadataFails { get; } = []; /// The serving roles of the next streams (Primary when empty). public Queue Roles { get; } = new(); public int PrimarySubscribes; public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => ValueTask.FromResult(new Lease(new FakeConnection(this))); private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease { public IDataConnection Connection => connection; public CancellationToken CancellationToken => CancellationToken.None; public ValueTask DisposeAsync() => ValueTask.CompletedTask; } } private sealed class FakeConnection(FakeConnections owner) : IDataConnection, IDataPrimarySubscriptionSource { public Task SubscribePrimaryAsync(CancellationToken cancellationToken) { Interlocked.Increment(ref owner.PrimarySubscribes); return SubscribeAsync(cancellationToken); } public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null); public TimeProvider Clock => TimeProvider.System; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => Task.FromResult>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i) ? new DataItemResult("0", DataItemStatus.Unavailable, null, null) : new DataItemResult("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false), null)).ToArray()); public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task SubscribeAsync(CancellationToken cancellationToken) { string role; lock (owner.Roles) role = owner.Roles.TryDequeue(out var next) ? next : "Primary"; var stream = new FakeStream(role); owner.Streams.Writer.TryWrite(stream); return Task.FromResult(stream); } public ValueTask DisposeAsync() => ValueTask.CompletedTask; } internal sealed class FakeStream(string role = "Primary") : IDataSubscription, IDataSubscriptionProvenance { public ServingIdentity Serving { get; } = new("origin-1", "inc-1", role, 1, 1); public bool Disposed { get; private set; } /// The mapping ids this stream opened items for. public IReadOnlyList Mappings => Open.Items.Select(x => x.ClientItemId).ToArray(); private readonly Channel _frames = Channel.CreateUnbounded(); private readonly TaskCompletionSource _open = new(TaskCreationOptions.RunContinuationsAsynchronously); private long _sequence; public List Removed { get; } = []; public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) { if (command is OpenSubscription open) _open.TrySetResult(open); if (command is RemoveSubscriptionItems remove) lock (Removed) Removed.AddRange(remove.Items); return Task.CompletedTask; } public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); public ValueTask DisposeAsync() { Disposed = true; _frames.Writer.TryComplete(); return ValueTask.CompletedTask; } private OpenSubscription Open => _open.Task.Wait(TimeSpan.FromSeconds(10)) ? _open.Task.Result : throw new TimeoutException("no open"); public DataItemHandle HandleOf(string mapping) { var index = Open.Items.Select((x, i) => (x, i)).Single(x => x.x.ClientItemId == mapping).i; return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1); } public void Ack(params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open", Open.Items.Select(x => refused.Contains(x.ClientItemId) ? new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Unavailable, null, x.Settings, "secondary") : new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray())); /// Snapshot record frames exactly as the A2 origin frames them (is_snapshot, no total). public void SnapshotRecords(string mapping, params DataConditionState[] records) { foreach (var chunk in records.Chunk(128)) Frame(mapping, true, null, chunk, false); } public void Begin(string mapping, int total) => Frame(mapping, true, total, [], false); public void Records(string mapping, params DataConditionState[] records) { foreach (var chunk in records.Chunk(128)) Frame(mapping, false, null, chunk, false); } public void Complete(string mapping) => Frame(mapping, true, null, [], true); public void End() => _frames.Writer.TryComplete(); private void Frame(string mapping, bool snapshot, int? total, IReadOnlyList items, bool complete) => _frames.Writer.TryWrite(new DataSubscriptionConditions(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, HandleOf(mapping), snapshot, total, items, complete)); } }