using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; /// /// H1 (plan ยง3.2): the origin's per-(principal, incarnation) store for remote HistoryRead continuations โ€” idle expiry, /// capacity eviction (oldest-idle), every binding field (principal, incarnation, epoch, view, details hash), single-use /// takes and the token's shape. /// [Trait("Feature", "GrpcData")] [Trait("Phase", "H1")] public sealed class PeerHistoryContinuationStoreTests { private const string Principal = "svc-consumer"; private const string Incarnation = "inc-1"; private const string Hash = "hash-a"; private static HistoryContinuationState State(string identifier = "Plant/dev/t1", long epoch = 3, AddressSpaceRealm realm = AddressSpaceRealm.Raw) => new("WW.T1", DateTime.UnixEpoch, DateTime.UnixEpoch.AddDays(1), 0, 10) { BoundRealm = realm, BoundIdentifier = identifier, BoundTag = "view-1", AddressSpaceEpoch = epoch, }; private static PeerHistoryContinuationKey Key( string principal = Principal, string incarnation = Incarnation, long epoch = 3, AddressSpaceRealm realm = AddressSpaceRealm.Raw, string identifier = "Plant/dev/t1", string hash = Hash, string? tag = "view-1") => new(principal, incarnation, epoch, realm, identifier, tag, hash); private static PeerHistoryContinuationStore Store(int capacity = 8, ManualClock? clock = null, TimeSpan? idle = null) => new(Principal, Incarnation, capacity, idle, clock ?? new ManualClock()); [Fact] public void A_matching_take_returns_the_state_once() { var store = Store(); var state = State(); var token = store.Save(state, Principal, Incarnation, Hash); store.Count.ShouldBe(1); store.TryTake(token, Key()).ShouldBe(state); store.TryTake(token, Key()).ShouldBeNull("takes are single-use"); store.Count.ShouldBe(0); } [Fact] public void A_mismatched_take_consumes_the_record_too() { var store = Store(); var token = store.Save(State(), Principal, Incarnation, Hash); store.TryTake(token, Key(hash: "other")).ShouldBeNull(); store.TryTake(token, Key()).ShouldBeNull("a failed take never leaves the token replayable"); } [Fact] public void Every_bound_field_must_match() { var cases = new (string Name, PeerHistoryContinuationKey Key)[] { ("principal", Key(principal: "someone-else")), ("incarnation", Key(incarnation: "inc-2")), ("epoch bump", Key(epoch: 4)), ("realm", Key(realm: AddressSpaceRealm.Uns)), ("identifier", Key(identifier: "Plant/dev/t2")), ("binding tag", Key(tag: "view-2")), ("no binding tag", Key(tag: null)), ("details hash", Key(hash: "hash-b")), }; foreach (var (name, key) in cases) { var store = Store(); var token = store.Save(State(), Principal, Incarnation, Hash); store.TryTake(token, key).ShouldBeNull(name); } } [Fact] public void An_idle_record_expires() { var clock = new ManualClock(); var store = Store(clock: clock); var fresh = store.Save(State(), Principal, Incarnation, Hash); clock.Advance(TimeSpan.FromSeconds(59)); store.TryTake(fresh, Key()).ShouldNotBeNull("59 s is inside the default 60 s idle expiry"); var stale = store.Save(State(), Principal, Incarnation, Hash); clock.Advance(TimeSpan.FromSeconds(60)); store.Count.ShouldBe(0); store.TryTake(stale, Key()).ShouldBeNull(); PeerHistoryContinuationStore.DefaultIdleExpiry.ShouldBe(TimeSpan.FromSeconds(60)); } [Fact] public void A_custom_idle_expiry_applies() { var clock = new ManualClock(); var store = Store(clock: clock, idle: TimeSpan.FromSeconds(5)); var token = store.Save(State(), Principal, Incarnation, Hash); clock.Advance(TimeSpan.FromSeconds(5)); store.TryTake(token, Key()).ShouldBeNull(); } [Fact] public void Capacity_evicts_the_oldest_idle_record() { var clock = new ManualClock(); var store = Store(capacity: 3, clock: clock); var tokens = new List(); for (var i = 0; i < 3; i++) { tokens.Add(store.Save(State(), Principal, Incarnation, Hash)); clock.Advance(TimeSpan.FromSeconds(1)); } // Take the middle one: the oldest-idle survivor is still tokens[0]. store.TryTake(tokens[1], Key()).ShouldNotBeNull(); tokens.Add(store.Save(State(), Principal, Incarnation, Hash)); // 3 live: 0, 2, 3 โ€” at capacity, nothing evicted yet store.Count.ShouldBe(3); tokens.Add(store.Save(State(), Principal, Incarnation, Hash)); // over capacity โ‡’ evicts tokens[0] store.Count.ShouldBe(3); store.TryTake(tokens[0], Key()).ShouldBeNull("the oldest-idle record was evicted"); store.TryTake(tokens[2], Key()).ShouldNotBeNull(); store.TryTake(tokens[3], Key()).ShouldNotBeNull(); store.TryTake(tokens[4], Key()).ShouldNotBeNull(); } [Fact] public void Expired_records_are_swept_before_capacity_evicts_a_live_one() { var clock = new ManualClock(); var store = Store(capacity: 2, clock: clock); store.Save(State(), Principal, Incarnation, Hash); clock.Advance(TimeSpan.FromSeconds(61)); var live = store.Save(State(), Principal, Incarnation, Hash); var newest = store.Save(State(), Principal, Incarnation, Hash); store.TryTake(live, Key()).ShouldNotBeNull(); store.TryTake(newest, Key()).ShouldNotBeNull(); } [Fact] public void Release_drops_a_record_and_is_idempotent() { var store = Store(); var token = store.Save(State(), Principal, Incarnation, Hash); store.Release(token).ShouldBeTrue(); store.Release(token).ShouldBeFalse(); store.TryTake(token, Key()).ShouldBeNull(); store.Release(null).ShouldBeFalse(); store.Release([1, 2, 3]).ShouldBeFalse(); } [Fact] public void Clear_drops_everything() { var store = Store(); var token = store.Save(State(), Principal, Incarnation, Hash); store.Save(State(), Principal, Incarnation, Hash); store.Clear(); store.Count.ShouldBe(0); store.TryTake(token, Key()).ShouldBeNull(); } [Fact] public void Tokens_are_random_16_byte_ids() { var store = Store(capacity: 2000); var seen = new HashSet(); for (var i = 0; i < 1000; i++) { var token = store.Save(State(), Principal, Incarnation, Hash); token.Length.ShouldBe(PeerHistoryContinuationStore.TokenLength); PeerHistoryContinuationStore.TokenLength.ShouldBe(16); seen.Add(Convert.ToHexString(token)).ShouldBeTrue("tokens never repeat"); } // Random, not sequential: across 1000 tokens every byte position takes many values. var tokens = seen.Select(Convert.FromHexString).ToList(); for (var position = 0; position < 16; position++) tokens.Select(t => t[position]).Distinct().Count().ShouldBeGreaterThan(100, $"byte {position}"); } [Fact] public void Malformed_tokens_are_misses() { var store = Store(); store.Save(State(), Principal, Incarnation, Hash); store.TryTake(null, Key()).ShouldBeNull(); store.TryTake([], Key()).ShouldBeNull(); store.TryTake(new byte[15], Key()).ShouldBeNull(); store.TryTake(new byte[17], Key()).ShouldBeNull(); store.TryTake(new byte[16], Key()).ShouldBeNull(); store.Count.ShouldBe(1); } [Fact] public void A_record_must_be_bound_to_a_view_and_arguments_are_validated() { var store = Store(); Should.Throw(() => store.Save(State() with { BoundIdentifier = null }, Principal, Incarnation, Hash)); Should.Throw(() => new PeerHistoryContinuationStore(Principal, Incarnation, 0)); Should.Throw(() => new PeerHistoryContinuationStore(" ", Incarnation, 1)); Should.Throw(() => new PeerHistoryContinuationStore(Principal, "", 1)); Should.Throw(() => new PeerHistoryContinuationStore(Principal, Incarnation, 1, TimeSpan.Zero)); } [Fact] public void The_scope_binds_the_request_details_hash() { var store = Store(); var scope = new PeerHistoryContinuationScope(store, Principal, () => Incarnation); var details = new HistoryReadRawVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), 10, ReturnBounds: false); var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, details, Tag: "view-1"); var token = scope.Save(State(), binding)!; scope.TryTake(token, binding with { Details = details with { NumValuesPerNode = 11 } }).ShouldBeNull("other details"); token = scope.Save(State(), binding)!; scope.TryTake(token, binding with { Details = details with { } }).ShouldNotBeNull("equal details hash equal"); token = scope.Save(State(), binding)!; scope.TryTake(token, binding with { Epoch = 4 }).ShouldBeNull("epoch bump"); store.Count.ShouldBe(0); } [Fact] public void A_serving_incarnation_change_on_a_live_connection_invalidates_its_tokens() { // In-process failover / role change: the connection (and so the store) survives, the serving incarnation does not. var store = Store(); var incarnation = Incarnation; var scope = new PeerHistoryContinuationScope(store, Principal, () => incarnation); var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, new HistoryReadRawVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), 10, ReturnBounds: false), Tag: "view-1"); var token = scope.Save(State(), binding)!; incarnation = "inc-2"; // A scope is per request: the resume is a NEW request, so it reads inc-2. var resume = new PeerHistoryContinuationScope(store, Principal, () => incarnation); resume.TryTake(token, binding).ShouldBeNull("issued under inc-1, resumed under inc-2"); token = new PeerHistoryContinuationScope(store, Principal, () => incarnation).Save(State(), binding)!; new PeerHistoryContinuationScope(store, Principal, () => incarnation).TryTake(token, binding) .ShouldNotBeNull("issued and resumed under inc-2"); } [Fact] public void Only_the_owning_principal_can_save_or_take() { var store = Store(); var owner = new PeerHistoryContinuationScope(store, Principal, () => Incarnation); var other = new PeerHistoryContinuationScope(store, "someone-else", () => Incarnation); var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null, Tag: "view-1"); Should.Throw(() => other.Save(State(), binding), "a store never holds another principal's cursor"); var token = owner.Save(State(), binding)!; other.TryTake(token, binding).ShouldBeNull(); owner.TryTake(token, binding).ShouldBeNull("the foreign take consumed it"); } [Fact] public void A_take_whose_expectation_throws_still_consumes_the_token() { var store = Store(); var token = store.Save(State(), Principal, Incarnation, Hash); store.TryTake(token, () => throw new InvalidOperationException("incarnation source down")).ShouldBeNull(); store.Count.ShouldBe(0); store.TryTake(token, Key()).ShouldBeNull("the token is gone"); } [Fact] public void A_scope_whose_incarnation_source_throws_or_is_blank_takes_nothing_and_fails_wiring_on_save() { var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null, Tag: "view-1"); foreach (var (name, source) in new (string, Func)[] { ("throws", () => throw new InvalidOperationException("incarnation source down")), ("blank", () => " "), }) { var store = Store(); var token = store.Save(State(), Principal, Incarnation, Hash); var broken = new PeerHistoryContinuationScope(store, Principal, source); broken.TryTake(token, binding).ShouldBeNull(name); store.Count.ShouldBe(0, $"{name}: the take consumed the token"); Should.Throw( () => new PeerHistoryContinuationScope(store, Principal, source).Save(State(), binding), name); } } [Fact] public void Wiring_errors_have_their_own_exception_type() { var store = Store(); Should.Throw(() => store.Save(State(), "someone-else", Incarnation, Hash)); Should.Throw(() => store.Save(State(), Principal, "", Hash)); } [Fact] public void A_request_that_straddles_an_incarnation_change_binds_the_incarnation_it_started_under() { // One scope per request: the incarnation is snapshotted at its first use, so a failover that lands between the // request's take and its save cannot re-bind the next token to the NEW incarnation. var store = Store(); var incarnation = Incarnation; var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null, Tag: "view-1"); var first = new PeerHistoryContinuationScope(store, Principal, () => incarnation).Save(State(), binding)!; var request = new PeerHistoryContinuationScope(store, Principal, () => incarnation); request.TryTake(first, binding).ShouldNotBeNull(); incarnation = "inc-2"; // failover mid-request var next = request.Save(State(), binding); next.ShouldNotBeNull("a save never answers null (that would read as a complete read)"); new PeerHistoryContinuationScope(store, Principal, () => incarnation).TryTake(next!, binding) .ShouldBeNull("the next token is bound to inc-1, so the resume under inc-2 is refused"); } [Fact] public void The_details_hash_is_culture_invariant() { var variants = new HistoryReadVariant[] { new HistoryReadRawVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), 10, ReturnBounds: true), new HistoryReadProcessedVariant(DateTime.UnixEpoch, DateTime.UnixEpoch.AddHours(1), TimeSpan.FromTicks(-5), new Opc.Ua.AggregateConfiguration { PercentDataBad = 100, PercentDataGood = 100 }), new HistoryReadAtTimeVariant([DateTime.UnixEpoch, DateTime.UnixEpoch.AddSeconds(1)]), }; var invariant = variants.Select(v => v.ComputeDetailsHash()).ToArray(); var odd = (System.Globalization.CultureInfo)System.Globalization.CultureInfo.InvariantCulture.Clone(); odd.NumberFormat.NegativeSign = "~"; odd.NumberFormat.NumberGroupSeparator = "'"; odd.TextInfo.ListSeparator = "#"; var previous = System.Globalization.CultureInfo.CurrentCulture; try { System.Globalization.CultureInfo.CurrentCulture = odd; variants.Select(v => v.ComputeDetailsHash()).ToArray().ShouldBe(invariant); } finally { System.Globalization.CultureInfo.CurrentCulture = previous; } } /// A monotonic test clock. private sealed class ManualClock : TimeProvider { private long _ticks = 1_000_000; public override long TimestampFrequency => TimeSpan.TicksPerSecond; public override long GetTimestamp() => Interlocked.Read(ref _ticks); public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks); } }