using System.Collections; using Google.Protobuf; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P11")] public sealed class GrpcDataAdversarialRecoveryTests { [Fact(Timeout = 30000)] public async Task Revocation_while_protobuf_values_are_encoding_fences_handoff_and_drains_charges() { var demand = new DeferredSubscriptionDemand(); demand.Accept(); var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); LocalDataFixture? fixture = null; using (fixture = new LocalDataFixture(subscriptions: context => new LocalSubscriptionService(fixture!.Services, context, new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) { fixture.Publish(42); var baseline = fixture.Hub.Resources.RetainedBytes; await using var connection = fixture.Connection(); await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); using var sink = new HeldEncoderSink(); var delivery = ((IDataSubscriptionTransport)subscription).RunDeliveryAsync(sink, TestContext.Current.CancellationToken); var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); try { await sink.EncoderEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); capacity.ActiveOperations.ShouldBe(1); fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline); fixture.Activation.Begin("revoke-while-encoding"); } finally { sink.Release(); } await sink.Encoded.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); await sink.Disposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); await delivery.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); await subscription.DisposeAsync(); sink.ValueHandoffs.ShouldBe(0, "revoked bytes must never reach the transport write boundary"); capacity.ActiveOperations.ShouldBe(0); fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline); capacity.Snapshots.TryAcquire("peer", 1, out var next).ShouldBeTrue(); next!.Dispose(); } } private sealed class HeldEncoderSink : IDataSubscriptionDeliverySink, IDisposable { private readonly ManualResetEventSlim _release = new(); internal readonly TaskCompletionSource EncoderEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource Encoded = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource Disposed = new(TaskCreationOptions.RunContinuationsAsynchronously); internal int ValueHandoffs; public async ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, CancellationToken cancellationToken) { if (frame is not DataSubscriptionValues values) return new Prepared(DataProtoMapper.EncodeControlOrAck(frame).ToByteArray(), false, this); // The production mapper is actively enumerating the real session's owned sample // when authority is revoked. The adapter holds only borrowed references; the session // remains the sole owner of the original frame and its resource leases. var borrowed = new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot, new HeldItems(values.Items, EncoderEntered, _release)); var bytes = await Task.Run(() => DataProtoMapper.EncodeValues(borrowed, true, subscriptionAgeReadiness: true).ToByteArray()); Encoded.TrySetResult(); return new Prepared(bytes, true, this); } public ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) { var value = (Prepared)prepared; if (value.IsValue && value.Guard?.Invoke() == true) Interlocked.Increment(ref ValueHandoffs); return ValueTask.CompletedTask; } internal void Release() => _release.Set(); public void Dispose() { _release.Set(); _release.Dispose(); } private sealed class Prepared(byte[] bytes, bool value, HeldEncoderSink owner) : IDataPreparedSubscriptionPublication { internal bool IsValue => value; internal Func? Guard; public long RetainedBytes => bytes.Length; public void SetPublicationGuard(Func guard) => Guard = guard; public void Dispose() { if (value) owner.Disposed.TrySetResult(); } } private sealed class HeldItems(IReadOnlyList items, TaskCompletionSource entered, ManualResetEventSlim release) : IReadOnlyList { public int Count => items.Count; public DataSubscriptionValue this[int index] => items[index]; public IEnumerator GetEnumerator() { foreach (var item in items) { entered.TrySetResult(); if (!release.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException("Encoder gate was not released."); yield return item; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } }