9d969c4724
S1: a held key that a transiently unknown mapping listed itself (_lastListed) is held without a bound; only a definitive refusal of that mapping (Denied / NotFound / Unsupported / ConditionCapacity, remembered across retries and stream ends) starts its MaxUnknownHold clock. Consistent with a never-opening stream. S2: the hold clock runs only while a stream is past its barrier (paused at the stream end, shifted at the next barrier). N1: in-stream root re-resolves run under a per-stream source cancelled when the stream ends. N2: no held-expiry timer without a sink (spin). N3: MaxUnknownHold must be positive. N5: #933 test lower bound taken before the hold starts; tests for S1, S2, N1, N2, N3 and a second failed re-resolve — each red on revert.
1636 lines
96 KiB
C#
1636 lines
96 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
|
||
// A4 review r1 B1: the second capacity reset's remove used the first one's command id, which the transport refuses
|
||
// (the FakeStream now does too), ending the stream.
|
||
f.Connections.Streams.Reader.TryPeek(out _).ShouldBeFalse("both capacity resets stayed on the open stream");
|
||
lock (stream.Removed) stream.Removed.Count.ShouldBe(2, "each reset removed its item");
|
||
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);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
// A4 review round 1 (S1–S4, NITs). B1 is pinned by the FakeStream's command-id uniqueness rule (it made
|
||
// N3_a_retry_still_over_capacity… red) plus the no-new-stream assertion there.
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
|
||
[Fact]
|
||
public async Task R1_S1_a_retry_snapshot_slower_than_the_timeout_still_completes_late_on_the_open_stream()
|
||
{
|
||
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 500, ("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.Unavailable, "map-a"); // transient ⇒ retried after the snapshot timeout
|
||
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);
|
||
stream.SnapshotRecords("map-a", Record(Key("y"), 3));
|
||
// The retry's deadline passes with the listing half delivered …
|
||
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.Unavailable);
|
||
// … and the rest arrives before the next retry (2× the timeout later): the late completion is taken.
|
||
stream.SnapshotRecords("map-a", 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);
|
||
stream.AddsOf("map-a").ShouldBe(1, "no restart was needed");
|
||
}
|
||
|
||
[Fact]
|
||
public async Task R1_S2_a_late_ack_of_a_superseded_retry_removes_the_orphaned_origin_item_and_the_mapping_recovers()
|
||
{
|
||
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.Unavailable, "map-a");
|
||
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); // retry #1: its ack is slow
|
||
await f.WaitAsync(() => stream.AddsOf("map-a") == 2); // #1 declared timed out; retry #2 replaced its command
|
||
var orphan = stream.AckAddAt("map-a", 0); // the origin did open #1 — acked late
|
||
await f.WaitAsync(() => { lock (stream.Removed) return stream.Removed.Contains(orphan); });
|
||
stream.AckAdd("map-a", DataItemStatus.InvalidArgument); // #2 reached the origin while #1 was open: duplicate
|
||
await f.WaitAsync(() => stream.AddsOf("map-a") == 3); // the orphan is gone, so the next re-add is accepted
|
||
stream.AckAdd("map-a");
|
||
stream.Begin("map-a", total: 1);
|
||
stream.SnapshotRecords("map-a", Record(Key("y"), 3));
|
||
stream.Complete("map-a");
|
||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")));
|
||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
|
||
f.Connections.Streams.Reader.TryPeek(out _).ShouldBeFalse("recovered on the open stream");
|
||
}
|
||
|
||
[Fact]
|
||
public async Task R1_S2_consecutive_InvalidArgument_refusals_of_in_stream_re_adds_end_the_stream_as_a_backstop()
|
||
{
|
||
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 200, ("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.Unavailable, "map-a");
|
||
stream.Begin("map-b", total: 1);
|
||
stream.SnapshotRecords("map-b", Record(Key("x"), 3));
|
||
stream.Complete("map-b");
|
||
for (var i = 1; i < ProjectedConditionAccess.MaxInvalidArgumentRefusals; i++)
|
||
{
|
||
await f.WaitAsync(() => stream.AddsOf("map-a") == i);
|
||
stream.AckAdd("map-a", DataItemStatus.InvalidArgument);
|
||
}
|
||
await f.WaitAsync(() => stream.AddsOf("map-a") == ProjectedConditionAccess.MaxInvalidArgumentRefusals);
|
||
f.Connections.Streams.Reader.TryPeek(out _).ShouldBeFalse("fewer refusals keep the stream");
|
||
stream.AckAdd("map-a", DataItemStatus.InvalidArgument);
|
||
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("the origin holds an item we lost: only a new stream clears it");
|
||
}
|
||
|
||
[Fact]
|
||
public async Task R1_S3_another_mappings_held_stale_keys_are_not_overlap_for_a_mapping_that_never_listed_them()
|
||
{
|
||
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-c", DataRealm.Raw, 10));
|
||
foreach (var m in f.Mappings.Current) { m.Mapping.ConditionSnapshotTimeoutMilliseconds = 300; m.Mapping.ConditionStaleTimeoutMilliseconds = 60_000; }
|
||
using var demand = f.Access.AcquireEventDemand(null);
|
||
var first = await CompleteFirstAsync(f, ("map-a", []), ("map-c", [Record(Key("x"), 3), Record(Key("y"), 3)]));
|
||
await f.WaitAsync(() => f.Sink.Live.Count == 2);
|
||
first.End();
|
||
|
||
var second = await f.NextStreamAsync();
|
||
second.Ack(DataItemStatus.Denied, "map-c"); // map-c's x, y are held stale (unknown ≠ gone)
|
||
// map-a never listed x or y: its 2 new keys + the 2 held would be 4 on a 3-condition node.
|
||
second.Begin("map-a", total: 2);
|
||
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.ConditionCapacity);
|
||
f.Sink.Live.Count.ShouldBe(2);
|
||
f.Sink.Removed.ShouldBeEmpty("map-c is unknown: nothing is removed (T2)");
|
||
}
|
||
|
||
[Fact]
|
||
public async Task R1_S4_SourceName_stays_on_the_deployed_primary_while_it_is_unavailable_and_moves_only_when_its_listing_changes()
|
||
{
|
||
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-r", DataRealm.Raw, 10), ("map-u", DataRealm.Uns, 10));
|
||
foreach (var m in f.Mappings.Current) m.Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
|
||
using var demand = f.Access.AcquireEventDemand(null);
|
||
var first = await CompleteFirstAsync(f, ("map-r", [Record(Key("x"), 3)]), ("map-u", [Record(Key("x"), 3, placement: f.UnsPlacement)]));
|
||
await f.WaitAsync(() => f.Sink.Applied.Count >= 1);
|
||
var rawName = f.Sink.Applied.Last().SourceName;
|
||
rawName.ShouldStartWith("Plant/map-r/");
|
||
first.End();
|
||
|
||
var second = await f.NextStreamAsync();
|
||
second.Ack(DataItemStatus.Denied, "map-r"); // a runtime refusal, not a deployed-config change
|
||
second.Begin("map-u", total: 1);
|
||
second.SnapshotRecords("map-u", Record(Key("x"), 4, placement: f.UnsPlacement));
|
||
second.Complete("map-u");
|
||
await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Version == 4));
|
||
var held = f.Sink.Applied.Last(u => u.State.Version == 4);
|
||
held.Placements.Select(p => p.MappingId).ShouldBe(["map-u"], "only the contributing placement is materialised");
|
||
held.SourceName.ShouldBe(rawName, "SourceName does not follow a runtime refusal");
|
||
second.End();
|
||
|
||
// Positive control: once the Raw mapping is known again and no longer lists x, SourceName moves.
|
||
var third = await f.NextStreamAsync();
|
||
third.Ack();
|
||
third.Begin("map-r", total: 0);
|
||
third.Complete("map-r");
|
||
third.Begin("map-u", total: 1);
|
||
third.SnapshotRecords("map-u", Record(Key("x"), 5, placement: f.UnsPlacement));
|
||
third.Complete("map-u");
|
||
await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Version == 5));
|
||
f.Sink.Applied.Last(u => u.State.Version == 5).SourceName.ShouldStartWith("Plant/map-u/");
|
||
}
|
||
|
||
[Fact]
|
||
public async Task R1_NIT_consumer_resyncs_count_streams_that_opened_not_failed_connect_attempts()
|
||
{
|
||
var options = Fixture.DefaultOptions with { MaxReconnectDelay = TimeSpan.FromMilliseconds(100) };
|
||
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10));
|
||
f.Connections.MetadataFails.Add(0); // every attempt ends before a stream opens
|
||
using (f.Access.AcquireEventDemand(null))
|
||
{
|
||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) >= 4);
|
||
f.Access.Diagnostics.CaptureConsumer(Connection)!.Resyncs.ShouldBe(0);
|
||
}
|
||
|
||
await using var g = new Fixture(("map-a", DataRealm.Raw, 10)); // positive control: an opened stream that ends counts
|
||
using var demand = g.Access.AcquireEventDemand(null);
|
||
var stream = await CompleteFirstAsync(g, ("map-a", [Record(Key("x"), 3)]));
|
||
stream.End();
|
||
await g.WaitAsync(() => g.Access.Diagnostics.CaptureConsumer(Connection)!.Resyncs >= 1);
|
||
}
|
||
|
||
/// <summary>
|
||
/// A4 F1–F3 (live gate): every deploy begins a catalog attempt whose mapping set is EMPTY until it completes. The consumer
|
||
/// used to treat that as "connection removed": every imported condition was removed and re-created after the deploy (a
|
||
/// fresh node ⇒ a phantom event per condition, an origin transition delivered twice, new EventIds with the old ones
|
||
/// BadEventIdUnknown). The conditions are now held across the attempt and handed to the next runner; only a SETTLED set
|
||
/// without the connection removes them.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task F1_a_deploys_empty_suspended_mapping_set_holds_the_conditions_and_only_a_settled_set_without_the_connection_removes_them()
|
||
{
|
||
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);
|
||
var placements = f.Mappings.Current.ToList();
|
||
var list = (List<ProjectedMappingPlacement>)f.Mappings.Current;
|
||
|
||
// A deploy: AttemptBegan (empty + suspended) … AttemptCompleted (the same placements, settled).
|
||
list.Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
|
||
await f.WaitAsync(() => !f.Access.IsRunning(Connection));
|
||
list.AddRange(placements); f.Mappings.Suspended = false; f.Mappings.Raise();
|
||
var stream = await f.NextStreamAsync();
|
||
stream.Ack();
|
||
stream.Begin("map-a", 1);
|
||
stream.SnapshotRecords("map-a", Record(Key("x"), 3));
|
||
stream.Complete("map-a");
|
||
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 1 && f.Sink.Applied.Count >= 2); // positive control: re-snapshot applied
|
||
f.Sink.Removed.ShouldBeEmpty("a deploy's undecided empty set is not a removal");
|
||
f.Sink.Live.ShouldBe([Key("x")]);
|
||
|
||
// A deploy whose settled set no longer has the connection DOES remove (after the hold).
|
||
list.Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
|
||
await f.WaitAsync(() => !f.Access.IsRunning(Connection));
|
||
// Review r2 NIT: must-arrive control. A removal would run as a continuation of the held runner's stop; the hold's stale
|
||
// mark (100 ms stale timeout) is chained AFTER that stop, so once it arrived any removal would already have run.
|
||
await f.WaitAsync(() => f.Sink.Stale.Contains(Connection));
|
||
f.Sink.Removed.ShouldBeEmpty();
|
||
f.Mappings.Suspended = false; f.Mappings.Raise();
|
||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||
f.Sink.Live.ShouldBeEmpty();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task R1_NIT_consumer_counters_of_a_removed_connection_are_pruned()
|
||
{
|
||
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10));
|
||
using var demand = f.Access.AcquireEventDemand(null);
|
||
var stream = await f.NextStreamAsync();
|
||
stream.Ack(DataItemStatus.Denied, "map-a");
|
||
await f.WaitAsync(() => f.Sink.RefreshRequired >= 1);
|
||
f.Access.Diagnostics.HasConsumerCounters(Connection).ShouldBeTrue();
|
||
((List<ProjectedMappingPlacement>)f.Mappings.Current).Clear();
|
||
f.Mappings.Raise();
|
||
f.Access.Diagnostics.HasConsumerCounters(Connection).ShouldBeFalse();
|
||
}
|
||
|
||
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
// A4 review round 2 (a4-review-round2.md): S1–S4 and NITs
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
|
||
/// <summary>The real deploy switch: a <see cref="LocalCatalogCoordinator"/> + <see cref="ProjectedMappingDeploymentRuntime"/>
|
||
/// publishing one condition-bearing mapping "map" on connection "link".</summary>
|
||
private sealed class DeployRig : IDisposable
|
||
{
|
||
private readonly RemoteNamespaceResolver _resolver;
|
||
private readonly byte[] _artifact = GrpcDataCatalogStagingTests.Artifact();
|
||
public const string Link = "link";
|
||
public LocalCatalogCoordinator Coordinator { get; }
|
||
public ProjectedMappingDeploymentRuntime Runtime { get; }
|
||
public RemoteNamespaceMapping Mapping { get; } = GrpcDataCatalogStagingTests.TestMapping();
|
||
|
||
public DeployRig()
|
||
{
|
||
var authority = new DataPlaneAuthorityState();
|
||
Coordinator = GrpcDataCatalogStagingTests.NewCoordinator(authority, new CatalogActivation());
|
||
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
|
||
_resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
|
||
new BrowseContinuationRegistry(8, TimeProvider.System), new GrpcDataCatalogStagingTests.MissingProjectionSource(), policy, 8, 2);
|
||
Runtime = new ProjectedMappingDeploymentRuntime(Coordinator, _resolver);
|
||
Mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe;
|
||
Complete(Begin(), success: true).ShouldBeTrue();
|
||
}
|
||
|
||
/// <summary>AttemptBegan: the published set goes empty and undecided.</summary>
|
||
public CatalogAttempt Begin() => GrpcDataCatalogStagingTests.Prepare(Coordinator, _artifact);
|
||
|
||
/// <summary>AttemptCompleted; <paramref name="success"/> false = a failed/degraded apply (catalog not activated).</summary>
|
||
public bool Complete(CatalogAttempt attempt, bool success)
|
||
{
|
||
Runtime.Stage(attempt, [Mapping], [GrpcDataCatalogStagingTests.TestConnection()]);
|
||
return Coordinator.Complete(attempt, success);
|
||
}
|
||
|
||
public void Dispose() { Runtime.Dispose(); _resolver.Dispose(); }
|
||
}
|
||
|
||
private static async Task<FakeStream> SnapshotAsync(Fixture f, string connection, int barriers, params DataConditionState[] records)
|
||
{
|
||
var stream = await f.NextStreamAsync();
|
||
stream.Ack();
|
||
stream.Begin("map", records.Length);
|
||
stream.SnapshotRecords("map", records);
|
||
stream.Complete("map");
|
||
await f.WaitAsync(() => f.Access.BarriersCompleted(connection) >= barriers);
|
||
return stream;
|
||
}
|
||
|
||
/// <summary>
|
||
/// S1: <c>AttemptCompleted</c> clears the undecided flag and THEN notifies. A demand acquired in between (a client
|
||
/// creating an event item) used to read the runtime's live flag ("settled") next to the adapter's still-empty copy of
|
||
/// the placements, and released — removed — every held condition (F1–F3 again). The window is opened deterministically:
|
||
/// a <c>Changed</c> handler registered BEFORE the adapter runs inside it. Also S3: the takeover's first barrier sends
|
||
/// exactly one RefreshRequired.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task R2_S1_a_demand_acquired_between_the_settle_and_its_notification_keeps_the_held_set()
|
||
{
|
||
using var rig = new DeployRig();
|
||
ProjectedConditionAccess? access = null;
|
||
IDisposable? windowDemand = null;
|
||
var armed = false;
|
||
rig.Runtime.Changed += placements =>
|
||
{
|
||
// Runs after _gate is released and before the adapter has seen this transition.
|
||
if (armed && placements.Count > 0) windowDemand = access!.AcquireEventDemand(null);
|
||
};
|
||
await using var f = new Fixture(new DeployedConditionMappings(rig.Runtime));
|
||
access = f.Access;
|
||
using var demand = f.Access.AcquireEventDemand(null);
|
||
await SnapshotAsync(f, DeployRig.Link, 1, Record(Key("x"), 3));
|
||
await f.WaitAsync(() => f.Sink.Live.Count == 1);
|
||
f.Sink.RefreshRequired.ShouldBe(0, "a complete first barrier tells nobody to refresh");
|
||
|
||
var attempt = rig.Begin();
|
||
await f.WaitAsync(() => !f.Access.IsRunning(DeployRig.Link));
|
||
armed = true;
|
||
rig.Complete(attempt, success: true).ShouldBeTrue();
|
||
using var _ = windowDemand.ShouldNotBeNull("the window demand ran");
|
||
|
||
await SnapshotAsync(f, DeployRig.Link, 1, Record(Key("x"), 3)); // the takeover re-snapshot
|
||
await f.WaitAsync(() => f.Sink.Applied.Count >= 2); // positive control: the re-snapshot applied
|
||
f.Sink.Removed.ShouldBeEmpty("a demand inside the settle window must not release the held set");
|
||
f.Sink.Live.ShouldBe([Key("x")]);
|
||
await f.WaitAsync(() => f.Sink.RefreshRequired >= 1);
|
||
f.Sink.RefreshRequired.ShouldBe(1, "S3: one RefreshRequired at the takeover's first barrier");
|
||
}
|
||
|
||
/// <summary>
|
||
/// S2: a deploy that completes UNSUCCESSFULLY (failed or degraded apply ⇒ catalog not activated) settles the set as
|
||
/// empty: the held conditions are released at once — not held, invisible and charged, until some later good deploy.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task R2_S2_an_unsuccessful_deploy_completion_releases_the_held_conditions()
|
||
{
|
||
using var rig = new DeployRig();
|
||
await using var f = new Fixture(new DeployedConditionMappings(rig.Runtime));
|
||
using var demand = f.Access.AcquireEventDemand(null);
|
||
await SnapshotAsync(f, DeployRig.Link, 1, Record(Key("x"), 3));
|
||
await f.WaitAsync(() => f.Sink.Live.Count == 1);
|
||
|
||
var attempt = rig.Begin();
|
||
await f.WaitAsync(() => !f.Access.IsRunning(DeployRig.Link));
|
||
f.Access.Diagnostics.CaptureConsumer(DeployRig.Link)!.StreamState.ShouldBe("held");
|
||
f.Access.ChargedConditions.ShouldBe(1, "held conditions exist, so they stay charged");
|
||
rig.Complete(attempt, success: false).ShouldBeFalse();
|
||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||
f.Sink.Live.ShouldBeEmpty();
|
||
await f.WaitAsync(() => f.Access.ChargedConditions == 0);
|
||
f.Access.Diagnostics.CaptureConsumer(DeployRig.Link).ShouldBeNull();
|
||
}
|
||
|
||
/// <summary>
|
||
/// S2: an attempt that never completes is bounded — the held conditions go stale (BadNoCommunication, the stream-gap
|
||
/// rule) on the connection's stale timeout, are reported as "held" and stay charged, and are released past MaxHold.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task R2_S2_a_hold_that_never_settles_goes_stale_then_is_released_past_MaxHold()
|
||
{
|
||
await using var f = new Fixture(Fixture.DefaultOptions with { MaxHold = TimeSpan.FromMilliseconds(600) }, ("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);
|
||
|
||
((List<ProjectedMappingPlacement>)f.Mappings.Current).Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
|
||
await f.WaitAsync(() => !f.Access.IsRunning(Connection));
|
||
var held = f.Access.Diagnostics.CaptureConsumer(Connection)!;
|
||
held.StreamState.ShouldBe("held");
|
||
held.Materialised.ShouldBe(1);
|
||
f.Access.ChargedConditions.ShouldBe(1);
|
||
await f.WaitAsync(() => f.Sink.Stale.Contains(Connection)); // stale timeout 100 ms
|
||
f.Sink.Removed.ShouldBeEmpty("stale, not removed, before MaxHold");
|
||
|
||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||
f.Sink.Live.ShouldBeEmpty();
|
||
await f.WaitAsync(() => f.Access.ChargedConditions == 0);
|
||
f.Access.Diagnostics.CaptureConsumer(Connection).ShouldBeNull();
|
||
}
|
||
|
||
/// <summary>S3: the takeover's RefreshRequired is sent once — a later stream end with a complete re-snapshot sends none.</summary>
|
||
[Fact]
|
||
public async Task R2_S3_a_runner_taking_over_a_held_set_sends_RefreshRequired_once_at_its_first_barrier()
|
||
{
|
||
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)]));
|
||
var list = (List<ProjectedMappingPlacement>)f.Mappings.Current;
|
||
var placements = list.ToList();
|
||
list.Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
|
||
await f.WaitAsync(() => !f.Access.IsRunning(Connection));
|
||
list.AddRange(placements); f.Mappings.Suspended = false; f.Mappings.Raise();
|
||
var stream = await f.NextStreamAsync();
|
||
stream.Ack();
|
||
f.Sink.RefreshRequired.ShouldBe(0, "not before the barrier");
|
||
stream.Begin("map-a", 1); stream.SnapshotRecords("map-a", Record(Key("x"), 3)); stream.Complete("map-a");
|
||
await f.WaitAsync(() => f.Sink.RefreshRequired == 1);
|
||
var applied = f.Sink.Applied.Count;
|
||
|
||
stream.End(); // a later resync of the same runner: complete barrier ⇒ no RefreshRequired
|
||
var next = await f.NextStreamAsync();
|
||
next.Ack(); next.Begin("map-a", 1); next.SnapshotRecords("map-a", Record(Key("x"), 3)); next.Complete("map-a");
|
||
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 2 && f.Sink.Applied.Count > applied); // must-arrive
|
||
f.Sink.RefreshRequired.ShouldBe(1);
|
||
f.Sink.Removed.ShouldBeEmpty();
|
||
}
|
||
|
||
/// <summary>Review r2 NIT: demand lingering out WHILE a set is held (the deploy still undecided) releases it.</summary>
|
||
[Fact]
|
||
public async Task R2_NIT_linger_expiry_while_held_releases_the_held_conditions()
|
||
{
|
||
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);
|
||
((List<ProjectedMappingPlacement>)f.Mappings.Current).Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
|
||
await f.WaitAsync(() => !f.Access.IsRunning(Connection));
|
||
f.Sink.Removed.ShouldBeEmpty();
|
||
demand!.Dispose(); // linger 200 ms; the set stays undecided throughout
|
||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||
f.Sink.Live.ShouldBeEmpty();
|
||
await f.WaitAsync(() => f.Access.ChargedConditions == 0);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
// Follow-ups #933 / #934 (A4 review)
|
||
// ---------------------------------------------------------------------------------------------------------------------
|
||
|
||
[Fact]
|
||
public async Task Issue933_a_key_held_for_a_durably_denied_mapping_is_removed_past_MaxUnknownHold_not_kept_forever()
|
||
{
|
||
var hold = TimeSpan.FromSeconds(1.5);
|
||
await using var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold },
|
||
("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-b"); // durable: retried only on the 5 min long timer
|
||
stream.Begin("map-a", total: 1);
|
||
stream.Records("map-a", Record(Key("x"), 3));
|
||
stream.Complete("map-a");
|
||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||
|
||
// map-a retires x; map-b is unknown, so x is held stale (T2) — the stale mark is the must-arrive control. Review r1 N5:
|
||
// the runner's hold clock starts after this instant, so it is a true lower bound (no tolerance for a slow poll).
|
||
var beforeHeld = DateTime.UtcNow;
|
||
stream.Records("map-a", Record(Key("x"), 4, removed: true));
|
||
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
||
f.Sink.Removed.ShouldBeEmpty("within the bound an unknown mapping still holds the key");
|
||
|
||
// …and past the bound it is removed (+ RefreshRequired at the sink), on the open stream, with no frame to prompt it.
|
||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||
(DateTime.UtcNow - beforeHeld).ShouldBeGreaterThanOrEqualTo(hold, "not before MaxUnknownHold");
|
||
f.Sink.Removed.Count(k => k == Key("x")).ShouldBe(1);
|
||
f.Sink.Live.ShouldNotContain(Key("x"));
|
||
f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Unavailable, "still unknown");
|
||
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(200))).ShouldBeNull("the stream is kept");
|
||
|
||
// A later listing re-creates it (the removal was a removal, not a verdict on the condition's state).
|
||
stream.Records("map-a", Record(Key("x"), 5, message: "back"));
|
||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Issue934_a_slow_in_stream_root_re_resolve_does_not_stall_frames_of_the_other_mappings()
|
||
{
|
||
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||
f.Connections.MetadataFails.Add(0); // map-a's root fails at the open: Unavailable, its item is not opened
|
||
f.Connections.MetadataBlockCall = 2; // …and its in-stream re-resolve (the 2nd metadata call) hangs until released
|
||
using var demand = f.Access.AcquireEventDemand(null);
|
||
var stream = await f.NextStreamAsync();
|
||
stream.Mappings.ShouldBe(["map-b"]);
|
||
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.Live.Contains(Key("x")));
|
||
f.Connections.MetadataFails.Clear();
|
||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) == 2); // the re-resolve is in flight
|
||
|
||
// The frame loop is not blocked by it: map-b's delta is applied while the metadata call is still pending.
|
||
stream.Records("map-b", Record(Key("y"), 3));
|
||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")));
|
||
f.Connections.MetadataRelease.Task.IsCompleted.ShouldBeFalse();
|
||
stream.AddsOf("map-a").ShouldBe(0, "not re-added before its root resolved");
|
||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable, "unknown while resolving (T2)");
|
||
|
||
// Positive control: once the answer arrives it is applied on the loop and the item is re-added — exactly once.
|
||
f.Connections.MetadataRelease.SetResult();
|
||
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);
|
||
stream.AddsOf("map-a").ShouldBe(1);
|
||
Volatile.Read(ref f.Connections.MetadataCalls).ShouldBe(2);
|
||
}
|
||
|
||
private static Fixture HoldFixture(int timeoutMs, TimeSpan hold, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
|
||
{
|
||
var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold }, mappings);
|
||
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs;
|
||
return f;
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Issue933_r1_S1_a_key_its_own_transiently_unknown_mapping_listed_is_held_past_the_bound_until_that_mapping_is_definitively_refused()
|
||
{
|
||
var hold = TimeSpan.FromSeconds(1);
|
||
await using var f = HoldFixture(300, hold, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||
using var demand = f.Access.AcquireEventDemand(null);
|
||
var first = await f.NextStreamAsync();
|
||
first.Ack();
|
||
first.Begin("map-a", total: 0);
|
||
first.Complete("map-a");
|
||
first.Begin("map-b", total: 1);
|
||
first.SnapshotRecords("map-b", Record(Key("x"), 3));
|
||
first.Complete("map-b");
|
||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||
|
||
// map-b listed x; on the next stream its item is refused TRANSIENTLY (Unavailable) and its retries keep timing out.
|
||
first.End();
|
||
var second = await f.NextStreamAsync();
|
||
second.Ack(DataItemStatus.Unavailable, "map-b");
|
||
second.Begin("map-a", total: 0);
|
||
second.Complete("map-a");
|
||
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
||
await Task.Delay(hold * 2.5, TestContext.Current.CancellationToken);
|
||
f.Sink.Removed.ShouldNotContain(Key("x"), "map-b's own key: its origin may still list it (T2) — no bound while map-b is transient");
|
||
f.Sink.Live.ShouldContain(Key("x"));
|
||
|
||
// Positive control: map-b's retry is refused DEFINITIVELY — now the bound runs, from then.
|
||
// Ack a FRESH re-add at once (its command stays current until the next re-add, ≥ 600 ms later on the backoff).
|
||
var adds = second.AddsOf("map-b");
|
||
await f.WaitAsync(() => second.AddsOf("map-b") > adds);
|
||
var beforeDefinitive = DateTime.UtcNow;
|
||
second.AckAdd("map-b", DataItemStatus.Denied);
|
||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||
(DateTime.UtcNow - beforeDefinitive).ShouldBeGreaterThanOrEqualTo(hold, "the clock starts at the definitive refusal");
|
||
f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Issue933_r1_S2_time_with_no_stream_past_its_barrier_does_not_count_toward_MaxUnknownHold()
|
||
{
|
||
var hold = TimeSpan.FromSeconds(1.5);
|
||
await using var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold },
|
||
("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-b"); // definitive: map-a's retired key is bounded
|
||
first.Begin("map-a", total: 1);
|
||
first.Records("map-a", Record(Key("x"), 3));
|
||
first.Complete("map-a");
|
||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||
first.Records("map-a", Record(Key("x"), 4, removed: true));
|
||
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
||
|
||
// The stream ends and the next one sits before its barrier (snapshot slow) for longer than the whole bound.
|
||
first.End();
|
||
var second = await f.NextStreamAsync();
|
||
await Task.Delay(hold * 2, TestContext.Current.CancellationToken);
|
||
f.Sink.Removed.ShouldBeEmpty("nothing is decided before a barrier");
|
||
second.Ack(DataItemStatus.Denied, "map-b");
|
||
second.Begin("map-a", total: 0);
|
||
second.Complete("map-a");
|
||
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.Complete);
|
||
await Task.Delay(300, TestContext.Current.CancellationToken);
|
||
f.Sink.Removed.ShouldBeEmpty("the outage did not count: x has been held well under the bound while a stream was live");
|
||
|
||
// Positive control: the remaining bound runs out on the live stream.
|
||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(100))).ShouldBeNull();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Issue933_r1_N2_with_no_sink_an_expired_hold_does_not_spin_the_loop()
|
||
{
|
||
var hold = TimeSpan.FromMilliseconds(300);
|
||
await using var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold },
|
||
("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-b");
|
||
stream.Begin("map-a", total: 1);
|
||
stream.Records("map-a", Record(Key("x"), 3));
|
||
stream.Complete("map-a");
|
||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||
stream.Records("map-a", Record(Key("x"), 4, removed: true));
|
||
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
||
f.SinkDetached = true;
|
||
stream.Records("map-a", Record(Key("y"), 1)); // one frame so the loop re-arms its timer without a sink
|
||
await Task.Delay(hold * 2, TestContext.Current.CancellationToken);
|
||
var before = Volatile.Read(ref f.SinkLookups);
|
||
await Task.Delay(500, TestContext.Current.CancellationToken);
|
||
(Volatile.Read(ref f.SinkLookups) - before).ShouldBeLessThan(50, "an expiry that cannot be applied must not re-arm the timer at zero");
|
||
f.SinkDetached = false;
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Issue934_r1_N1_a_root_re_resolve_in_flight_is_cancelled_when_the_stream_ends()
|
||
{
|
||
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||
f.Connections.MetadataFails.Add(0);
|
||
f.Connections.MetadataBlockCall = 2;
|
||
using var demand = f.Access.AcquireEventDemand(null);
|
||
var stream = await f.NextStreamAsync();
|
||
stream.Ack();
|
||
stream.Begin("map-b", total: 0);
|
||
stream.Complete("map-b");
|
||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) == 2); // the re-resolve is in flight
|
||
f.Connections.MetadataCancelled.ShouldBe(0);
|
||
|
||
stream.End(); // a natural end (no consumer cancellation)
|
||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCancelled) == 1);
|
||
f.Connections.MetadataFails.Clear();
|
||
var next = await f.NextStreamAsync(); // positive control: the next stream resolves map-a at its open
|
||
next.Mappings.ShouldBe(["map-a", "map-b"]);
|
||
stream.AddsOf("map-a").ShouldBe(0, "the abandoned answer was never applied");
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Issue934_r1_a_second_failed_in_stream_re_resolve_is_rescheduled_and_a_later_success_re_adds_once()
|
||
{
|
||
await using var f = TimedFixture(200, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||
f.Connections.MetadataFails.Add(0); // map-a's root keeps failing: at the open, and on the first two re-resolves
|
||
using var demand = f.Access.AcquireEventDemand(null);
|
||
var stream = await f.NextStreamAsync();
|
||
stream.Ack();
|
||
stream.Begin("map-b", total: 0);
|
||
stream.Complete("map-b");
|
||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) >= 3);
|
||
stream.AddsOf("map-a").ShouldBe(0);
|
||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
|
||
f.Connections.MetadataFails.Clear();
|
||
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
|
||
stream.AckAdd("map-a");
|
||
stream.Begin("map-a", total: 0);
|
||
stream.Complete("map-a");
|
||
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.Complete);
|
||
stream.AddsOf("map-a").ShouldBe(1);
|
||
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(100))).ShouldBeNull("handled in-stream");
|
||
}
|
||
|
||
[Fact]
|
||
public void Issue933_r1_N3_a_non_positive_MaxUnknownHold_is_refused()
|
||
{
|
||
Should.Throw<ArgumentOutOfRangeException>(() => new Fixture(Fixture.DefaultOptions with { MaxUnknownHold = TimeSpan.Zero }, ("map-a", DataRealm.Raw, 10)));
|
||
}
|
||
|
||
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; }
|
||
/// <summary>#933 review r1 N2: when set, the sink is gone (the access sees null).</summary>
|
||
public volatile bool SinkDetached;
|
||
/// <summary>#933 review r1 N2: how often the access asked for the sink (a spinning loop asks continuously).</summary>
|
||
public int SinkLookups;
|
||
private IProjectedConditionSink? CurrentSink() { Interlocked.Increment(ref SinkLookups); return SinkDetached ? null : Sink; }
|
||
|
||
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, CurrentSink, TimeProvider.System, options, NullLogger.Instance);
|
||
}
|
||
|
||
/// <summary>A4 review r2: over a real mapping source (e.g. <see cref="DeployedConditionMappings"/>); <see cref="Mappings"/> is unset.</summary>
|
||
public Fixture(IProjectedConditionMappings mappings, ProjectedConditionOptions? options = null)
|
||
{
|
||
Grant(NodePermissions.Browse | NodePermissions.Subscribe);
|
||
Mappings = null!;
|
||
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
|
||
Access = new ProjectedConditionAccess(mappings, Connections, policy, CurrentSink, TimeProvider.System, options ?? DefaultOptions, 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();
|
||
/// <summary>A4 F1–F3: a catalog attempt in progress (its Current is the undecided empty set).</summary>
|
||
public bool Suspended { get; set; }
|
||
}
|
||
|
||
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>#934: when set, the metadata call with this 1-based number waits for <see cref="MetadataRelease"/>.</summary>
|
||
public int? MetadataBlockCall;
|
||
public TaskCompletionSource MetadataRelease { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
/// <summary>#934 review r1 N1: blocked metadata calls whose token was cancelled.</summary>
|
||
public int MetadataCancelled;
|
||
/// <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 async Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
|
||
{
|
||
if (Interlocked.Increment(ref owner.MetadataCalls) == owner.MetadataBlockCall)
|
||
{
|
||
try { await owner.MetadataRelease.Task.WaitAsync(cancellationToken); } // #934: a slow origin metadata answer
|
||
catch (OperationCanceledException) { Interlocked.Increment(ref owner.MetadataCancelled); throw; }
|
||
}
|
||
return Answer(request);
|
||
}
|
||
|
||
private IReadOnlyList<DataItemResult<DataMetadata>> Answer(MetadataRequest request) =>
|
||
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;
|
||
|
||
/// <summary>Every command id this stream has accepted (A4 review r1 B1).</summary>
|
||
private readonly HashSet<string> _commandIds = new(StringComparer.Ordinal);
|
||
|
||
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
|
||
{
|
||
// A4 review r1 B1: the real transport refuses a command id already used on the stream (GrpcDataConnection
|
||
// `_usedCommands`, "Command capacity or duplicate command"), and the origin one still pending
|
||
// (DataSubscriptionSession); either ends the consumer's stream. The fake enforces the stricter (transport) rule.
|
||
lock (_commandIds)
|
||
if (!_commandIds.Add(command.CommandId)) throw new InvalidOperationException("Command capacity or duplicate command.");
|
||
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")]));
|
||
}
|
||
|
||
/// <summary>A4 review r1 S2: acks the <paramref name="index"/>-th re-add of <paramref name="mapping"/> (a late ack), Good.</summary>
|
||
public DataItemHandle AckAddAt(string mapping, int index)
|
||
{
|
||
AddSubscriptionItems add;
|
||
lock (Adds) add = Adds.Where(a => a.Items.Any(i => i.ClientItemId == mapping)).ElementAt(index);
|
||
var handle = new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, ++_nextHandle, 1);
|
||
_frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, add.CommandId,
|
||
[new DataSubscriptionItemAck(mapping, DataItemStatus.Good, handle, null, null)]));
|
||
return handle;
|
||
}
|
||
|
||
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));
|
||
}
|
||
}
|