diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs index bfde39b90..c5654f335 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -213,8 +213,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo // #994 (R-2): the delivery index must hold every item (and every distinct source) the stream may admit. It was sized // from the frame window alone (MaxPendingFrames × 16 = 1024 by default), so the 1025th item — inside the advertised // MaxMonitoredItems — failed registration AFTER its acknowledgement and stopped the whole session. - var schedulerCapacity = checked(Math.Max(limits.MaxPendingFrames * 16, services.SubscriptionLimits.MaxMonitoredItems) + - limits.MaxPendingFrames * 16); + var schedulerCapacity = limits.DeliveryIndexCapacity ?? checked(Math.Max(limits.MaxPendingFrames * 16, + services.SubscriptionLimits.MaxMonitoredItems) + limits.MaxPendingFrames * 16); _scheduler = new DeliveryScheduler(schedulerCapacity, schedulerCapacity); var preOpen = limits.PreOpenTimeout ?? TimeSpan.FromSeconds(10); _preOpen = services.Clock.CreateTimer(static state => ((DataSubscriptionSession)state!).Stop(), this, @@ -515,6 +515,17 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo { itemReservation!.Dispose(); result.Lease.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue; } var item = new Item(request.ClientItemId, handle, view, result.RevisedSettings, result.Lease, itemReservation!); if (_services.SubscriptionHub.TryGetCurrentTicket(view.Source, out var ticket)) item.Ticket = ticket; + // #1057: register in the delivery index BEFORE the acknowledgement is built, so an item it cannot hold is refused + // LimitExceeded in its own ack. Registering after the ack had been queued as Good could only stop the whole session. + // No tick runs while this command does (one worker), so nothing considers the item before its snapshot group exists. + // An item still waiting for its first value registers now too (the index is keyed by source, not ticket), so its + // later recovery cannot fail for capacity after it was acknowledged either; until then it has no ticket to read. + if (!_scheduler.TryRegister(view.Source, checked((long)handle.Handle))) + { + lock (_gate) _handles!.Remove(handle); + item.Dispose(); + acks.Add(new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null)); continue; + } lock (_gate) { _items.Add(handle.Handle, item); _itemsByClient.Add(item.ClientItemId, item); } if (item.Ticket is null) lock (_gate) item.WaitingNode = _waiting.AddLast(handle.Handle); admitted.Add(item); @@ -562,7 +573,6 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo foreach (var item in admitted) { if (item.Ticket is not { } ticket || !snapshot.Items.TryGetValue(ticket, out var captured)) continue; - if (!_scheduler.TryRegister(item.View.Source, checked((long)item.Handle.Handle))) { Stop(); return; } if (captured.Sample is not null) item.LastConsidered = captured.Sample.Version; } _snapshotJobs.AddLast(new SnapshotJob(snapshot, admission, group, admitted, marks)); @@ -959,8 +969,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo { if (!_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) { snapshot!.Dispose(); interest!.Dispose(); admission!.Dispose(); return true; } - if (!_scheduler.TryRegister(item.View.Source, checked((long)item.Handle.Handle))) - { snapshot!.Dispose(); interest!.Dispose(); admission!.Dispose(); CloseWithReset("Interest capacity exhausted."); return true; } + // #1057: the item has been in the delivery index since its admission. _snapshots.Add(snapshot!); _snapshotAdmissions.Add(admission!); group = new InterestGroup(interest!) { Count = 1 }; group.Sources.Add(item.View.Source, 1); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalSubscriptionService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalSubscriptionService.cs index 8f2e3a03f..13d017281 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalSubscriptionService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalSubscriptionService.cs @@ -17,9 +17,13 @@ internal sealed record SubscriptionDemandResult(DataItemStatus Status, DataSubsc long Boundary, IDisposable? Lease); /// A2 review S2: the most root-scoped condition items one stream may hold. +/// +/// #1057: overrides the delivery index's interest/source capacity (null = sized from the frame window and the advertised +/// MaxMonitoredItems). Only tests set it, to reach the registration-refusal path the default sizing makes unreachable. +/// internal sealed record SubscriptionSessionLimits(int MaxCommands, int MaxPendingFrames, long MaxPendingBytes, TimeSpan MaxSessionLifetime, TimeSpan? PreOpenTimeout = null, - int MaxConditionItems = SubscriptionSessionLimits.DefaultMaxConditionItems) + int MaxConditionItems = SubscriptionSessionLimits.DefaultMaxConditionItems, int? DeliveryIndexCapacity = null) { /// The default per-stream condition-item cap (A3 opens one item per condition-bearing mapping). internal const int DefaultMaxConditionItems = 32; @@ -27,6 +31,7 @@ internal sealed record SubscriptionSessionLimits(int MaxCommands, int MaxPending internal void Validate() { if (MaxCommands <= 0 || MaxPendingFrames <= 0 || MaxPendingBytes <= 0 || MaxSessionLifetime <= TimeSpan.Zero || MaxConditionItems <= 0 || + DeliveryIndexCapacity is <= 0 || PreOpenTimeout is { } timeout && (timeout <= TimeSpan.Zero || timeout > TimeSpan.FromMilliseconds(uint.MaxValue - 1))) throw new ArgumentOutOfRangeException(nameof(MaxCommands)); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1057FollowUpTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1057FollowUpTests.cs new file mode 100644 index 000000000..dabcdca5d --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1057FollowUpTests.cs @@ -0,0 +1,106 @@ +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; + +/// #1057: follow-ups left from #994 on the origin subscription session (delivery-index refusal before the ack). +[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().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 _frames = new(); + private readonly ConcurrentDictionary> _acks = new(StringComparer.Ordinal); + internal IReadOnlyCollection Frames => _frames; + internal Task Ack(string command) => + _acks.GetOrAdd(command, _ => new(TaskCreationOptions.RunContinuationsAsynchronously)).Task; + internal bool LiveValueFor(IReadOnlyCollection handles) => handles.All(handle => + _frames.OfType().Any(v => !v.IsSnapshot && v.Items.Any(i => i.Handle == handle))); + internal async Task WaitAsync(Func, 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 PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, + CancellationToken cancellationToken) => ValueTask.FromResult(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() { } + } + } +}