fix(grpc-data): A3a review r1 — buffered in-stream re-snapshots, late completion + stale-on-incomplete + bounded retry, Primary-pinned condition streams, node-wide host-cap ledger, runner hand-over after stop, metadata failure Unavailable; NM: revalidation through the imported gate, demand released first, rebuild unwires, instance-keyed promotion, incremental folder index, verdict TTL + expiry, removal RefreshRequired, chunked refresh/replay, folder-only demand
Runtime tests: B1 multi-frame + capacity re-snapshot, B2 late completion / stale-on-incomplete / refused retry, B4 cross-connection / reverse order / records>total / delta growth, S3/S4 hand-over, S6, deviation 9, S2 IsActive generation; absence assertions now follow must-arrive controls.
This commit is contained in:
+25
-7
@@ -321,10 +321,21 @@ public sealed class ImportedConditionEventWireTests
|
||||
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements) =>
|
||||
caller is not null && Allowed.Contains(caller.Principal);
|
||||
public long AuthorityGeneration => Interlocked.Read(ref Generation);
|
||||
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) =>
|
||||
caller is not null && Allowed.Contains(caller.Principal);
|
||||
/// <summary>Leases currently held (acquired minus released).</summary>
|
||||
public int Outstanding;
|
||||
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller)
|
||||
{
|
||||
Interlocked.Increment(ref Demands);
|
||||
return null;
|
||||
Interlocked.Increment(ref Outstanding);
|
||||
return new Lease(this);
|
||||
}
|
||||
|
||||
private sealed class Lease(FakeConditionAccess owner) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) Interlocked.Decrement(ref owner.Outstanding); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,7 +351,18 @@ public sealed class ImportedConditionEventWireTests
|
||||
|
||||
public static Fixture Install(ServerEventRig rig, string grantedPrincipal)
|
||||
{
|
||||
var nm = rig.Nm;
|
||||
var (anchor, anchorB, device, definition) = Materialise(rig.Nm);
|
||||
var access = new FakeConditionAccess();
|
||||
access.Allowed.Add(grantedPrincipal);
|
||||
rig.Nm.ProjectedConditionAccess = access;
|
||||
return new Fixture { Rig = rig, Access = access, Anchor = anchor, AnchorB = anchorB, DeviceFolder = device, DeviceDefinition = definition };
|
||||
}
|
||||
|
||||
/// <summary>Re-creates the same projected folders (new instances, same NodeIds) — e.g. after a full rebuild.</summary>
|
||||
public void Rematerialise() => Materialise(Rig.Nm);
|
||||
|
||||
private static (NodeId Anchor, NodeId AnchorB, NodeId Device, ProjectedVariableDefinition Definition) Materialise(OtOpcUaNodeManager nm)
|
||||
{
|
||||
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
|
||||
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
|
||||
var rootA = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant");
|
||||
@@ -355,11 +377,7 @@ public sealed class ImportedConditionEventWireTests
|
||||
var definition = new ProjectedVariableDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, devAddress), anchor!.Value,
|
||||
metadata, 1, () => true);
|
||||
nm.TryEnsureProjectedVariable(definition, out var device).ShouldBeTrue();
|
||||
var access = new FakeConditionAccess();
|
||||
access.Allowed.Add(grantedPrincipal);
|
||||
nm.ProjectedConditionAccess = access;
|
||||
return new Fixture { Rig = rig, Access = access, Anchor = anchor.Value, AnchorB = anchorB!.Value, DeviceFolder = device!.Value,
|
||||
DeviceDefinition = definition };
|
||||
return (anchor.Value, anchorB!.Value, device!.Value, definition);
|
||||
}
|
||||
|
||||
/// <summary>Primary: the raw tag under dev1 (map-a); second: the same condition listed directly under the map-a root.</summary>
|
||||
|
||||
+1
@@ -141,6 +141,7 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable
|
||||
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements) => caller is not null && Visible;
|
||||
public long AuthorityGeneration => Generation;
|
||||
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) => null;
|
||||
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => caller is not null && Visible;
|
||||
}
|
||||
|
||||
private sealed class Fixture
|
||||
|
||||
+345
-21
@@ -37,13 +37,13 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
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.Begin("map-b", total: 2);
|
||||
stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3));
|
||||
f.Sink.Applied.ShouldBeEmpty();
|
||||
stream.Complete("map-b");
|
||||
await f.WaitAsync(() => f.Sink.Applied.Count == 2);
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
|
||||
@@ -73,9 +73,9 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
var cappedStream = await capped.NextStreamAsync();
|
||||
cappedStream.Ack();
|
||||
cappedStream.Begin("map-a", total: 2000);
|
||||
await capped.WaitAsync(() => cappedStream.Removed.Count == 1);
|
||||
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();
|
||||
capped.Sink.Applied.ShouldBeEmpty("the barrier (the positive control) passed with nothing to materialise");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -100,10 +100,12 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
[Fact]
|
||||
public async Task A_stream_end_re_snapshots_without_removing_and_only_a_complete_re_snapshot_removes_staleness_in_between()
|
||||
{
|
||||
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
|
||||
// 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");
|
||||
@@ -116,6 +118,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
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);
|
||||
@@ -194,6 +198,269 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
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);
|
||||
f.Sink.RefreshRequired.ShouldBeGreaterThan(refreshes, "clients are told the removal happened (§5.2)");
|
||||
}
|
||||
|
||||
private static Fixture TimedFixture(int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
|
||||
{
|
||||
var f = new Fixture(mappings);
|
||||
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs;
|
||||
return f;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task B2_a_snapshot_completing_after_the_timeout_is_merged_late_and_the_stream_is_kept()
|
||||
{
|
||||
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Ack();
|
||||
stream.Begin("map-b", total: 1);
|
||||
stream.Records("map-b", Record(Key("x"), 3));
|
||||
stream.Complete("map-b");
|
||||
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
|
||||
|
||||
stream.Begin("map-a", total: 1); // 2,000 conditions arriving 1 s late, in miniature
|
||||
stream.SnapshotRecords("map-a", Record(Key("w"), 3));
|
||||
stream.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("w")));
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
|
||||
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(900))).ShouldBeNull("a late completion cancels the retry");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task B2_an_incomplete_barrier_marks_the_incomplete_mappings_materialised_keys_BadNoCommunication_never_removed()
|
||||
{
|
||||
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]), ("map-b", [Record(Key("y"), 3)]));
|
||||
await f.WaitAsync(() => f.Sink.Live.Count == 2);
|
||||
first.End();
|
||||
|
||||
var second = await f.NextStreamAsync();
|
||||
second.Ack();
|
||||
second.Begin("map-b", total: 1);
|
||||
second.SnapshotRecords("map-b", Record(Key("y"), 4));
|
||||
second.Complete("map-b"); // map-a never answers: the barrier passes at the timeout
|
||||
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
||||
f.Sink.Removed.ShouldBeEmpty("unknown is not gone");
|
||||
f.Sink.StaleKeys.ShouldNotContain(Key("y"));
|
||||
f.Sink.RefreshRequired.ShouldBeGreaterThanOrEqualTo(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task B2_S7_a_refused_item_is_an_incomplete_barrier_RefreshRequired_and_the_stream_is_retried_after_a_bounded_wait()
|
||||
{
|
||||
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Ack(refused: "map-a"); // e.g. a Secondary that advertises but refuses (A2 N7)
|
||||
stream.Begin("map-b", total: 1);
|
||||
stream.Records("map-b", Record(Key("x"), 3));
|
||||
stream.Complete("map-b");
|
||||
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
|
||||
f.Sink.RefreshRequired.ShouldBe(1, "S7: an incomplete barrier from a non-Good ack also requires refresh");
|
||||
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("B2: an Unavailable mapping ends the stream; a new one retries it");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Deviation9_a_condition_stream_served_by_a_Secondary_is_dropped_and_reopened_on_the_Primary()
|
||||
{
|
||||
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
|
||||
f.Connections.Roles.Enqueue("Secondary");
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var secondary = await f.NextStreamAsync();
|
||||
var primary = await f.NextStreamAsync();
|
||||
secondary.Disposed.ShouldBeTrue("never opened items on a Secondary");
|
||||
f.Connections.PrimarySubscribes.ShouldBeGreaterThanOrEqualTo(2, "the Primary-only open is asked for");
|
||||
primary.Ack();
|
||||
primary.Begin("map-a", 1);
|
||||
primary.SnapshotRecords("map-a", Record(Key("x"), 3));
|
||||
primary.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task S6_a_root_whose_metadata_fails_is_Unavailable_and_its_item_is_not_opened()
|
||||
{
|
||||
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||||
f.Connections.MetadataFails.Add(0);
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Mappings.ShouldBe(["map-b"]);
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task B4_the_host_caps_are_node_wide_across_connections()
|
||||
{
|
||||
var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50));
|
||||
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10, "conn-a"), ("map-b", DataRealm.Raw, 10, "conn-b"));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var streams = new[] { await f.NextStreamAsync(), await f.NextStreamAsync() };
|
||||
foreach (var stream in streams)
|
||||
{
|
||||
var mapping = stream.Mappings.Single();
|
||||
stream.Ack();
|
||||
stream.Begin(mapping, 2);
|
||||
stream.SnapshotRecords(mapping, Record(Key(mapping + "1"), 3), Record(Key(mapping + "2"), 3));
|
||||
stream.Complete(mapping);
|
||||
}
|
||||
await f.WaitAsync(() => f.Access.BarriersCompleted("conn-a") == 1 && f.Access.BarriersCompleted("conn-b") == 1);
|
||||
streams.Sum(x => x.Removed.Count).ShouldBe(1, "two connections of 2 cannot both fit a 3-condition node cap");
|
||||
f.Sink.Live.Count.ShouldBe(2);
|
||||
f.Access.ChargedConditions.ShouldBeLessThanOrEqualTo(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task B4_admission_is_order_independent_a_later_ordered_begin_arriving_first_still_counts()
|
||||
{
|
||||
var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50));
|
||||
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Ack();
|
||||
stream.Begin("map-b", 2);
|
||||
stream.Begin("map-a", 2);
|
||||
await f.WaitAsync(() => stream.Removed.Count == 1);
|
||||
stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the second begin is decided against the first one's claim");
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task B4_records_past_the_snapshot_total_reset_the_mapping_to_ConditionCapacity_before_materialising()
|
||||
{
|
||||
await using var f = new Fixture(("map-a", DataRealm.Raw, 100));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Ack();
|
||||
stream.Begin("map-a", total: 1);
|
||||
stream.SnapshotRecords("map-a", Enumerable.Range(0, 50).Select(i => Record(Key("k" + i), 3)).ToArray());
|
||||
stream.Complete("map-a");
|
||||
await f.WaitAsync(() => stream.Removed.Count == 1 && f.Access.BarriersCompleted(Connection) == 1);
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
|
||||
f.Sink.Applied.ShouldBeEmpty("an origin claiming total 1 cannot materialise 50 (the barrier is the positive control)");
|
||||
f.Access.ChargedConditions.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task B4_post_snapshot_delta_growth_past_MaxConditions_resets_the_mapping_and_removes_its_conditions()
|
||||
{
|
||||
await using var f = new Fixture(("map-a", DataRealm.Raw, 2));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
|
||||
await f.WaitAsync(() => f.Sink.Live.Count == 1);
|
||||
stream.Records("map-a", Record(Key("y"), 3), Record(Key("z"), 3));
|
||||
await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Contains(Key("x")));
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
|
||||
f.Sink.Live.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task S2_an_authority_deactivation_moves_the_authority_generation_so_cached_verdicts_are_re_proved()
|
||||
{
|
||||
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
|
||||
var before = f.Access.AuthorityGeneration;
|
||||
((ActiveAuthority)f.Mappings.Current[0].Authority).Active = false; // no deploy, no epoch change
|
||||
f.Access.AuthorityGeneration.ShouldNotBe(before);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task S3_a_new_runner_waits_for_the_old_runners_removal_so_a_re_materialised_key_survives()
|
||||
{
|
||||
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
|
||||
var demand = f.Access.AcquireEventDemand(null)!;
|
||||
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
|
||||
await f.WaitAsync(() => f.Sink.Live.Count == 1);
|
||||
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
f.Sink.RemovalGate = gate; // hold the old runner's removal open
|
||||
demand.Dispose();
|
||||
await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired; its removal is now blocked in the sink
|
||||
using var again = f.Access.AcquireEventDemand(null);
|
||||
_ = Task.Delay(400, TestContext.Current.CancellationToken).ContinueWith(_ => gate.TrySetResult(), TaskScheduler.Default);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Ack();
|
||||
stream.Begin("map-a", 1);
|
||||
stream.SnapshotRecords("map-a", Record(Key("x"), 4));
|
||||
stream.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.Removed.Count == 1 && f.Sink.Applied.Count == 2);
|
||||
f.Sink.Live.ShouldContain(Key("x"), "the old runner's removal must not land after the new runner materialised the key");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task S4_a_mapping_change_hands_the_materialised_set_over_after_the_old_loop_stopped()
|
||||
{
|
||||
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
|
||||
await f.WaitAsync(() => f.Sink.Live.Count == 1);
|
||||
f.Mappings.Current[0].Mapping.MaxConditions = 11; // a changed signature ⇒ a new runner, a new stream
|
||||
f.Mappings.Raise();
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Ack();
|
||||
stream.Begin("map-a", 1);
|
||||
stream.SnapshotRecords("map-a", Record(Key("y"), 3));
|
||||
stream.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||||
f.Sink.Live.ShouldBe([Key("y")], "x was handed over (not orphaned) and the new complete set removed it");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
internal static string Key(string seed) =>
|
||||
@@ -223,12 +490,18 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
public ProjectedConditionAccess Access { get; }
|
||||
|
||||
public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
|
||||
: this(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)), 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)).ToList());
|
||||
Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions, m.Connection)).ToList());
|
||||
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
|
||||
Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance);
|
||||
}
|
||||
@@ -242,11 +515,11 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
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)
|
||||
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,
|
||||
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",
|
||||
@@ -261,6 +534,15 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
|
||||
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);
|
||||
@@ -278,7 +560,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
{
|
||||
public long CatalogEpoch => 1;
|
||||
public long AuthorityEpoch => 1;
|
||||
public bool IsActive => true;
|
||||
public bool Active { get; set; } = true;
|
||||
public bool IsActive => Active;
|
||||
}
|
||||
|
||||
internal sealed class FakeMappings(List<ProjectedMappingPlacement> current) : IProjectedConditionMappings
|
||||
@@ -294,20 +577,40 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
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);
|
||||
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates) { lock (_gate) _applied.AddRange(updates); }
|
||||
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys) { lock (_gate) _removed.AddRange(conditionKeys); }
|
||||
/// <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>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)));
|
||||
|
||||
@@ -319,29 +622,42 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeConnection(FakeConnections owner) : IDataConnection
|
||||
private sealed class FakeConnection(FakeConnections owner) : IDataConnection, IDataPrimarySubscriptionSource
|
||||
{
|
||||
public Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref owner.PrimarySubscribes);
|
||||
return SubscribeAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null);
|
||||
public TimeProvider Clock => TimeProvider.System;
|
||||
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select(v => new DataItemResult<DataMetadata>("0", DataItemStatus.Good,
|
||||
new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false,
|
||||
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
|
||||
? new DataItemResult<DataMetadata>("0", DataItemStatus.Unavailable, null, null)
|
||||
: new DataItemResult<DataMetadata>("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false,
|
||||
DataOperations.Browse, 1, null, null, false), null)).ToArray());
|
||||
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var stream = new FakeStream();
|
||||
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 : IDataSubscription
|
||||
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;
|
||||
@@ -355,7 +671,7 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
}
|
||||
|
||||
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
|
||||
public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
|
||||
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");
|
||||
|
||||
@@ -365,8 +681,16 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1);
|
||||
}
|
||||
|
||||
public void Ack() => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
|
||||
Open.Items.Select(x => new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray()));
|
||||
public void Ack(params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
|
||||
Open.Items.Select(x => refused.Contains(x.ClientItemId)
|
||||
? new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Unavailable, null, x.Settings, "secondary")
|
||||
: new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray()));
|
||||
|
||||
/// <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)
|
||||
|
||||
Reference in New Issue
Block a user