diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs
index 21b6071f3..36806cbdb 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs
@@ -48,7 +48,48 @@ public sealed record DataConnectionDiagnosticsSnapshot(
long? HistoryReadsGood = null,
long? HistoryReadsUncertain = null,
long? HistoryReadsBad = null,
- int? OpenRemoteContinuations = null);
+ int? OpenRemoteContinuations = null,
+ // A4 consumer-side imported-condition evidence (null = no condition-bearing mapping on this connection, or an older sender).
+ ConsumerConditionDiagnostics? Conditions = null);
+
+/// A4: one condition-bearing mapping of a consumer connection's condition stream.
+/// The mapping.
+/// Pending | Snapshotting | Complete | Unavailable | ConditionCapacity.
+/// The last count the origin reported or listed for it (a snapshot total, or the committed set).
+/// The mapping's MaxConditions.
+/// The origin's last refusal status for its item or root (null when not refused).
+public sealed record ConditionMappingDiagnostics(string MappingId, string Status, int Observed, int Limit, string? Refusal = null);
+
+/// A4: consumer evidence of one connection's imported conditions (plan §6 "AdminUI").
+/// idle (no event subscriber) | connecting | snapshotting | live.
+/// When the connection's last snapshot barrier passed (null: none since start).
+/// Imported conditions this node holds for the connection.
+/// Of those, how many carry state_known = false (never shown known-inactive).
+/// RefreshRequired requests made for the connection since start (explicit, plus each removal batch).
+/// Condition streams that ended and re-snapshotted since start.
+/// Mappings reset to ConditionCapacity since start.
+/// Per mapping: status, observed count vs limit, refusal.
+/// Imported conditions charged against this node's host caps (every connection).
+/// The node-wide condition cap implied by MaxImportedConditionNodes/Bytes.
+public sealed record ConsumerConditionDiagnostics(string StreamState, DateTime? SnapshotAtUtc, int Materialised, int StateUnknown,
+ long RefreshRequired, long Resyncs, long CapacityRejections, IReadOnlyList Mappings,
+ long ChargedConditions, long HostConditionLimit, ConditionMethodCounts Methods);
+
+/// A4: remote condition method calls by outcome class (from DataWriteState).
+public sealed record ConditionMethodCounts(long Succeeded, long Rejected, long Failed, long Unknown);
+
+/// A4: origin-side evidence of the root-scoped condition items this node serves to peers.
+/// Open condition items (all peers).
+/// The largest current listing among the open items (their last snapshot's total).
+/// That item's MaxConditions limit (0 when no item is open).
+/// When an item last took a snapshot (null: none since start).
+/// Items re-snapshotted after a hub reader reset since start.
+/// Item snapshots refused as over the item's limit since start.
+/// Native conditions whose initial state was never signalled (served state_known = false);
+/// null when the node has no condition hub.
+/// Remote condition method calls served, by outcome class.
+public sealed record OriginConditionDiagnostics(int OpenItems, int LargestListing, int ListingLimit, DateTime? LastSnapshotAtUtc,
+ long Resyncs, long CapacityRejections, int? UnsignalledConditions, ConditionMethodCounts Methods);
/// H4 origin-side remote-history evidence for one node (what it serves to peers over data connections).
/// The node has a historian backend and can serve remote history.
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs
index 1517e0ea1..480fda693 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs
@@ -51,6 +51,10 @@ public sealed record DriverInstanceDiagnostics(
/// H4: remote history this node serves to data-connection peers. Null from a sender built before H4 or when the node
/// runs no data-connection services.
///
+///
+/// A4: root-scoped condition items this node serves to data-connection peers. Null from a sender built before A4 or when the
+/// node runs no data-connection services.
+///
public sealed record NodeDiagnosticsSnapshot(
NodeId NodeId,
RevisionHash? CurrentRevision,
@@ -59,4 +63,5 @@ public sealed record NodeDiagnosticsSnapshot(
bool RunningFromCache = false,
IReadOnlyList? DataConnections = null,
IReadOnlyDictionary? DroppedExportOperations = null,
- OriginHistoryDiagnostics? OriginHistory = null);
+ OriginHistoryDiagnostics? OriginHistory = null,
+ OriginConditionDiagnostics? OriginConditions = null);
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs
index e37784937..893364fa2 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs
@@ -137,6 +137,14 @@ public static class DataConnectionRegistration
diagnostics.AttachProvisionalOrigin(() => probe.Serving is not null);
return diagnostics;
});
+ // A4: one dependency-free condition diagnostics instance shared by the origin condition items, the consumer runtime and
+ // the diagnostics readers (it also backs the side-labelled otopcua.dataconn.condition* metrics).
+ services.AddSingleton(sp =>
+ {
+ var diagnostics = new DataConnectionConditionDiagnostics();
+ if (sp.GetService() is { } hub) diagnostics.AttachUnsignalled(() => hub.Unsignalled.Values.Sum(x => x.Conditions));
+ return diagnostics;
+ });
// H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection.
services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService(),
sp.GetRequiredService(),
@@ -153,7 +161,8 @@ public static class DataConnectionRegistration
{
MaxImportedConditionNodes = options.MaxImportedConditionNodes,
MaxImportedConditionBytes = options.MaxImportedConditionBytes,
- }, sp.GetRequiredService().CreateLogger()));
+ }, sp.GetRequiredService().CreateLogger(),
+ sp.GetRequiredService()));
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => new ConfiguredProjectionDiscovery(
sp.GetRequiredService(), sp.GetRequiredService(),
@@ -197,7 +206,7 @@ public static class DataConnectionRegistration
// A2: root-scoped condition items over the A1 hub and the node manager's snapshot port.
sp.GetService(), new DeferredOriginConditionSource(sp.GetRequiredService()),
// A2b security review: the audit trail on its OWN category from the host's logger factory.
- sp.GetRequiredService());
+ sp.GetRequiredService(), sp.GetRequiredService());
});
services.AddSingleton(sp => new DeferredFactory(() => sp.GetRequiredService().Services));
services.AddSingleton();
@@ -264,6 +273,7 @@ public static class DataConnectionRegistration
{
Logger = LoggerFor(sp),
HistoryDiagnostics = sp.GetRequiredService(),
+ ConditionDiagnostics = sp.GetRequiredService(),
};
return runtime;
});
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs
index 6a6900e1a..84058d65b 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs
@@ -43,7 +43,7 @@ internal sealed record ConditionItemScope(object Catalog, IReadOnlyList.
///
-internal sealed class ConditionItemStream : IDisposable
+internal sealed class ConditionItemStream : IDisposable, DataConnectionConditionDiagnostics.IOriginItem
{
/// The most records one chunk carries.
internal const int MaxRecordsPerChunk = 128;
@@ -90,8 +90,10 @@ internal sealed class ConditionItemStream : IDisposable
/// Charges a snapshot's estimated bytes (null = refused); default: never refused.
/// The most estimated record bytes one chunk carries (≤ ).
internal ConditionItemStream(ConditionStateHub hub, IOriginConditionSource source, Func scope,
- bool includeInfo, TimeProvider clock, Func? reserveSnapshot = null, long chunkBytes = MaxChunkBytes)
+ bool includeInfo, TimeProvider clock, Func? reserveSnapshot = null, long chunkBytes = MaxChunkBytes,
+ DataConnectionConditionDiagnostics? diagnostics = null)
{
+ Diagnostics = diagnostics;
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
_source = source ?? throw new ArgumentNullException(nameof(source));
_scope = scope ?? throw new ArgumentNullException(nameof(scope));
@@ -108,6 +110,14 @@ internal sealed class ConditionItemStream : IDisposable
/// The most estimated record bytes one chunk carries.
internal long ChunkBytes { get; }
+ /// A4: the node's condition diagnostics (null: metrics only).
+ internal DataConnectionConditionDiagnostics? Diagnostics { get; }
+
+ private long _lastSnapshotUtcTicks;
+ int DataConnectionConditionDiagnostics.IOriginItem.Total => Volatile.Read(ref _total);
+ int DataConnectionConditionDiagnostics.IOriginItem.Limit => Volatile.Read(ref _limit);
+ long DataConnectionConditionDiagnostics.IOriginItem.LastSnapshotTicks => Interlocked.Read(ref _lastSnapshotUtcTicks);
+
/// A record could not be made to fit ; the session ends the stream.
internal bool Oversized { get; private set; }
@@ -162,6 +172,12 @@ internal sealed class ConditionItemStream : IDisposable
lock (_leaseGate) ReleaseLease();
}
+ private void CountCapacityRejection()
+ {
+ if (Diagnostics is { } diagnostics) diagnostics.OriginCapacityRejection();
+ else DataConnectionConditionDiagnostics.CountCapacityRejection(DataConnectionConditionDiagnostics.OriginSide);
+ }
+
/// Produce the next chunk, or null when there is nothing to send now.
internal ConditionChunk? Next()
{
@@ -193,7 +209,8 @@ internal sealed class ConditionItemStream : IDisposable
private ConditionChunk? ResetSnapshot(ConditionItemScope scope)
{
Resets++;
- OtOpcUaTelemetry.DataConnConditionResyncs.Add(1);
+ if (Diagnostics is { } diagnostics) diagnostics.OriginResync();
+ else DataConnectionConditionDiagnostics.CountResync(DataConnectionConditionDiagnostics.OriginSide);
_state = State.NeedSnapshot;
return CanSnapshotNow() ? TakeSnapshot(scope) : null;
}
@@ -237,6 +254,8 @@ internal sealed class ConditionItemStream : IDisposable
{
Snapshots++;
_lastSnapshotAt = _clock.GetTimestamp();
+ Interlocked.Exchange(ref _lastSnapshotUtcTicks, _clock.GetUtcNow().UtcTicks);
+ Diagnostics?.OriginSnapshot(_clock.GetUtcNow().UtcTicks);
_catalog = scope.Catalog;
_limit = scope.Limit;
lock (_leaseGate) ReleaseLease();
@@ -247,7 +266,7 @@ internal sealed class ConditionItemStream : IDisposable
{
// §5.5: total above the limit is reported at snapshot begin, before (and instead of) any record.
_state = State.OverCapacity;
- OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
+ CountCapacityRejection();
_total = listing.Count;
return new ConditionChunk(true, listing.Count, [], false);
}
@@ -261,7 +280,7 @@ internal sealed class ConditionItemStream : IDisposable
if (records.Count > _limit)
{
_state = State.OverCapacity;
- OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
+ CountCapacityRejection();
_total = records.Count;
return new ConditionChunk(true, records.Count, [], false);
}
@@ -282,7 +301,7 @@ internal sealed class ConditionItemStream : IDisposable
if (_reserveSnapshot(bytes) is not { } lease)
{
MemoryRejections++;
- OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
+ CountCapacityRejection();
_snapshotRecords.Clear(); _sliceWatermarks.Clear(); _sent.Clear();
_state = State.NeedSnapshot; // retried after MinResnapshotInterval
return null;
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionConditionDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionConditionDiagnostics.cs
new file mode 100644
index 000000000..9351808ca
--- /dev/null
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionConditionDiagnostics.cs
@@ -0,0 +1,193 @@
+using System.Collections.Concurrent;
+using System.Diagnostics.Metrics;
+using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
+using ZB.MOM.WW.OtOpcUa.Commons.Observability;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
+
+namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
+
+///
+/// A4 imported/exported-condition diagnostics and metrics for one process (plan §6 "AdminUI" and "Metrics"), shaped like
+/// H4's : dependency-free, shared by the origin services
+/// (, its condition items), the consumer runtime () and
+/// the diagnostics readers (, the driver host), so none depends on another.
+///
+///
+/// Metrics, on , never carry an id in a label; every one carries side
+/// (origin | consumer), because a node can be both (the H4 convention):
+///
+/// - otopcua.dataconn.conditions.items{side} — open condition items: origin = root-scoped items served to peers;
+/// consumer = the items its condition streams hold open (one per acked mapping).
+/// - otopcua.dataconn.conditions.resyncs{side} — origin: an item re-snapshotted after a hub reader reset;
+/// consumer: a condition stream that ended (it re-snapshots on the next).
+/// - {side=consumer} — RefreshRequired requests the consumer runtime
+/// made (an incomplete barrier with a changed incomplete set, a capacity reset that removed nothing, each removal batch).
+/// - otopcua.dataconn.conditions.capacity_rejections{side} — origin: an item snapshot over its limit; consumer: a
+/// mapping reset to ConditionCapacity (over its MaxConditions or the host caps).
+/// - otopcua.dataconn.condition_methods{method,outcome,side} — origin: calls served; consumer: calls forwarded
+/// (outcome = the DataWriteState).
+///
+///
+public sealed class DataConnectionConditionDiagnostics
+{
+ public const string OriginSide = "origin";
+ public const string ConsumerSide = "consumer";
+ public const string RefreshRequiredCounterName = "otopcua.dataconn.conditions.refresh_required";
+
+ private static readonly Counter RefreshRequiredCounter = OtOpcUaTelemetry.Meter.CreateCounter(RefreshRequiredCounterName,
+ unit: "{request}", description: "RefreshRequired requests made by the imported-condition runtime (tag side = consumer).");
+
+ private static KeyValuePair Side(string side) => new("side", side);
+
+ internal static void CountItems(string side, int delta) => OtOpcUaTelemetry.DataConnConditionItems.Add(delta, Side(side));
+
+ internal static void CountResync(string side) => OtOpcUaTelemetry.DataConnConditionResyncs.Add(1, Side(side));
+
+ internal static void CountCapacityRejection(string side) => OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1, Side(side));
+
+ internal static void CountMethod(string side, DataConditionMethods method, DataWriteState outcome) =>
+ OtOpcUaTelemetry.DataConnConditionMethods.Add(1, new KeyValuePair("method", method.ToString()),
+ new KeyValuePair("outcome", outcome.ToString()), Side(side));
+
+ private sealed class Methods
+ {
+ public long Succeeded, Rejected, Failed, Unknown;
+
+ public void Add(DataWriteState outcome)
+ {
+ switch (outcome)
+ {
+ case DataWriteState.DriverConfirmedSuccess: Interlocked.Increment(ref Succeeded); break;
+ case DataWriteState.RejectedBeforeDispatch: Interlocked.Increment(ref Rejected); break;
+ case DataWriteState.DriverConfirmedFailure: Interlocked.Increment(ref Failed); break;
+ default: Interlocked.Increment(ref Unknown); break;
+ }
+ }
+
+ public ConditionMethodCounts Capture() =>
+ new(Interlocked.Read(ref Succeeded), Interlocked.Read(ref Rejected), Interlocked.Read(ref Failed), Interlocked.Read(ref Unknown));
+ }
+
+ private sealed class ConsumerCounts
+ {
+ public long Refresh, Resyncs, Capacity;
+ public readonly Methods Methods = new();
+ }
+
+ /// What the consumer runtime reports for one connection (null: no condition-bearing mapping on it).
+ public sealed record ConsumerState(string StreamState, DateTime? SnapshotAtUtc, int Materialised, int StateUnknown,
+ ConditionMappingDiagnostics[] Mappings, long ChargedConditions, long HostConditionLimit);
+
+ /// An origin condition item's current listing (read at capture; plain ints, written by the item's producer).
+ internal interface IOriginItem
+ {
+ int Total { get; }
+ int Limit { get; }
+ long LastSnapshotTicks { get; }
+ }
+
+ private readonly ConcurrentDictionary _consumer = new(StringComparer.OrdinalIgnoreCase);
+ private readonly Methods _originMethods = new();
+ private readonly ConcurrentDictionary _originItems = new(ReferenceEqualityComparer.Instance);
+ private long _originResyncs, _originCapacity, _originLastSnapshotTicks;
+ private Func? _consumerState;
+ private Func? _unsignalled;
+
+ private ConsumerCounts Consumer(string connectionId) => _consumer.GetOrAdd(connectionId, static _ => new ConsumerCounts());
+
+ // ------------------------------------------------------------------ consumer
+
+ /// Connects the consumer runtime whose live per-connection state this reports.
+ internal void AttachConsumer(Func state) => _consumerState = state;
+
+ internal void ConsumerRefreshRequired(string connectionId)
+ {
+ Interlocked.Increment(ref Consumer(connectionId).Refresh);
+ RefreshRequiredCounter.Add(1, Side(ConsumerSide));
+ }
+
+ internal void ConsumerResync(string connectionId)
+ {
+ Interlocked.Increment(ref Consumer(connectionId).Resyncs);
+ CountResync(ConsumerSide);
+ }
+
+ internal void ConsumerCapacityRejection(string connectionId)
+ {
+ Interlocked.Increment(ref Consumer(connectionId).Capacity);
+ CountCapacityRejection(ConsumerSide);
+ }
+
+ internal void ConsumerMethod(string connectionId, DataConditionMethods method, DataWriteState outcome)
+ {
+ Consumer(connectionId).Methods.Add(outcome);
+ CountMethod(ConsumerSide, method, outcome);
+ }
+
+ /// The consumer evidence of one connection; null when it carries no condition-bearing mapping.
+ public ConsumerConditionDiagnostics? CaptureConsumer(string connectionId)
+ {
+ ConsumerState? state;
+ try { state = _consumerState?.Invoke(connectionId); }
+ catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException) { state = null; }
+ if (state is null) return null;
+ var counts = _consumer.TryGetValue(connectionId, out var c) ? c : new ConsumerCounts();
+ return new ConsumerConditionDiagnostics(state.StreamState, state.SnapshotAtUtc, state.Materialised, state.StateUnknown,
+ Interlocked.Read(ref counts.Refresh), Interlocked.Read(ref counts.Resyncs), Interlocked.Read(ref counts.Capacity), state.Mappings,
+ state.ChargedConditions, state.HostConditionLimit, counts.Methods.Capture());
+ }
+
+ // ------------------------------------------------------------------ origin
+
+ /// Connects the condition hub's unsignalled count (state_known = false at the origin).
+ public void AttachUnsignalled(Func unsignalled) => _unsignalled = unsignalled;
+
+ internal void OriginItemOpened(IOriginItem item)
+ {
+ _originItems.TryAdd(item, 0);
+ CountItems(OriginSide, 1);
+ }
+
+ internal void OriginItemClosed(IOriginItem item)
+ {
+ if (_originItems.TryRemove(item, out _)) CountItems(OriginSide, -1);
+ }
+
+ internal void OriginSnapshot(long utcTicks) => Interlocked.Exchange(ref _originLastSnapshotTicks, utcTicks);
+
+ internal void OriginResync()
+ {
+ Interlocked.Increment(ref _originResyncs);
+ CountResync(OriginSide);
+ }
+
+ internal void OriginCapacityRejection()
+ {
+ Interlocked.Increment(ref _originCapacity);
+ CountCapacityRejection(OriginSide);
+ }
+
+ internal void OriginMethod(DataConditionMethods method, DataWriteState outcome)
+ {
+ _originMethods.Add(outcome);
+ CountMethod(OriginSide, method, outcome);
+ }
+
+ /// The origin evidence of this node (never null from an A4 build; zeros before any peer).
+ public OriginConditionDiagnostics CaptureOrigin()
+ {
+ int largest = 0, limit = 0;
+ foreach (var item in _originItems.Keys)
+ {
+ var total = item.Total;
+ // The item nearest its limit is the one to show (largest ratio; ties → largest listing).
+ if (limit == 0 || (long)total * Math.Max(1, limit) > (long)largest * Math.Max(1, item.Limit)) { largest = total; limit = item.Limit; }
+ }
+ int? unsignalled;
+ try { unsignalled = _unsignalled?.Invoke(); }
+ catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException) { unsignalled = null; }
+ var ticks = Interlocked.Read(ref _originLastSnapshotTicks);
+ return new OriginConditionDiagnostics(_originItems.Count, largest, limit, ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc),
+ Interlocked.Read(ref _originResyncs), Interlocked.Read(ref _originCapacity), unsignalled, _originMethods.Capture());
+ }
+}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs
index 0ac48a0bc..6d7dcd229 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs
@@ -48,6 +48,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
public ILogger Logger { private get; init; } = NullLogger.Instance;
/// H4: consumer/origin remote-history evidence merged into the diagnostics; optional (init keeps the constructor shape).
public DataConnectionHistoryDiagnostics? HistoryDiagnostics { get; init; }
+ /// A4: consumer/origin imported-condition evidence merged into the diagnostics; optional (init keeps the constructor shape).
+ public DataConnectionConditionDiagnostics? ConditionDiagnostics { get; init; }
private IReadOnlyDictionary _droppedOperations = new Dictionary();
private long _unknownOperationRows;
private readonly string _node, _owner;
@@ -121,9 +123,11 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
int? MappingDrops(string id) => mappingsWithDroppedOperations is null ? null
: mappingsWithDroppedOperations.TryGetValue(id, out var count) ? count : 0;
var history = HistoryDiagnostics;
+ var conditions = ConditionDiagnostics;
ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot WithHistory(
ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot row)
{
+ if (conditions is not null) row = row with { Conditions = conditions.CaptureConsumer(row.ConnectionId) };
if (history is null) return row;
var counts = history.CaptureConsumer(row.ConnectionId);
return row with { HistoryReadsGood = counts.Good, HistoryReadsUncertain = counts.Uncertain, HistoryReadsBad = counts.Bad,
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs
index c09756647..3e3930ac3 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs
@@ -35,7 +35,8 @@ internal sealed partial class DataSubscriptionSession
{
Stream.Dispose(); // releases the snapshot memory charge
r.Dispose();
- OtOpcUaTelemetry.DataConnConditionItems.Add(-1);
+ if (Stream.Diagnostics is { } diagnostics) diagnostics.OriginItemClosed(Stream);
+ else DataConnectionConditionDiagnostics.CountItems(DataConnectionConditionDiagnostics.OriginSide, -1);
}
}
}
@@ -108,9 +109,11 @@ internal sealed partial class DataSubscriptionSession
var principal = _context.PrincipalId;
var snapshots = _capacity.Snapshots;
var stream = new ConditionItemStream(hub, source, authority.Scope, request.ConditionScope!.IncludeInfo, services.Clock,
- reserveSnapshot: bytes => snapshots.TryAcquire(principal, bytes, out var lease) ? lease : null, chunkBytes: chunkBytes);
+ reserveSnapshot: bytes => snapshots.TryAcquire(principal, bytes, out var lease) ? lease : null, chunkBytes: chunkBytes,
+ diagnostics: services.ConditionDiagnostics);
var item = new ConditionItem(request.ClientItemId, handle, authority, stream, reservation!);
- OtOpcUaTelemetry.DataConnConditionItems.Add(1);
+ if (stream.Diagnostics is { } itemDiagnostics) itemDiagnostics.OriginItemOpened(stream);
+ else DataConnectionConditionDiagnostics.CountItems(DataConnectionConditionDiagnostics.OriginSide, 1);
lock (_gate)
{
_conditionItems.Add(handle.Handle, item);
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs
index 52aee051a..d3389428d 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs
@@ -25,7 +25,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable
ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null,
DataConnectionHistoryDiagnostics? historyDiagnostics = null,
ConditionStateHub? conditionHub = null, ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginConditionSource? conditionSource = null,
- IDataConnectionAuditLog? audit = null)
+ IDataConnectionAuditLog? audit = null, DataConnectionConditionDiagnostics? conditionDiagnostics = null)
{
ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub);
ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities);
@@ -49,6 +49,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable
Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, HistoryDiagnostics = historyDiagnostics,
// A2: condition streams over the A1 hub and the node manager's snapshot port; keys from the coordinator.
ConditionHub = conditionHub, ConditionSource = conditionSource, ConditionKeysSource = () => catalog.ConditionKeys,
+ ConditionDiagnostics = conditionDiagnostics,
// A2b security review: the audit trail on its own logger category (the Host passes it), never the services' logger.
Audit = audit ?? new LoggerDataConnectionAuditLog(logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance),
ConditionMethodMaxOperations = limits.MaxConditionMethodOperations,
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs
index f42e21177..243ca5569 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs
@@ -161,8 +161,8 @@ public sealed partial class LocalDataServices
{
Logger.LogError(ex, "The data-connection audit log failed to record a condition method call");
}
- OtOpcUaTelemetry.DataConnConditionMethods.Add(1, new KeyValuePair("method", request.Method.ToString()),
- new KeyValuePair("outcome", state.ToString()));
+ if (ConditionDiagnostics is { } diagnostics) diagnostics.OriginMethod(request.Method, state);
+ else DataConnectionConditionDiagnostics.CountMethod(DataConnectionConditionDiagnostics.OriginSide, request.Method, state);
}
async Task<(DataConditionMethodResult, bool)> DecideAsync()
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs
index 633b136d5..42c6b5d80 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs
@@ -20,6 +20,9 @@ public sealed partial class LocalDataServices
/// A1/A2: the condition-state hub the node manager feeds (null ⇒ conditions are not servable).
public ConditionStateHub? ConditionHub { get; init; }
+ /// A4: the node's condition diagnostics (items, snapshots, resyncs, capacity, method outcomes); null = metrics only.
+ public DataConnectionConditionDiagnostics? ConditionDiagnostics { get; init; }
+
/// A2: the node manager's condition snapshot port (null ⇒ conditions are not servable).
public IOriginConditionSource? ConditionSource { get; init; }
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs
index b54bd3119..8ba8f62be 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs
@@ -52,8 +52,20 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod
public async Task CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(call);
- ServingIdentity? serving;
- lock (_gate) serving = _runners.TryGetValue(call.ConnectionId, out var runner) ? runner.Serving : null;
+ var outcome = DataWriteState.OutcomeUnknown;
+ try
+ {
+ var result = await ForwardAsync(call, cancellationToken).ConfigureAwait(false);
+ outcome = result.State;
+ return result;
+ }
+ finally { Diagnostics.ConsumerMethod(call.ConnectionId, call.Method, outcome); } // A4: every forwarded call, by outcome
+ }
+
+ private async Task ForwardAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken)
+ {
+ // #931 N6: no _gate here — a method call must never queue behind a runner stop (which takes the stale gate).
+ var serving = _runners.TryGetValue(call.ConnectionId, out var runner) ? runner.Serving : null;
// No open condition stream ⇒ no serving incarnation to address: the connection is down for this purpose. Nothing sent.
if (serving is null)
return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "No condition stream is open on the connection.");
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs
index 75b4dd8af..3eee6bae6 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
+using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
@@ -24,8 +25,24 @@ public sealed partial class ProjectedConditionAccess
private sealed class Entry
{
public int Materialised;
+ /// #931 N5: materialised keys no contributing mapping lists (an Unavailable mapping's stale-held keys).
+ public int Unlisted;
public readonly Dictionary Claims = new(StringComparer.OrdinalIgnoreCase);
- public long Charge => Math.Max(Materialised, Claims.Values.Sum(x => (long)x));
+ /// Claims of mappings with no committed set in this stream (first snapshot / retry): they may re-list the
+ /// held-but-unlisted keys, so they overlap instead of adding to it.
+ public readonly HashSet Unknown = new(StringComparer.OrdinalIgnoreCase);
+ // N5: max(Materialised, ΣClaims) under-counted while one mapping's stale keys were held and another (known) mapping
+ // claimed new ones. The held-but-unlisted keys are charged beside the known mappings' claims; an unknown mapping's
+ // claim may be those very keys, so it is charged as max(Unlisted, Σ unknown claims).
+ public long Charge
+ {
+ get
+ {
+ long known = 0, unknown = 0;
+ foreach (var (mapping, count) in Claims) if (Unknown.Contains(mapping)) unknown += count; else known += count;
+ return Math.Max(Materialised, known + Math.Max(Unlisted, unknown));
+ }
+ }
}
private readonly object _gate = new();
@@ -43,39 +60,65 @@ public sealed partial class ProjectedConditionAccess
conditions * ProjectedConditionOptions.NodesPerCondition > options.MaxImportedConditionNodes * 8L / 10;
/// Sets a mapping's claim when the node total stays within both caps; otherwise leaves it unchanged.
- public bool TryClaim(string connection, string mapping, int count, out long total)
+ /// The mapping has no committed set in this stream yet (N5: its claim may overlap held keys).
+ public bool TryClaim(string connection, string mapping, int count, bool unknown, out long total)
{
lock (_gate)
{
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
var had = entry.Claims.TryGetValue(mapping, out var previous);
+ var wasUnknown = entry.Unknown.Contains(mapping);
entry.Claims[mapping] = count;
+ if (unknown) entry.Unknown.Add(mapping); else entry.Unknown.Remove(mapping);
total = TotalLocked();
- if (!Over(total) || count <= previous) return true;
+ if (!Over(total) || (count <= previous && unknown == wasUnknown)) return true;
if (had) entry.Claims[mapping] = previous; else entry.Claims.Remove(mapping);
+ if (wasUnknown) entry.Unknown.Add(mapping); else entry.Unknown.Remove(mapping);
return false;
}
}
+ /// The swap: the mapping's committed count (≤ its admitted total), now a known claim. Never refused.
+ public void Commit(string connection, string mapping, int count)
+ {
+ lock (_gate)
+ {
+ if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
+ entry.Claims[mapping] = count;
+ entry.Unknown.Remove(mapping);
+ }
+ }
+
public void Release(string connection, string mapping)
{
- lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Remove(mapping);
+ lock (_gate) if (_connections.TryGetValue(connection, out var entry)) { entry.Claims.Remove(mapping); entry.Unknown.Remove(mapping); }
}
public void ResetClaims(string connection)
{
- lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Clear();
+ lock (_gate) if (_connections.TryGetValue(connection, out var entry)) { entry.Claims.Clear(); entry.Unknown.Clear(); }
}
- public void SetMaterialised(string connection, int count)
+ ///
+ /// Records what a connection holds. #931 N5: returns false when the node total is now over a host cap — materialising
+ /// is never refused here (the keys were admitted by their claims; growth is bounded by Σ MaxConditions), so the caller
+ /// only reports it.
+ ///
+ public bool SetMaterialised(string connection, int count, int unlisted = 0)
{
lock (_gate)
{
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
entry.Materialised = count;
- if (count == 0 && entry.Claims.Count == 0) _connections.Remove(connection);
+ entry.Unlisted = Math.Min(unlisted, count);
+ if (count == 0 && entry.Claims.Count == 0) { _connections.Remove(connection); return true; }
+ return !Over(TotalLocked());
}
}
+
+ /// The node-wide condition cap implied by the node and byte caps (for diagnostics).
+ public long ConditionLimit => Math.Min(options.MaxImportedConditionNodes / ProjectedConditionOptions.NodesPerCondition,
+ options.MaxImportedConditionBytes / ProjectedConditionOptions.BytesPerCondition);
}
// -----------------------------------------------------------------------------------------------------------------
@@ -124,8 +167,23 @@ public sealed partial class ProjectedConditionAccess
public ulong? Handle { get; set; }
public DataItemHandle? ItemHandle { get; set; }
public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending;
- /// The origin refused the item (or its metadata failed): nothing more arrives on this stream.
+ /// The origin refused the item (or its metadata failed): nothing more arrives for it until an in-stream retry.
public bool Refused { get; set; }
+ /// #930: the status of the last refusal (item ack or root metadata); null when not refused.
+ public DataItemStatus? Refusal { get; set; } // written under _statusGate (MarkRefused / retry), read there by Capture
+ /// #930: the command whose ack belongs to the mapping's current item ("open", then "retry-…").
+ public string CommandId { get; set; } = "open";
+ /// #930: when the next in-stream retry (or, while , the retry's snapshot deadline) is due.
+ public DateTimeOffset? RetryDue { get; set; }
+ /// #930: a re-added item awaits its ack / snapshot.
+ public bool Retrying { get; set; }
+ /// #930: consecutive in-stream retries (reset by a completed snapshot); drives the backoff.
+ public int Retries { get; set; }
+ /// A4 diagnostics: the last count the origin reported or listed (a snapshot total, or the committed set).
+ public int ObservedField;
+ public int Observed { get => Volatile.Read(ref ObservedField); set => Volatile.Write(ref ObservedField, value); }
+ /// A4: the consumer conditions.items gauge counts this mapping's open item.
+ public bool ItemCounted { get; set; }
/// The mapping's committed complete set in this stream (null until its first snapshot completes).
public ConditionSet? Live { get; set; }
/// Review r1 B1: a (re-)snapshot in progress, swapped in only at snapshot_complete.
@@ -153,7 +211,17 @@ public sealed partial class ProjectedConditionAccess
private ITimer? _stale;
private long _staleGeneration;
private int _barriers;
- private int _consecutiveRetries;
+ /// #931 N4: consecutive streams that ended before their barrier (reconnect backoff).
+ private int _failedStreams;
+ /// #930 N2: the mappings that were not known at the last barrier (null before the first); an incomplete barrier
+ /// with the SAME set sends no RefreshRequired — the clients were already told.
+ private HashSet? _lastIncomplete;
+ /// A4 diagnostics: materialised keys whose last record had state_known = false.
+ private readonly HashSet _unknownKeys = new(StringComparer.Ordinal);
+ private int _unknownCount;
+ private long _snapshotAtTicks;
+ private int _streamOpen;
+ private int _unlisted;
public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature,
ConnectionRunner? predecessor)
@@ -168,6 +236,29 @@ public sealed partial class ProjectedConditionAccess
/// A3b: the serving identity of the CURRENT condition stream (null while no stream is open).
public ServingIdentity? Serving => Volatile.Read(ref _serving);
+ /// A4 diagnostics (any thread): stream state, last barrier time, materialised / state-unknown counts, mappings.
+ public (string State, DateTime? SnapshotAt, int Materialised, int Unknown, ConditionMappingDiagnostics[] Mappings) Capture()
+ {
+ MappingState[] states;
+ ConditionMappingDiagnostics[] rows;
+ lock (_statusGate)
+ {
+ states = _states;
+ rows = states.Select(x => new ConditionMappingDiagnostics(x.MappingId, x.Status.ToString(), Volatile.Read(ref x.ObservedField),
+ x.Placement.Mapping.MaxConditions, x.Refusal?.ToString())).ToArray();
+ }
+ var state = Volatile.Read(ref _streamOpen) == 0 ? "connecting"
+ : states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting) && !BarrierThisStream
+ ? "snapshotting" : "live";
+ var ticks = Interlocked.Read(ref _snapshotAtTicks);
+ return (state, ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc), Volatile.Read(ref _materialisedCount),
+ Volatile.Read(ref _unknownCount), rows);
+ }
+
+ private volatile bool _barrierThisStream;
+ private bool BarrierThisStream => _barrierThisStream;
+ private int _materialisedCount;
+
/// Completes once the loop ended and (for a removing stop) its conditions were removed.
public Task Stopped => _stopped;
@@ -196,6 +287,11 @@ public sealed partial class ProjectedConditionAccess
try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); }
_materialised = previous._materialised;
previous._materialised = new HashSet(StringComparer.Ordinal);
+ _unknownKeys.UnionWith(previous._unknownKeys);
+ _unknownKeys.IntersectWith(_materialised);
+ previous._unknownKeys.Clear();
+ Volatile.Write(ref _materialisedCount, _materialised.Count);
+ Volatile.Write(ref _unknownCount, _unknownKeys.Count);
_predecessor = null;
}
@@ -212,6 +308,9 @@ public sealed partial class ProjectedConditionAccess
var keys = _materialised.ToArray();
if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys);
_materialised.Clear();
+ _unknownKeys.Clear();
+ Volatile.Write(ref _materialisedCount, 0);
+ Volatile.Write(ref _unknownCount, 0);
_owner._ledger.ResetClaims(ConnectionId);
_owner._ledger.SetMaterialised(ConnectionId, 0);
}, TaskScheduler.Default);
@@ -223,21 +322,34 @@ public sealed partial class ProjectedConditionAccess
while (!ct.IsCancellationRequested)
{
epoch++;
+ var barriers = Barriers;
try { await RunStreamAsync(epoch, ct).ConfigureAwait(false); }
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
catch (Exception ex)
{
- _owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", ConnectionId);
+ if (_failedStreams == 0) _owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", ConnectionId);
+ else _owner._log.LogDebug(ex, "Imported conditions: stream for connection {Connection} ended again ({Failures} in a row)", ConnectionId, _failedStreams + 1);
}
- finally { Volatile.Write(ref _serving, null); }
+ finally { Volatile.Write(ref _serving, null); Volatile.Write(ref _streamOpen, 0); }
// §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead.
ArmStale();
- OtOpcUaTelemetry.DataConnConditionResyncs.Add(1);
- try { await Task.Delay(_owner._options.ReconnectDelay, _owner._clock, ct).ConfigureAwait(false); }
+ _owner.Diagnostics.ConsumerResync(ConnectionId);
+ // #931 N4: a stream that never reached its barrier (metadata failing for every mapping, no Primary during a
+ // failover) backs off exponentially up to MaxReconnectDelay instead of looping at ReconnectDelay.
+ _failedStreams = Barriers > barriers ? 0 : _failedStreams + 1;
+ try { await Task.Delay(ReconnectBackoff(_owner._options, _failedStreams), _owner._clock, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
}
}
+ /// #931 N4: ReconnectDelay × 2^(failures − 1), capped at MaxReconnectDelay (never below ReconnectDelay).
+ internal static TimeSpan ReconnectBackoff(ProjectedConditionOptions options, int failures)
+ {
+ if (failures <= 1) return options.ReconnectDelay;
+ var ticks = options.ReconnectDelay.Ticks * (double)(1L << Math.Min(failures - 1, 20));
+ return TimeSpan.FromTicks((long)Math.Max(options.ReconnectDelay.Ticks, Math.Min(ticks, options.MaxReconnectDelay.Ticks)));
+ }
+
private void ArmStale()
{
lock (_staleGate)
@@ -273,29 +385,7 @@ public sealed partial class ProjectedConditionAccess
// The remote root's origin subject: placement addresses are made relative to it (SourceName, folder subject).
// S6: a root whose metadata fails is Unavailable (its item is not opened — a root item without the origin's own
// view is refused, and placements made relative to a missing root subject would be wrong).
- try
- {
- var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, states.Length), 1024 * 1024);
- var metadata = await connection.GetMetadataAsync(new MetadataRequest(states.Select(x => x.Root).ToArray(), budget), token)
- .ConfigureAwait(false);
- for (var i = 0; i < states.Length; i++)
- {
- if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root })
- {
- states[i].RootSubject = root.View.Subject;
- states[i].RootView = root.View;
- continue;
- }
- MarkRefused(states[i]);
- _owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried on a new stream",
- states[i].MappingId, i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable);
- }
- }
- catch (Exception ex) when (ex is not OperationCanceledException)
- {
- foreach (var state in states) MarkRefused(state);
- _owner._log.LogWarning(ex, "Imported conditions: connection {Connection} root metadata failed — every mapping Unavailable", ConnectionId);
- }
+ await ResolveRootsAsync(connection, states, token).ConfigureAwait(false);
var open = states.Where(x => !x.Refused).ToArray();
if (open.Length == 0) throw new InvalidOperationException("No condition-bearing mapping root resolved.");
@@ -307,24 +397,25 @@ public sealed partial class ProjectedConditionAccess
if (serving is not null && !string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"Condition stream served by a {serving.Role} ({serving.NodeId}); conditions are pinned to the Primary.");
Volatile.Write(ref _serving, serving);
+ _barrierThisStream = false;
+ Volatile.Write(ref _streamOpen, 1);
_owner._log.LogInformation("Imported conditions: stream {Epoch} for connection {Connection} opened ({Mappings} mapping(s), serving {Serving})",
epoch, ConnectionId, open.Length, Serving?.NodeId ?? "(no provenance)");
var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N");
- var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
- var items = open.Select(x => new DataSubscriptionItem(x.MappingId, x.RootView ?? x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray();
- await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false,
- TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false);
-
+ var items = open.Select(Item).ToArray();
var snapshotTimeout = TimeSpan.FromMilliseconds(Math.Max(1, states.Max(x => x.Placement.Mapping.ConditionSnapshotTimeoutMilliseconds)));
var barrierPassed = false;
var timeout = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
- using var barrierTimer = _owner._clock.CreateTimer(_ => timeout.TrySetResult(), null, snapshotTimeout, Timeout.InfiniteTimeSpan);
- // B2: a mapping still Unavailable a bounded wait after the barrier ends the stream (a fresh stream retries it).
+ // #930: one timer for the earliest in-stream retry due (re-armed when that changes); its signal is a fresh TCS.
var retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
ITimer? retryTimer = null;
+ DateTimeOffset? retryArmedFor = null;
var context = new StreamContext(subscription, subscriptionId, epoch, token);
try
{
+ await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false,
+ TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false);
+ using var barrierTimer = _owner._clock.CreateTimer(_ => timeout.TrySetResult(), null, snapshotTimeout, Timeout.InfiniteTimeSpan);
await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token);
Task? next = null;
while (true)
@@ -340,24 +431,32 @@ public sealed partial class ProjectedConditionAccess
}
if (barrierPassed)
{
- var unavailable = states.Any(x => x.Status == ProjectedConditionMappingStatus.Unavailable);
- if (retry.Task.IsCompleted && unavailable)
+ // #930 (N2/N3): an Unavailable or over-capacity mapping is retried ON THIS STREAM (its item re-added) on
+ // its own backoff — the stream is no longer ended for it, so the healthy mappings are not re-snapshotted
+ // and clients are not sent RefreshRequired every cycle.
+ if (retry.Task.IsCompleted)
{
- _consecutiveRetries++;
- _owner._log.LogWarning("Imported conditions: connection {Connection} mapping(s) {Mappings} still Unavailable — ending the stream to retry",
- ConnectionId, string.Join(", ", states.Where(x => x.Status == ProjectedConditionMappingStatus.Unavailable).Select(x => x.MappingId)));
- return;
+ retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ retryArmedFor = null;
+ await RetryDueAsync(connection, states, context, snapshotTimeout).ConfigureAwait(false);
}
- if (!unavailable)
+ foreach (var s in states)
+ if (s.RetryDue is null && s.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity)
+ ScheduleRetry(s, snapshotTimeout);
+ var due = states.Where(x => x.RetryDue is not null).Select(x => x.RetryDue!.Value).DefaultIfEmpty().Min();
+ DateTimeOffset? wanted = states.Any(x => x.RetryDue is not null) ? due : null;
+ if (wanted != retryArmedFor)
{
- retryTimer?.Dispose(); retryTimer = null; _consecutiveRetries = 0;
+ retryTimer?.Dispose(); retryTimer = null;
if (retry.Task.IsCompleted) retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
- }
- else if (retryTimer is null)
- {
- var wait = snapshotTimeout * Math.Min(1 << Math.Min(_consecutiveRetries, 3), 8);
- var signal = retry;
- retryTimer = _owner._clock.CreateTimer(_ => signal.TrySetResult(), null, wait, Timeout.InfiniteTimeSpan);
+ retryArmedFor = wanted;
+ if (wanted is { } at)
+ {
+ var signal = retry;
+ var wait = at - _owner._clock.GetUtcNow();
+ retryTimer = _owner._clock.CreateTimer(_ => signal.TrySetResult(), null, wait > TimeSpan.Zero ? wait : TimeSpan.Zero,
+ Timeout.InfiniteTimeSpan);
+ }
}
}
next ??= frames.MoveNextAsync().AsTask();
@@ -370,24 +469,155 @@ public sealed partial class ProjectedConditionAccess
next = null;
var outcome = await ProcessAsync(frames.Current, states, context).ConfigureAwait(false);
if (!barrierPassed) { barrierPassed = TryPassBarrier(states, timedOut: false); continue; }
- if (outcome.Changed.Count > 0 || outcome.Reconcile) Reconcile(states, outcome.Changed, outcome.Reconcile);
- if (outcome.Refresh) _owner._sink()?.RequireRefresh(ConnectionId);
+ var removed = 0;
+ if (outcome.Changed.Count > 0 || outcome.Reconcile) removed = Reconcile(states, outcome.Changed, outcome.Reconcile);
+ // #931 N7: a removal already sent RefreshRequired to every item that held a removed condition (the sink's
+ // §5.2 "removal + RefreshRequired"); a capacity reset asks again only when it removed nothing.
+ if (outcome.Refresh && removed == 0) RequireRefresh();
}
}
- finally { retryTimer?.Dispose(); }
+ finally
+ {
+ retryTimer?.Dispose();
+ foreach (var s in states) CountItem(s, open: false);
+ }
+ }
+
+ private static DataSubscriptionItem Item(MappingState state) =>
+ new(state.MappingId, state.RootView ?? state.Root, new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null),
+ new DataConditionScope(IncludeInfo: true));
+
+ /// Resolves the roots of (metadata); a root that fails is refused (Unavailable).
+ private async Task ResolveRootsAsync(IDataConnection connection, MappingState[] targets, CancellationToken token)
+ {
+ if (targets.Length == 0) return;
+ try
+ {
+ var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, targets.Length), 1024 * 1024);
+ var metadata = await connection.GetMetadataAsync(new MetadataRequest(targets.Select(x => x.Root).ToArray(), budget), token)
+ .ConfigureAwait(false);
+ for (var i = 0; i < targets.Length; i++)
+ {
+ if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root })
+ {
+ targets[i].RootSubject = root.View.Subject;
+ targets[i].RootView = root.View;
+ continue;
+ }
+ var status = i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable;
+ MarkRefused(targets[i], status);
+ _owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried in-stream",
+ targets[i].MappingId, status);
+ }
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ foreach (var state in targets) MarkRefused(state, DataItemStatus.Unavailable);
+ _owner._log.LogWarning(ex, "Imported conditions: connection {Connection} root metadata failed — {Count} mapping(s) Unavailable",
+ ConnectionId, targets.Length);
+ }
+ }
+
+ /// #930: whether a refusal is definitive (the origin will keep saying no until its configuration changes).
+ private static bool Definitive(MappingState state) =>
+ state.Status == ProjectedConditionMappingStatus.ConditionCapacity
+ || state.Refusal is DataItemStatus.Denied or DataItemStatus.NotFound or DataItemStatus.Unsupported;
+
+ /// #930: when the mapping's next in-stream retry is due — long (and doubling ≤ 4×) for a definitive refusal or
+ /// ConditionCapacity, the snapshot timeout × 2ⁿ (≤ 8×) otherwise.
+ private void ScheduleRetry(MappingState state, TimeSpan snapshotTimeout)
+ {
+ var delay = Definitive(state)
+ ? _owner._options.LongRetryDelay * (1 << Math.Min(state.Retries, 2))
+ : snapshotTimeout * (1 << Math.Min(state.Retries, 3));
+ state.RetryDue = _owner._clock.GetUtcNow() + delay;
+ }
+
+ ///
+ /// #930: runs the in-stream retries that are due. A retry whose snapshot has not completed by its deadline becomes
+ /// Unavailable again (its claim released; a late completion of that item is still taken). A due Unavailable or
+ /// ConditionCapacity mapping has its root re-resolved when it never resolved, any still-open item removed, and its item
+ /// re-added with a fresh command id. While a retry runs the mapping is Pending — unknown, so nothing it might list is
+ /// removed or marked known-inactive meanwhile (§5.1 T2).
+ ///
+ private async Task RetryDueAsync(IDataConnection connection, MappingState[] states, StreamContext context, TimeSpan snapshotTimeout)
+ {
+ var now = _owner._clock.GetUtcNow();
+ var due = new List();
+ foreach (var state in states.Where(x => x.RetryDue is { } at && at <= now))
+ {
+ state.RetryDue = null;
+ if (state.Retrying)
+ {
+ state.Retrying = false;
+ if (state.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)
+ {
+ lock (_statusGate) state.Status = ProjectedConditionMappingStatus.Unavailable;
+ state.Buffer = null;
+ _owner._ledger.Release(ConnectionId, state.MappingId);
+ _owner._log.LogWarning("Imported conditions: mapping {Mapping} retry snapshot timed out — Unavailable", state.MappingId);
+ }
+ continue;
+ }
+ if (state.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity) due.Add(state);
+ }
+ if (due.Count == 0) return;
+ foreach (var state in due) state.Retries++;
+ await ResolveRootsAsync(connection, due.Where(x => x.RootView is null).ToArray(), context.Token).ConfigureAwait(false);
+ var ready = due.Where(x => x.RootView is not null).ToArray();
+ // An Unavailable mapping whose snapshot timed out still has its item open: remove it before re-adding (one per root).
+ var stillOpen = ready.Where(x => x.ItemHandle is not null).ToArray();
+ foreach (var state in stillOpen) CountItem(state, open: false);
+ if (stillOpen.Length > 0)
+ await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-retry-" + Guid.NewGuid().ToString("N"),
+ TimeSpan.FromSeconds(30), stillOpen.Select(x => x.ItemHandle!).ToArray()), context.Token).ConfigureAwait(false);
+ foreach (var state in ready)
+ {
+ lock (_statusGate)
+ {
+ state.Status = ProjectedConditionMappingStatus.Pending;
+ state.Refused = false; state.Refusal = null;
+ state.Handle = null; state.ItemHandle = null;
+ state.CommandId = "retry-" + state.MappingId + "-" + Guid.NewGuid().ToString("N");
+ }
+ state.Buffer = null;
+ state.Retrying = true;
+ state.RetryDue = _owner._clock.GetUtcNow() + snapshotTimeout;
+ _owner._log.LogInformation("Imported conditions: connection {Connection} mapping {Mapping} retried in-stream (attempt {Attempt})",
+ ConnectionId, state.MappingId, state.Retries);
+ await context.Subscription.SendAsync(new AddSubscriptionItems(context.SubscriptionId, context.Epoch, state.CommandId,
+ TimeSpan.FromSeconds(30), [Item(state)]), context.Token).ConfigureAwait(false);
+ }
+ }
+
+ private void CountItem(MappingState state, bool open)
+ {
+ if (state.ItemCounted == open) return;
+ state.ItemCounted = open;
+ DataConnectionConditionDiagnostics.CountItems(DataConnectionConditionDiagnostics.ConsumerSide, open ? 1 : -1);
+ }
+
+ private void RequireRefresh()
+ {
+ _owner.Diagnostics.ConsumerRefreshRequired(ConnectionId);
+ _owner._sink()?.RequireRefresh(ConnectionId);
}
private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token);
private sealed record FrameOutcome(HashSet Changed, bool Reconcile, bool Refresh);
- private void MarkRefused(MappingState state)
+ private void MarkRefused(MappingState state, DataItemStatus status)
{
lock (_statusGate)
{
state.Refused = true;
+ state.Refusal = status;
if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable;
}
+ state.Retrying = false;
+ state.RetryDue = null; // re-scheduled (with its backoff) once past the barrier
+ CountItem(state, open: false);
}
private bool TryPassBarrier(MappingState[] states, bool timedOut)
@@ -395,14 +625,24 @@ public sealed partial class ProjectedConditionAccess
lock (_statusGate)
if (states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) return false;
Interlocked.Increment(ref _barriers);
+ Interlocked.Exchange(ref _snapshotAtTicks, _owner._clock.GetUtcNow().UtcTicks);
+ _barrierThisStream = true;
DisarmStale();
- var incomplete = states.Any(x => !x.Known);
+ var incompleteSet = states.Where(x => !x.Known).Select(x => x.MappingId).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ var incomplete = incompleteSet.Count > 0;
+ // #930 N2: the same incomplete set as the last barrier ⇒ the clients were already told; a permanently refused
+ // mapping must not send RefreshRequired on every stream (it is retried in-stream now, but a stream can still end).
+ var alreadyTold = _lastIncomplete is { } last && last.SetEquals(incompleteSet);
+ _lastIncomplete = incompleteSet;
_owner._log.LogInformation("Imported conditions: connection {Connection} snapshot barrier passed ({Statuses}; {Records} record(s){TimedOut})",
ConnectionId, string.Join(", ", states.Select(x => x.MappingId + "=" + x.Status)), states.Where(x => x.Contributes).Sum(x => x.Live!.Records.Count),
timedOut ? "; snapshot timed out" : "");
Reconcile(states, states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal), full: true);
// S7: an incomplete (re)snapshot — a timeout OR a refused item — tells clients to refresh.
- if (incomplete) _owner._sink()?.RequireRefresh(ConnectionId);
+ if (incomplete && !alreadyTold) RequireRefresh();
+ else if (incomplete)
+ _owner._log.LogDebug("Imported conditions: connection {Connection} incomplete set unchanged ({Mappings}) — no RefreshRequired",
+ ConnectionId, string.Join(", ", incompleteSet));
return true;
}
@@ -416,14 +656,16 @@ public sealed partial class ProjectedConditionAccess
case DataSubscriptionAck ack:
foreach (var itemAck in ack.Items)
{
- var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId);
+ // #930: an ack belongs to the mapping's CURRENT command (the open, or its latest in-stream retry).
+ var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId && x.CommandId == ack.CommandId);
if (state is null) continue;
if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle)
{
lock (_statusGate) { state.Handle = handle.Handle; state.ItemHandle = handle; }
+ CountItem(state, open: true);
continue;
}
- MarkRefused(state);
+ MarkRefused(state, itemAck.Status);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} item refused by the origin ({Status}: {Diagnostic})",
state.MappingId, itemAck.Status, itemAck.Diagnostic);
}
@@ -436,13 +678,15 @@ public sealed partial class ProjectedConditionAccess
{
// A snapshot begin: decided before anything of it is materialised; buffered until snapshot_complete (B1),
// so the committed set (and what is materialised) is untouched while it streams.
- if (total > limit || !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, Math.Max(total, mapping.Live?.Records.Count ?? 0), out var after))
+ if (total > limit || !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, Math.Max(total, mapping.Live?.Records.Count ?? 0),
+ mapping.Live is null, out var after))
{
await ResetToCapacityAsync(mapping, total, total > limit ? "over its MaxConditions" : "would cross the host condition caps",
changed, context).ConfigureAwait(false);
reconcile = refresh = true;
break;
}
+ mapping.Observed = total;
if (_owner._ledger.HighWater(after))
_owner._log.LogWarning("Imported conditions: host condition budget above 80% ({Count} conditions)", after);
mapping.Buffer = new ConditionSet(total);
@@ -464,7 +708,7 @@ public sealed partial class ProjectedConditionAccess
string? over = null;
if (mapping.Buffer is { } buffer && buffer.Records.Count > Math.Min(buffer.Total, limit)) over = "listed more records than its snapshot total";
else if (mapping.Live is { } grown && grown.Records.Count > limit) over = "grew past its MaxConditions";
- else if (mapping.Live is not null && !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, mapping.Claim, out _)) over = "grew past the host condition caps";
+ else if (mapping.Live is not null && !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, mapping.Claim, false, out _)) over = "grew past the host condition caps";
if (over is not null)
{
await ResetToCapacityAsync(mapping, mapping.Claim, over, changed, context).ConfigureAwait(false);
@@ -480,7 +724,11 @@ public sealed partial class ProjectedConditionAccess
mapping.Live = done;
mapping.Buffer = null;
lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete;
- _owner._ledger.TryClaim(ConnectionId, mapping.MappingId, done.Records.Count, out _); // ≤ the admitted total
+ _owner._ledger.Commit(ConnectionId, mapping.MappingId, done.Records.Count); // ≤ the admitted total
+ // #930: a completed (re)snapshot ends any retry; the mapping is known again.
+ mapping.Retrying = false; mapping.Retries = 0; mapping.RetryDue = null; mapping.Refusal = null;
+ mapping.Observed = done.Records.Count;
+ _lastIncomplete?.Remove(mapping.MappingId);
reconcile = true;
}
break;
@@ -495,14 +743,22 @@ public sealed partial class ProjectedConditionAccess
if (mapping.Live is { } live) changed.UnionWith(live.Records.Keys);
mapping.Live = null;
mapping.Buffer = null;
+ mapping.Observed = observed;
+ // #930 N3: re-added in-stream on the long timer (ConditionCapacity is definitive), not left empty until the stream ends.
+ mapping.Retrying = false;
+ mapping.RetryDue = null;
_owner._ledger.Release(ConnectionId, mapping.MappingId);
- OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
+ _owner.Diagnostics.ConsumerCapacityRejection(ConnectionId);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} ({Count} conditions) {Reason} (MaxConditions {Max}) — Unavailable(ConditionCapacity)",
mapping.MappingId, observed, reason, mapping.Placement.Mapping.MaxConditions);
// §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing).
if (mapping.ItemHandle is { } handle)
+ {
+ lock (_statusGate) { mapping.Handle = null; mapping.ItemHandle = null; }
+ CountItem(mapping, open: false);
await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-" + mapping.MappingId,
TimeSpan.FromSeconds(30), [handle]), context.Token).ConfigureAwait(false);
+ }
}
///
@@ -511,12 +767,14 @@ public sealed partial class ProjectedConditionAccess
/// A key no contributing mapping lists is removed only when every mapping's set is known; while any is unknown
/// (Unavailable, not yet complete) it is kept with BadNoCommunication (unknown ≠ gone, §5.1 T2, B2).
///
- private void Reconcile(MappingState[] states, HashSet keys, bool full)
+ /// How many conditions were removed (#931 N7: a removal already carries RefreshRequired to their holders).
+ private int Reconcile(MappingState[] states, HashSet keys, bool full)
{
- if (_owner._sink() is not { } sink) return;
+ if (_owner._sink() is not { } sink) return 0;
+ HashSet? listed = null;
if (full)
{
- var listed = states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal);
+ listed = states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal);
foreach (var key in _materialised) if (!listed.Contains(key)) keys.Add(key);
}
var unknown = states.Any(x => !x.Known);
@@ -526,18 +784,31 @@ public sealed partial class ProjectedConditionAccess
foreach (var key in keys)
{
var update = Merge(states, key);
- if (update is not null) { updates.Add(update); _materialised.Add(key); continue; }
+ if (update is not null)
+ {
+ updates.Add(update); _materialised.Add(key);
+ if (update.State.StateKnown) _unknownKeys.Remove(key); else _unknownKeys.Add(key);
+ continue;
+ }
if (!_materialised.Contains(key)) continue;
if (unknown) stale.Add(key);
- else { _materialised.Remove(key); removals.Add(key); }
+ else { _materialised.Remove(key); _unknownKeys.Remove(key); removals.Add(key); }
}
- if (removals.Count > 0) sink.RemoveConditions(ConnectionId, removals);
+ Volatile.Write(ref _unknownCount, _unknownKeys.Count);
+ Volatile.Write(ref _materialisedCount, _materialised.Count);
+ if (removals.Count > 0) { sink.RemoveConditions(ConnectionId, removals); _owner.Diagnostics.ConsumerRefreshRequired(ConnectionId); }
if (stale.Count > 0) sink.MarkConditionsStale(ConnectionId, stale);
if (updates.Count > 0) sink.ApplyConditions(updates);
- _owner._ledger.SetMaterialised(ConnectionId, _materialised.Count);
+ // #931 N5: the held keys no contributing mapping lists are charged on top of the claims (counted on a full re-diff).
+ if (full) _unlisted = _materialised.Count(k => !listed!.Contains(k));
+ else _unlisted = Math.Min(_unlisted, _materialised.Count);
+ if (!_owner._ledger.SetMaterialised(ConnectionId, _materialised.Count, _unlisted))
+ _owner._log.LogWarning("Imported conditions: connection {Connection} holds {Count} condition(s) and the node is over its host condition caps",
+ ConnectionId, _materialised.Count);
if (updates.Count + removals.Count + stale.Count > 0)
_owner._log.LogDebug("Imported conditions: connection {Connection} applied {Updates} update(s), {Removals} removal(s), {Stale} kept stale",
ConnectionId, updates.Count, removals.Count, stale.Count);
+ return removals.Count;
}
/// One key across the connection's complete mappings: placements (primary first), latest record, SourceName.
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs
index b3a43ccda..b52377b1e 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs
@@ -1,5 +1,7 @@
+using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
+using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
@@ -60,6 +62,18 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC
/// §9.3 L2: the host byte cap = measured per-condition bytes × 2,500 (the host condition cap).
public const long DefaultMaxImportedConditionBytes = BytesPerCondition * 2_500;
+ ///
+ /// #930 (N2/N3): the base in-stream retry delay of a mapping the origin refused DEFINITIVELY (Denied,
+ /// NotFound, Unsupported, for its item or its root metadata) or that is over capacity
+ /// (); doubled per consecutive retry up to 4×. A transient
+ /// refusal or a snapshot timeout retries after ConditionSnapshotTimeoutMilliseconds × 2ⁿ (≤ 8×). Either way the
+ /// mapping's item is re-added on the OPEN stream — the healthy mappings are never re-snapshotted for it.
+ ///
+ public TimeSpan LongRetryDelay { get; init; } = TimeSpan.FromMinutes(5);
+
+ /// #931 (N4): the ceiling of the exponential reconnect backoff after streams that end before their barrier.
+ public TimeSpan MaxReconnectDelay { get; init; } = TimeSpan.FromSeconds(60);
+
public static ProjectedConditionOptions Default { get; } =
new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1));
}
@@ -97,7 +111,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
private readonly ProjectedConditionOptions _options;
private readonly ILogger _log;
private readonly object _gate = new();
- private readonly Dictionary _runners = new(StringComparer.OrdinalIgnoreCase);
+ /// Mutated under only; concurrent so a method call reads its runner's Serving without
+ /// taking (#931 N6: _gate can sit behind a stop that waits on _staleGate).
+ private readonly ConcurrentDictionary _runners = new(StringComparer.OrdinalIgnoreCase);
/// Review r1 S3/S4: a stopped runner's completion (its loop AND its removal) per connection; the next runner of
/// that connection awaits it before opening a stream or taking the materialised set, so the two never overlap.
private readonly Dictionary _stopping = new(StringComparer.OrdinalIgnoreCase);
@@ -109,9 +125,10 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
public ProjectedConditionAccess(IProjectedConditionMappings mappings, IGrpcDataAdapterConnectionSource connections,
DataOperationPolicy policy, Func? sink, TimeProvider clock, ProjectedConditionOptions? options = null,
- ILogger? logger = null)
+ ILogger? logger = null, DataConnectionConditionDiagnostics? diagnostics = null)
{
_mappings = mappings ?? throw new ArgumentNullException(nameof(mappings));
+ Diagnostics = diagnostics ?? new DataConnectionConditionDiagnostics();
_connections = connections ?? throw new ArgumentNullException(nameof(connections));
_policy = policy ?? throw new ArgumentNullException(nameof(policy));
_sink = sink ?? (() => Sink);
@@ -120,6 +137,24 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
_log = logger ?? NullLogger.Instance;
_ledger = new ConditionLedger(_options);
_mappings.Changed += OnMappingsChanged;
+ Diagnostics.AttachConsumer(CaptureConsumer);
+ }
+
+ /// A4: the diagnostics/metrics this runtime reports into (shared with the diagnostics readers).
+ public DataConnectionConditionDiagnostics Diagnostics { get; }
+
+ /// A4: one connection's consumer condition state; null when no current mapping of it is condition-bearing.
+ private DataConnectionConditionDiagnostics.ConsumerState? CaptureConsumer(string connectionId)
+ {
+ var mappings = _mappings.Current.Where(x => string.Equals(x.Mapping.DataConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)
+ && x.Authority.IsActive && IsConditionBearing(x.Mapping)).ToArray();
+ if (mappings.Length == 0) return null;
+ // #931 N6 spirit: a diagnostics poll never takes _gate either.
+ if (!_runners.TryGetValue(connectionId, out var runner))
+ return new("idle", null, 0, 0, OrderMappings(mappings).Select(x => new ConditionMappingDiagnostics(x.Mapping.RemoteNamespaceMappingId,
+ ProjectedConditionMappingStatus.Pending.ToString(), 0, x.Mapping.MaxConditions)).ToArray(), _ledger.Total, _ledger.ConditionLimit);
+ var (state, snapshotAt, materialised, unknown, rows) = runner.Capture();
+ return new(state, snapshotAt, materialised, unknown, rows, _ledger.Total, _ledger.ConditionLimit);
}
/// The node manager the host binds once the server is up (used when no sink delegate was supplied).
@@ -222,7 +257,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
if (_disposed || _demand > 0) return;
stopped = _runners.Values.ToList();
_runners.Clear();
- foreach (var runner in stopped) { runner.Stop(removeConditions: true); _stopping[runner.ConnectionId] = runner; }
+ foreach (var runner in stopped) { runner.Stop(removeConditions: true); Park(runner); }
}
}
@@ -245,9 +280,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
.ToDictionary(x => x.Key, x => OrderMappings(x).ToArray(), StringComparer.OrdinalIgnoreCase);
foreach (var id in _runners.Keys.Where(id => !byConnection.ContainsKey(id)).ToList())
{
- _runners.Remove(id, out var gone);
+ _runners.TryRemove(id, out var gone);
gone!.Stop(removeConditions: true);
- _stopping[id] = gone;
+ Park(gone);
}
foreach (var (id, mappings) in byConnection)
{
@@ -267,6 +302,27 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
}
}
+ ///
+ /// Under _gate: parks a removing runner so the connection's next runner awaits its removal (S3/S4). #931 N8: the entry
+ /// is dropped once that removal has finished — a removing stop hands over an empty set, so nothing is left to wait for,
+ /// and a connection that never returns no longer pins its last runner.
+ ///
+ private void Park(ConnectionRunner runner)
+ {
+ _stopping[runner.ConnectionId] = runner;
+ runner.Stopped.ContinueWith(_ =>
+ {
+ lock (_gate)
+ if (_stopping.TryGetValue(runner.ConnectionId, out var parked) && ReferenceEquals(parked, runner)) _stopping.Remove(runner.ConnectionId);
+ }, TaskScheduler.Default);
+ }
+
+ /// Test observation (#931 N8): whether a stopped runner of the connection is still parked.
+ public bool IsParked(string connectionId)
+ {
+ lock (_gate) return _stopping.ContainsKey(connectionId);
+ }
+
/// §5.2: Raw mappings before UNS, then mapping id ordinal (deployed configuration only).
internal static IEnumerable OrderMappings(IEnumerable mappings) =>
mappings.OrderBy(x => x.Mapping.Realm == DataRealm.Raw ? 0 : 1)
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs
index f1cf33605..3e74d18c4 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs
@@ -2998,7 +2998,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts(),
_catalogCoordinator?.ProjectedMappings?.CaptureDroppedByConnection()),
DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations,
- OriginHistory: _dataConnections?.HistoryDiagnostics?.CaptureOrigin());
+ OriginHistory: _dataConnections?.HistoryDiagnostics?.CaptureOrigin(),
+ OriginConditions: _dataConnections?.ConditionDiagnostics?.CaptureOrigin());
Sender.Tell(snapshot);
}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs
index 4f8d42454..79ac37771 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs
@@ -253,7 +253,9 @@ public sealed class GrpcDataProjectedConditionAccessTests
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)");
+ // #931 N7: the removal itself carries RefreshRequired to the holders (the sink's §5.2 "removal + RefreshRequired"), so
+ // the reset does not ask a second time.
+ f.Sink.RefreshRequired.ShouldBe(refreshes, "one RefreshRequired per capacity reset: the removal's");
}
private static Fixture TimedFixture(int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
@@ -316,7 +318,17 @@ public sealed class GrpcDataProjectedConditionAccessTests
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");
+ // #930 N2: the retry is IN-STREAM (the item re-added after the bounded wait) — the stream is not ended for it.
+ await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
+ stream.AckAdd("map-a");
+ stream.Begin("map-a", total: 1);
+ 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(300))).ShouldBeNull("no new stream: map-b is never re-snapshotted for map-a");
+ f.Sink.Applied.Count(u => u.State.ConditionKey == Key("x")).ShouldBe(1, "the healthy mapping's condition is not re-applied");
+ f.Sink.RefreshRequired.ShouldBe(1, "a recovered mapping needs no second RefreshRequired");
}
[Fact]
@@ -503,6 +515,162 @@ public sealed class GrpcDataProjectedConditionAccessTests
DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1));
}
+ // ---------------------------------------------------------------------------------------------------------------------
+ // #930 (N2/N3) and #931 (N4/N5/N7/N8) — A4
+ // ---------------------------------------------------------------------------------------------------------------------
+
+ private static Fixture LongRetryFixture(TimeSpan longRetry, int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
+ {
+ var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = longRetry }, mappings);
+ foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs;
+ return f;
+ }
+
+ [Fact]
+ public async Task N2_a_definitive_refusal_waits_the_long_backoff_on_the_open_stream_never_storming_the_healthy_mapping()
+ {
+ await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 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(DataItemStatus.Denied, "map-a");
+ 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);
+ // A transient refusal would be retried after the 300 ms snapshot timeout (and, before #930, the stream ended for it).
+ (await f.TryNextStreamAsync(TimeSpan.FromSeconds(1.5))).ShouldBeNull("the stream is kept");
+ stream.AddsOf("map-a").ShouldBe(0, "Denied is definitive: the long backoff, not the snapshot timeout");
+ f.Sink.Applied.Count.ShouldBe(1, "map-b is not re-snapshotted");
+ f.Sink.RefreshRequired.ShouldBe(1);
+ f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
+ }
+
+ [Fact]
+ public async Task N2_an_unchanged_incomplete_set_on_a_new_stream_sends_no_second_RefreshRequired_a_changed_one_does()
+ {
+ await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
+ using var demand = f.Access.AcquireEventDemand(null);
+ var first = await f.NextStreamAsync();
+ first.Ack(DataItemStatus.Denied, "map-a");
+ first.Begin("map-b", total: 1);
+ first.Records("map-b", Record(Key("x"), 3));
+ first.Complete("map-b");
+ await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 1);
+ f.Sink.RefreshRequired.ShouldBe(1);
+ first.End();
+
+ var second = await f.NextStreamAsync();
+ second.Ack(DataItemStatus.Denied, "map-a"); // still refused: the same incomplete set
+ second.Begin("map-b", total: 1);
+ second.SnapshotRecords("map-b", Record(Key("x"), 4));
+ second.Complete("map-b");
+ await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 2);
+ f.Sink.RefreshRequired.ShouldBe(1, "the clients were already told about map-a");
+ second.End();
+
+ var third = await f.NextStreamAsync();
+ third.Ack(DataItemStatus.Denied, "map-a", "map-b"); // a changed incomplete set ⇒ told again (positive control)
+ await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 3);
+ f.Sink.RefreshRequired.ShouldBe(2);
+ }
+
+ [Fact]
+ public async Task N3_a_ConditionCapacity_mapping_is_re_added_in_stream_on_the_long_timer_and_recovers_when_under_its_limit()
+ {
+ await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(400), 30_000, ("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10));
+ using var demand = f.Access.AcquireEventDemand(null);
+ var stream = await f.NextStreamAsync();
+ stream.Ack();
+ stream.Begin("map-a", total: 3); // over its MaxConditions
+ stream.Begin("map-b", total: 1);
+ stream.SnapshotRecords("map-b", Record(Key("x"), 3));
+ stream.Complete("map-b");
+ await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
+ f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
+
+ await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
+ stream.AckAdd("map-a");
+ stream.Begin("map-a", total: 2); // the origin dropped back under the limit
+ stream.SnapshotRecords("map-a", Record(Key("y"), 3), Record(Key("z"), 3));
+ stream.Complete("map-a");
+ await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")) && f.Sink.Live.Contains(Key("z")));
+ f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
+ (await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(300))).ShouldBeNull("recovered on the open stream");
+ }
+
+ [Fact]
+ public async Task N3_a_retry_still_over_capacity_stays_ConditionCapacity_and_is_retried_again_never_removing_what_another_mapping_lists()
+ {
+ await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(300), 30_000, ("map-a", DataRealm.Raw, 1), ("map-b", DataRealm.Raw, 10));
+ using var demand = f.Access.AcquireEventDemand(null);
+ var stream = await f.NextStreamAsync();
+ stream.Ack();
+ stream.Begin("map-a", total: 2);
+ stream.Begin("map-b", total: 1);
+ stream.SnapshotRecords("map-b", Record(Key("x"), 3));
+ stream.Complete("map-b");
+ await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
+ stream.AckAdd("map-a");
+ stream.Begin("map-a", total: 2);
+ await f.WaitAsync(() => stream.AddsOf("map-a") == 2); // backoff doubled, still in-stream
+ f.Sink.Removed.ShouldBeEmpty("map-b's key is never removed by map-a's retries (T2)");
+ f.Sink.Live.ShouldBe([Key("x")]);
+ }
+
+ [Fact]
+ public async Task N4_streams_that_never_reach_a_barrier_back_off_exponentially()
+ {
+ var options = Fixture.DefaultOptions with { MaxReconnectDelay = TimeSpan.FromMilliseconds(400) };
+ await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10));
+ f.Connections.MetadataFails.Add(0); // every mapping's root fails ⇒ every stream ends before a barrier
+ using var demand = f.Access.AcquireEventDemand(null);
+ await Task.Delay(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
+ var calls = Volatile.Read(ref f.Connections.MetadataCalls);
+ calls.ShouldBeGreaterThan(2, "it keeps retrying");
+ // Fixed 50 ms reconnects would make ~40 attempts in 2 s; 50, 100, 200, 400, 400… makes ≤ ~8.
+ calls.ShouldBeLessThan(12);
+ }
+
+ [Fact]
+ public async Task N5_held_stale_keys_are_charged_beside_a_known_mappings_new_claim_but_overlap_an_unknown_mappings()
+ {
+ var options = Fixture.DefaultOptions with { MaxImportedConditionNodes = 3 * 49 }; // 3 conditions on the node
+ await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
+ foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = 300;
+ f.Mappings.Current[0].Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
+ f.Mappings.Current[1].Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
+ using var demand = f.Access.AcquireEventDemand(null);
+ var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("z"), 3)]));
+ await f.WaitAsync(() => f.Sink.Live.Count == 3);
+ first.End();
+
+ var second = await f.NextStreamAsync();
+ second.Ack();
+ second.Begin("map-b", total: 1);
+ second.SnapshotRecords("map-b", Record(Key("z"), 4));
+ second.Complete("map-b"); // map-a never answers: x, y held stale (unlisted)
+ await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
+ // map-b (known) now re-lists z plus a new w: 4 conditions would be held — over the 3-condition cap.
+ second.Begin("map-b", total: 2);
+ await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-b"] == ProjectedConditionMappingStatus.ConditionCapacity);
+ f.Sink.Live.ShouldNotContain(Key("w"));
+ f.Sink.Removed.ShouldBeEmpty("map-a is unknown: nothing is removed (T2)");
+ }
+
+ [Fact]
+ public async Task N8_a_stopped_runner_is_not_kept_parked_after_its_removal_finished()
+ {
+ await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
+ 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);
+ demand.Dispose();
+ await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1);
+ await f.WaitAsync(() => !f.Access.IsParked(Connection));
+ f.Access.RunnerReference(Connection).ShouldBeNull("a connection that never returns pins no runner");
+ stream.Disposed.ShouldBeTrue();
+ }
+
private sealed class Fixture : IAsyncDisposable
{
internal static readonly DataView DefaultRawPlacement =
@@ -637,6 +805,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
public Channel Streams { get; } = Channel.CreateUnbounded();
/// Metadata answers Bad for these root indexes (deployed order).
public HashSet MetadataFails { get; } = [];
+ /// #931 N4: metadata requests made (one per stream attempt, plus in-stream root retries).
+ public int MetadataCalls;
/// The serving roles of the next streams (Primary when empty).
public Queue Roles { get; } = new();
public int PrimarySubscribes;
@@ -664,7 +834,7 @@ public sealed class GrpcDataProjectedConditionAccessTests
public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
- Task.FromResult>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
+ Interlocked.Increment(ref owner.MetadataCalls) < 0 ? throw new InvalidOperationException() : Task.FromResult>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
? new DataItemResult("0", DataItemStatus.Unavailable, null, null)
: new DataItemResult("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());
@@ -691,14 +861,37 @@ public sealed class GrpcDataProjectedConditionAccessTests
private readonly TaskCompletionSource _open = new(TaskCreationOptions.RunContinuationsAsynchronously);
private long _sequence;
public List Removed { get; } = [];
+ /// #930: in-stream item re-adds (retries), in order.
+ public List Adds { get; } = [];
+ private readonly Dictionary _current = new(StringComparer.Ordinal);
+ private ulong _nextHandle = 100;
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
if (command is OpenSubscription open) _open.TrySetResult(open);
if (command is RemoveSubscriptionItems remove) lock (Removed) Removed.AddRange(remove.Items);
+ if (command is AddSubscriptionItems add) lock (Adds) Adds.Add(add);
return Task.CompletedTask;
}
+ /// How many re-adds named .
+ public int AddsOf(string mapping) { lock (Adds) return Adds.Count(a => a.Items.Any(i => i.ClientItemId == mapping)); }
+
+ /// Acks the latest re-add of (Good ⇒ a fresh handle that later frames use).
+ public void AckAdd(string mapping, DataItemStatus status = DataItemStatus.Good)
+ {
+ AddSubscriptionItems add;
+ lock (Adds) add = Adds.Last(a => a.Items.Any(i => i.ClientItemId == mapping));
+ DataItemHandle? handle = null;
+ if (status == DataItemStatus.Good)
+ {
+ handle = new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, ++_nextHandle, 1);
+ lock (_current) _current[mapping] = handle;
+ }
+ _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, add.CommandId,
+ [new DataSubscriptionItemAck(mapping, status, handle, null, status == DataItemStatus.Good ? null : "refused")]));
+ }
+
public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
public ValueTask DisposeAsync() { Disposed = true; _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
@@ -706,13 +899,16 @@ public sealed class GrpcDataProjectedConditionAccessTests
public DataItemHandle HandleOf(string mapping)
{
+ lock (_current) if (_current.TryGetValue(mapping, out var current)) return current;
var index = Open.Items.Select((x, i) => (x, i)).Single(x => x.x.ClientItemId == mapping).i;
return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1);
}
- public void Ack(params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
+ public void Ack(params string[] refused) => Ack(DataItemStatus.Unavailable, refused);
+
+ public void Ack(DataItemStatus refusal, 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, refusal, null, x.Settings, "refused")
: new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray()));
/// Snapshot record frames exactly as the A2 origin frames them (is_snapshot, no total).