Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1057FollowUpTests.cs
T
Joseph Doherty 258634c12b fix(grpc-data): #1057 an item the origin's delivery index cannot hold is refused LimitExceeded in its ack instead of stopping the session after it
Registration in the session's delivery index happened after the Open/Add acknowledgement had been queued as Good, so a
registration failure could only Stop() the whole session (every sibling item went with it). Items now register at
admission, before the ack is built; a refusal is the item's own LimitExceeded. Waiting-for-initial-data items register
at admission too (the index is keyed by source), so their later recovery can no longer reset the stream for capacity.
SubscriptionSessionLimits.DeliveryIndexCapacity is a test-only override of the index size.
2026-12-03 15:11:09 -05:00

107 lines
6.5 KiB
C#

using System.Collections.Concurrent;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>#1057: follow-ups left from #994 on the origin subscription session (delivery-index refusal before the ack).</summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "1057")]
public sealed class GrpcData1057FollowUpTests
{
internal static readonly DataSubscriptionSettings Settings = new(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
internal static DataView Extra(LocalDataFixture fixture, int i) => fixture.Raw with
{
Address = fixture.Raw.Address with { Identifier = fixture.Raw.Address.Identifier + i }, Subject = fixture.Raw.Subject + i
};
// Item 1: an item the delivery index could not hold was refused only AFTER its acknowledgement had been queued as Good —
// the registration failure then stopped the whole session, so every sibling item on the stream went down with it.
[Fact(Timeout = 30000)]
public async Task An_item_the_delivery_index_cannot_hold_is_refused_LimitExceeded_in_its_ack_and_the_stream_keeps_serving()
{
var ct = TestContext.Current.CancellationToken;
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1), DeliveryIndexCapacity: 2);
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(additionalRawNodes: 3, targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(10);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(ct);
var sink = new RecordingSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().RunDeliveryAsync(sink, ct);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("a", Extra(fixture, 0), Settings), new("b", Extra(fixture, 1), Settings), new("c", Extra(fixture, 2), Settings)],
false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), ct);
var ack = await sink.Ack("open").WaitAsync(TimeSpan.FromSeconds(10), ct);
ack.Items.Single(x => x.ClientItemId == "a").Status.ShouldBe(DataItemStatus.Good);
ack.Items.Single(x => x.ClientItemId == "b").Status.ShouldBe(DataItemStatus.Good);
var refused = ack.Items.Single(x => x.ClientItemId == "c");
refused.Status.ShouldBe(DataItemStatus.LimitExceeded, "the refusal belongs in the acknowledgement, not in a session stop after it");
refused.Handle.ShouldBeNull();
await sink.WaitAsync(frames => frames.Any(f => f is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }),
TimeSpan.FromSeconds(10), ct);
// The stream keeps serving its admitted items: a later value reaches both.
var handles = ack.Items.Where(x => x.Handle is not null).Select(x => x.Handle!).ToArray();
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 20);
fixture.Hub.ProcessPending();
for (var i = 0; i < 50 && !sink.LiveValueFor(handles); i++)
{
fixture.Clock.Advance(TimeSpan.FromMilliseconds(100));
await Task.Delay(20, ct);
}
sink.LiveValueFor(handles).ShouldBeTrue("both admitted items still deliver: " + sink.Describe());
writer.IsCompleted.ShouldBeFalse("the session was not stopped");
}
}
internal sealed class RecordingSink : IDataSubscriptionDeliverySink
{
private readonly ConcurrentQueue<DataSubscriptionFrame> _frames = new();
private readonly ConcurrentDictionary<string, TaskCompletionSource<DataSubscriptionAck>> _acks = new(StringComparer.Ordinal);
internal IReadOnlyCollection<DataSubscriptionFrame> Frames => _frames;
internal Task<DataSubscriptionAck> Ack(string command) =>
_acks.GetOrAdd(command, _ => new(TaskCreationOptions.RunContinuationsAsynchronously)).Task;
internal bool LiveValueFor(IReadOnlyCollection<DataItemHandle> handles) => handles.All(handle =>
_frames.OfType<DataSubscriptionValues>().Any(v => !v.IsSnapshot && v.Items.Any(i => i.Handle == handle)));
internal async Task WaitAsync(Func<IReadOnlyCollection<DataSubscriptionFrame>, bool> condition, TimeSpan timeout, CancellationToken ct)
{
var deadline = DateTime.UtcNow + timeout;
while (!condition(_frames))
{
if (DateTime.UtcNow > deadline) throw new ShouldAssertException("timed out: " + Describe());
await Task.Delay(10, ct);
}
}
internal string Describe() => string.Join(" | ", _frames.Select(frame => frame switch
{
DataSubscriptionAck ack => "ack:" + ack.CommandId + "[" + string.Join(",", ack.Items.Select(i => i.ClientItemId + "=" + i.Status)) + "]",
DataSubscriptionControl control => control.Kind + (control.Diagnostic is { } d ? ":" + d : ""),
DataSubscriptionValues values => (values.IsSnapshot ? "snap" : "live") + values.Items.Count,
_ => frame.GetType().Name
}));
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame));
public ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
var frame = ((Prepared)prepared).Frame;
_frames.Enqueue(frame);
if (frame is DataSubscriptionAck ack)
_acks.GetOrAdd(ack.CommandId, _ => new(TaskCreationOptions.RunContinuationsAsynchronously)).TrySetResult(ack);
return ValueTask.CompletedTask;
}
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}
}