969f3d4645
Co-Authored-By: Claude <noreply@anthropic.com>
963 lines
56 KiB
C#
963 lines
56 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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 <c>MaxProjectionNodes</c>, 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
|
|
/// <see cref="DataOperationPolicy"/>, primary placement from deployed config, and demand with linger.
|
|
/// </summary>
|
|
[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);
|
|
await f.WaitAsync(() => f.Sink.RefreshRequired >= 1); // the barrier applies before it asks for the refresh
|
|
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<FakeStream> 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);
|
|
// #931 N7: the removal itself carries RefreshRequired to the holders (the sink's §5.2 "removal + RefreshRequired"), so
|
|
// the reset does not ask a second time.
|
|
f.Sink.RefreshRequired.ShouldBe(refreshes, "one RefreshRequired per capacity reset: the removal's");
|
|
}
|
|
|
|
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);
|
|
await f.WaitAsync(() => f.Sink.RefreshRequired >= 1); // the barrier applies before it asks for the refresh
|
|
f.Sink.RefreshRequired.ShouldBe(1, "S7: an incomplete barrier from a non-Good ack also requires refresh");
|
|
// #930 N2: the retry is IN-STREAM (the item re-added after the bounded wait) — the stream is not ended for it.
|
|
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
|
|
stream.AckAdd("map-a");
|
|
stream.Begin("map-a", total: 1);
|
|
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(300))).ShouldBeNull("no new stream: map-b is never re-snapshotted for map-a");
|
|
f.Sink.Applied.Count(u => u.State.ConditionKey == Key("x")).ShouldBe(1, "the healthy mapping's condition is not re-applied");
|
|
f.Sink.RefreshRequired.ShouldBe(1, "a recovered mapping needs no second RefreshRequired");
|
|
}
|
|
|
|
[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");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task N1_demand_cycles_and_mapping_changes_do_not_chain_runners_so_an_old_runner_is_collectable()
|
|
{
|
|
// Verification review r2 N1: each runner kept its predecessor (and that one's record sets), so every linger expiry
|
|
// + re-subscribe or mapping change added a link R3 → R2 → R1 and memory grew without bound.
|
|
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)]));
|
|
var first = f.Access.RunnerReference(Connection)!;
|
|
var version = 3L;
|
|
for (var cycle = 0; cycle < 3; cycle++)
|
|
{
|
|
demand.Dispose();
|
|
await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired
|
|
demand = f.Access.AcquireEventDemand(null)!;
|
|
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)]));
|
|
}
|
|
for (var change = 0; change < 2; change++)
|
|
{
|
|
f.Mappings.Current[0].Mapping.MaxConditions++; // a changed signature ⇒ a new runner, a new stream
|
|
f.Mappings.Raise();
|
|
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)]));
|
|
}
|
|
f.Sink.Live.ShouldBe([Key("x")], "the hand-over still works across every cycle");
|
|
for (var i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); }
|
|
first.IsAlive.ShouldBeFalse("the current runner must not keep a chain of predecessors reachable");
|
|
demand.Dispose();
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
|
|
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));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
// #930 (N2/N3) and #931 (N4/N5/N7/N8) — A4
|
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
|
|
private static Fixture LongRetryFixture(TimeSpan longRetry, int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
|
|
{
|
|
var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = longRetry }, mappings);
|
|
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs;
|
|
return f;
|
|
}
|
|
|
|
[Fact]
|
|
public async Task N2_a_definitive_refusal_waits_the_long_backoff_on_the_open_stream_never_storming_the_healthy_mapping()
|
|
{
|
|
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 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(DataItemStatus.Denied, "map-a");
|
|
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);
|
|
// A transient refusal would be retried after the 300 ms snapshot timeout (and, before #930, the stream ended for it).
|
|
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(1.5))).ShouldBeNull("the stream is kept");
|
|
stream.AddsOf("map-a").ShouldBe(0, "Denied is definitive: the long backoff, not the snapshot timeout");
|
|
f.Sink.Applied.Count.ShouldBe(1, "map-b is not re-snapshotted");
|
|
f.Sink.RefreshRequired.ShouldBe(1);
|
|
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task N2_an_unchanged_incomplete_set_on_a_new_stream_sends_no_second_RefreshRequired_a_changed_one_does()
|
|
{
|
|
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
|
using var demand = f.Access.AcquireEventDemand(null);
|
|
var first = await f.NextStreamAsync();
|
|
first.Ack(DataItemStatus.Denied, "map-a");
|
|
first.Begin("map-b", total: 1);
|
|
first.Records("map-b", Record(Key("x"), 3));
|
|
first.Complete("map-b");
|
|
await f.WaitAsync(() => f.Sink.RefreshRequired == 1);
|
|
first.End();
|
|
|
|
var second = await f.NextStreamAsync();
|
|
second.Ack(DataItemStatus.Denied, "map-a"); // still refused: the same incomplete set
|
|
second.Begin("map-b", total: 1);
|
|
second.SnapshotRecords("map-b", Record(Key("x"), 4));
|
|
second.Complete("map-b");
|
|
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 2);
|
|
f.Sink.RefreshRequired.ShouldBe(1, "the clients were already told about map-a");
|
|
second.End();
|
|
|
|
var third = await f.NextStreamAsync();
|
|
third.Ack(DataItemStatus.Denied, "map-a", "map-b"); // a changed incomplete set ⇒ told again (positive control)
|
|
// The barrier count moves before the barrier's RefreshRequired, so wait for the refresh itself. It is also the positive
|
|
// control for the second stream's absence: had that barrier asked, this would read 3.
|
|
await f.WaitAsync(() => f.Sink.RefreshRequired >= 2);
|
|
await Task.Delay(100, TestContext.Current.CancellationToken);
|
|
f.Sink.RefreshRequired.ShouldBe(2);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task N3_a_ConditionCapacity_mapping_is_re_added_in_stream_on_the_long_timer_and_recovers_when_under_its_limit()
|
|
{
|
|
await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(400), 30_000, ("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-a", total: 3); // over its MaxConditions
|
|
stream.Begin("map-b", total: 1);
|
|
stream.SnapshotRecords("map-b", Record(Key("x"), 3));
|
|
stream.Complete("map-b");
|
|
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
|
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
|
|
|
|
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
|
|
stream.AckAdd("map-a");
|
|
stream.Begin("map-a", total: 2); // the origin dropped back under the limit
|
|
stream.SnapshotRecords("map-a", Record(Key("y"), 3), Record(Key("z"), 3));
|
|
stream.Complete("map-a");
|
|
await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")) && f.Sink.Live.Contains(Key("z")));
|
|
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
|
|
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(300))).ShouldBeNull("recovered on the open stream");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task N3_a_retry_still_over_capacity_stays_ConditionCapacity_and_is_retried_again_never_removing_what_another_mapping_lists()
|
|
{
|
|
await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(300), 30_000, ("map-a", DataRealm.Raw, 1), ("map-b", DataRealm.Raw, 10));
|
|
using var demand = f.Access.AcquireEventDemand(null);
|
|
var stream = await f.NextStreamAsync();
|
|
stream.Ack();
|
|
stream.Begin("map-a", total: 2);
|
|
stream.Begin("map-b", total: 1);
|
|
stream.SnapshotRecords("map-b", Record(Key("x"), 3));
|
|
stream.Complete("map-b");
|
|
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
|
|
stream.AckAdd("map-a");
|
|
stream.Begin("map-a", total: 2);
|
|
await f.WaitAsync(() => stream.AddsOf("map-a") == 2); // backoff doubled, still in-stream
|
|
f.Sink.Removed.ShouldBeEmpty("map-b's key is never removed by map-a's retries (T2)");
|
|
f.Sink.Live.ShouldBe([Key("x")]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task N4_streams_that_never_reach_a_barrier_back_off_exponentially()
|
|
{
|
|
var options = Fixture.DefaultOptions with { MaxReconnectDelay = TimeSpan.FromMilliseconds(400) };
|
|
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10));
|
|
f.Connections.MetadataFails.Add(0); // every mapping's root fails ⇒ every stream ends before a barrier
|
|
using var demand = f.Access.AcquireEventDemand(null);
|
|
await Task.Delay(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
|
|
var calls = Volatile.Read(ref f.Connections.MetadataCalls);
|
|
calls.ShouldBeGreaterThan(2, "it keeps retrying");
|
|
// Fixed 50 ms reconnects would make ~40 attempts in 2 s; 50, 100, 200, 400, 400… makes ≤ ~8.
|
|
calls.ShouldBeLessThan(12);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task N5_held_stale_keys_are_charged_beside_a_known_mappings_new_claim_but_overlap_an_unknown_mappings()
|
|
{
|
|
var options = Fixture.DefaultOptions with { MaxImportedConditionNodes = 3 * 49 }; // 3 conditions on the node
|
|
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
|
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = 300;
|
|
f.Mappings.Current[0].Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
|
|
f.Mappings.Current[1].Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
|
|
using var demand = f.Access.AcquireEventDemand(null);
|
|
var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("z"), 3)]));
|
|
await f.WaitAsync(() => f.Sink.Live.Count == 3);
|
|
first.End();
|
|
|
|
var second = await f.NextStreamAsync();
|
|
second.Ack();
|
|
second.Begin("map-b", total: 1);
|
|
second.SnapshotRecords("map-b", Record(Key("z"), 4));
|
|
second.Complete("map-b"); // map-a never answers: x, y held stale (unlisted)
|
|
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
|
// map-b (known) now re-lists z plus a new w: 4 conditions would be held — over the 3-condition cap.
|
|
second.Begin("map-b", total: 2);
|
|
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-b"] == ProjectedConditionMappingStatus.ConditionCapacity);
|
|
f.Sink.Live.ShouldNotContain(Key("w"));
|
|
f.Sink.Removed.ShouldBeEmpty("map-a is unknown: nothing is removed (T2)");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task N8_a_stopped_runner_is_not_kept_parked_after_its_removal_finished()
|
|
{
|
|
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
|
|
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);
|
|
demand.Dispose();
|
|
await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1);
|
|
await f.WaitAsync(() => !f.Access.IsParked(Connection));
|
|
f.Access.RunnerReference(Connection).ShouldBeNull("a connection that never returns pins no runner");
|
|
stream.Disposed.ShouldBeTrue();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A4_consumer_diagnostics_show_stream_state_snapshot_time_counts_vs_limits_capacity_and_state_unknown()
|
|
{
|
|
await using var f = LongRetryFixture(TimeSpan.FromMinutes(10), 30_000, ("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10));
|
|
var idle = f.Access.Diagnostics.CaptureConsumer(Connection).ShouldNotBeNull();
|
|
idle.StreamState.ShouldBe("idle");
|
|
idle.Mappings.Select(x => x.MappingId).ShouldBe(["map-a", "map-b"]);
|
|
f.Access.Diagnostics.CaptureConsumer("not-a-condition-connection").ShouldBeNull();
|
|
|
|
using var demand = f.Access.AcquireEventDemand(null);
|
|
var stream = await f.NextStreamAsync();
|
|
stream.Ack();
|
|
stream.Begin("map-a", total: 3); // over its MaxConditions of 2
|
|
stream.Begin("map-b", total: 2);
|
|
stream.SnapshotRecords("map-b", Record(Key("x"), 3), Record(Key("y"), 3) with { StateKnown = false });
|
|
stream.Complete("map-b");
|
|
await f.WaitAsync(() => f.Sink.Live.Count == 2);
|
|
var live = f.Access.Diagnostics.CaptureConsumer(Connection).ShouldNotBeNull();
|
|
live.StreamState.ShouldBe("live");
|
|
live.SnapshotAtUtc.ShouldNotBeNull();
|
|
(live.Materialised, live.StateUnknown, live.CapacityRejections).ShouldBe((2, 1, 1L));
|
|
live.Mappings.ShouldBe([new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.ConditionMappingDiagnostics("map-a", "ConditionCapacity", 3, 2), new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.ConditionMappingDiagnostics("map-b", "Complete", 2, 10)]);
|
|
live.ChargedConditions.ShouldBe(2);
|
|
live.HostConditionLimit.ShouldBe(122_500 / 49);
|
|
}
|
|
|
|
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<AclScopeRef, IReadOnlyList<NodeAclPath>> { [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<FakeStream> NextStreamAsync() => await Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
|
|
|
|
/// <summary>The next stream within <paramref name="within"/>, or null.</summary>
|
|
public async Task<FakeStream?> 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<bool> 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<ProjectedMappingPlacement> current) : IProjectedConditionMappings
|
|
{
|
|
public IReadOnlyList<ProjectedMappingPlacement> 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<ImportedConditionUpdate> _applied = [];
|
|
private readonly List<string> _removed = [];
|
|
private readonly List<string> _stale = [];
|
|
private readonly List<string> _staleKeys = [];
|
|
private readonly HashSet<string> _live = new(StringComparer.Ordinal);
|
|
private int _refresh;
|
|
public IReadOnlyList<ImportedConditionUpdate> Applied { get { lock (_gate) return _applied.ToList(); } }
|
|
public IReadOnlyList<string> Removed { get { lock (_gate) return _removed.ToList(); } }
|
|
public IReadOnlyList<string> Stale { get { lock (_gate) return _stale.ToList(); } }
|
|
public IReadOnlyList<string> StaleKeys { get { lock (_gate) return _staleKeys.ToList(); } }
|
|
/// <summary>The keys the sink holds right now (applied minus removed).</summary>
|
|
public IReadOnlyCollection<string> Live { get { lock (_gate) return _live.ToList(); } }
|
|
public int RefreshRequired => Volatile.Read(ref _refresh);
|
|
/// <summary>When set, a removal blocks until released (the S3 race window, held open).</summary>
|
|
public TaskCompletionSource? RemovalGate { get; set; }
|
|
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates)
|
|
{
|
|
lock (_gate) { _applied.AddRange(updates); foreach (var u in updates) _live.Add(u.State.ConditionKey); }
|
|
}
|
|
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> 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<string> conditionKeys) { lock (_gate) _staleKeys.AddRange(conditionKeys); }
|
|
public void RequireRefresh(string connectionId) => Interlocked.Increment(ref _refresh);
|
|
}
|
|
|
|
internal sealed class FakeConnections : IGrpcDataAdapterConnectionSource
|
|
{
|
|
public Channel<FakeStream> Streams { get; } = Channel.CreateUnbounded<FakeStream>();
|
|
/// <summary>Metadata answers Bad for these root indexes (deployed order).</summary>
|
|
public HashSet<int> MetadataFails { get; } = [];
|
|
/// <summary>#931 N4: metadata requests made (one per stream attempt, plus in-stream root retries).</summary>
|
|
public int MetadataCalls;
|
|
/// <summary>The serving roles of the next streams (Primary when empty).</summary>
|
|
public Queue<string> Roles { get; } = new();
|
|
public int PrimarySubscribes;
|
|
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
|
|
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(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<IDataSubscription> 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<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
|
|
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
|
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
|
|
Interlocked.Increment(ref owner.MetadataCalls) < 0 ? throw new InvalidOperationException() : Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
|
|
? new DataItemResult<DataMetadata>("0", DataItemStatus.Unavailable, null, null)
|
|
: new DataItemResult<DataMetadata>("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<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
|
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
|
public Task<IDataSubscription> 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<IDataSubscription>(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; }
|
|
/// <summary>The mapping ids this stream opened items for.</summary>
|
|
public IReadOnlyList<string> Mappings => Open.Items.Select(x => x.ClientItemId).ToArray();
|
|
private readonly Channel<DataSubscriptionFrame> _frames = Channel.CreateUnbounded<DataSubscriptionFrame>();
|
|
private readonly TaskCompletionSource<OpenSubscription> _open = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
private long _sequence;
|
|
public List<DataItemHandle> Removed { get; } = [];
|
|
/// <summary>#930: in-stream item re-adds (retries), in order.</summary>
|
|
public List<AddSubscriptionItems> Adds { get; } = [];
|
|
private readonly Dictionary<string, DataItemHandle> _current = new(StringComparer.Ordinal);
|
|
private ulong _nextHandle = 100;
|
|
|
|
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);
|
|
if (command is AddSubscriptionItems add) lock (Adds) Adds.Add(add);
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
/// <summary>How many re-adds named <paramref name="mapping"/>.</summary>
|
|
public int AddsOf(string mapping) { lock (Adds) return Adds.Count(a => a.Items.Any(i => i.ClientItemId == mapping)); }
|
|
|
|
/// <summary>Acks the latest re-add of <paramref name="mapping"/> (Good ⇒ a fresh handle that later frames use).</summary>
|
|
public void AckAdd(string mapping, DataItemStatus status = DataItemStatus.Good)
|
|
{
|
|
AddSubscriptionItems add;
|
|
lock (Adds) add = Adds.Last(a => a.Items.Any(i => i.ClientItemId == mapping));
|
|
DataItemHandle? handle = null;
|
|
if (status == DataItemStatus.Good)
|
|
{
|
|
handle = new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, ++_nextHandle, 1);
|
|
lock (_current) _current[mapping] = handle;
|
|
}
|
|
_frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, add.CommandId,
|
|
[new DataSubscriptionItemAck(mapping, status, handle, null, status == DataItemStatus.Good ? null : "refused")]));
|
|
}
|
|
|
|
public IAsyncEnumerable<DataSubscriptionFrame> 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)
|
|
{
|
|
lock (_current) if (_current.TryGetValue(mapping, out var current)) return current;
|
|
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) => Ack(DataItemStatus.Unavailable, refused);
|
|
|
|
public void Ack(DataItemStatus refusal, 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, refusal, null, x.Settings, "refused")
|
|
: new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray()));
|
|
|
|
/// <summary>Snapshot record frames exactly as the A2 origin frames them (is_snapshot, no total).</summary>
|
|
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<DataConditionState> items, bool complete) =>
|
|
_frames.Writer.TryWrite(new DataSubscriptionConditions(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, HandleOf(mapping), snapshot,
|
|
total, items, complete));
|
|
}
|
|
}
|