fix(grpc-data): A3b review r1 — per-item results after base.Call (S1), mapping timeout honoured + transport-known BadTimeout (S2), unsent vs OutcomeUnknown + origin failure status (S3), per-connection sub-limit + dispatch floor (S4), N1/N2/N3/N7/N8; tests: real-path L3, worst-case L2 harness, RefreshRequired over the wire, Confirm guards isolated, gate placements/realm, slots, standby, faults, principals

This commit is contained in:
Joseph Doherty
2026-11-24 19:59:21 -05:00
parent 01a4e8db9d
commit 72dece7f45
9 changed files with 787 additions and 76 deletions
@@ -62,10 +62,25 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
/// <summary>Most remote condition methods in flight on this node (§5.6: bounds upstream load, not threads).</summary>
internal const int DefaultImportedMethodConcurrency = 8;
/// <summary>
/// A3b review S4: most remote condition methods in flight to ONE connection — a sub-limit inside the node-wide
/// <see cref="DefaultImportedMethodConcurrency"/>, so a stalled origin holds at most half the node's slots and acks to
/// healthy origins still dispatch.
/// </summary>
internal const int DefaultImportedMethodConcurrencyPerConnection = 4;
/// <summary>How long past the call's own budget the node manager waits for the port before answering <c>BadTimeout</c>.</summary>
internal static readonly TimeSpan ImportedMethodGrace = TimeSpan.FromMilliseconds(250);
/// <summary>
/// A3b review S4: a call whose remaining budget at dispatch is below this is refused <c>BadTimeout</c> UNSENT — the origin
/// could apply it while the consumer had already answered <c>BadTimeout</c>.
/// </summary>
internal static readonly TimeSpan ImportedMethodMinimumDispatchBudget = TimeSpan.FromMilliseconds(250);
private readonly SemaphoreSlim _importedMethodSlots = new(DefaultImportedMethodConcurrency, DefaultImportedMethodConcurrency);
// One per connection that ever dispatched (connections are few and long-lived; never removed — a SemaphoreSlim is small).
private readonly ConcurrentDictionary<string, SemaphoreSlim> _importedMethodConnectionSlots = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, Task<ServiceResult>> _importedMethodsInFlight = new(StringComparer.Ordinal);
private long _importedMethodsDispatched, _importedMethodsJoined, _importedMethodsRefused;
@@ -85,7 +100,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
/// §5.6 step 1: (a) claim every unprocessed request whose ObjectId is in <c>mapped/conditions</c> — a namespace-index
/// test, no lock; (b) the unchanged synchronous <c>base.Call</c> for everything else (it skips claimed requests), run
/// and completed before any remote await; (c) the claimed calls concurrently, bounded by the per-node semaphore.
/// No <c>Lock</c> is held by this method at any point.
/// No <c>Lock</c> is held by this method at any point. Review S1: nothing after <c>base.Call</c> throws — local items are
/// already applied by then, so a fault there must become a per-item status, never a ServiceFault for the batch.
/// </summary>
public override async ValueTask CallAsync(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall,
IList<CallMethodResult> results, IList<ServiceResult> errors, CancellationToken cancellationToken = default)
@@ -109,10 +125,26 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
for (var k = 0; k < claimed.Count; k++)
{
results[claimed[k]] = new CallMethodResult();
calls[k] = CallImportedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token);
calls[k] = CallImportedGuardedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token);
}
// Each task is guarded (never faults), so WhenAll never throws; results are collected per item regardless.
await Task.WhenAll(calls).ConfigureAwait(false);
for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = calls[k].Result;
}
/// <summary>Review S1: <see cref="CallImportedAsync"/> as a task that cannot fault (a synchronous throw included).</summary>
private async Task<ServiceResult> CallImportedGuardedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline,
CancellationToken cancellationToken)
{
try
{
return await CallImportedAsync(caller, request, deadline, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "OtOpcUaNodeManager: imported condition method failed before dispatch");
return Refuse(StatusCodes.BadInternalError);
}
var outcomes = await Task.WhenAll(calls).ConfigureAwait(false);
for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = outcomes[k];
}
/// <summary>
@@ -133,7 +165,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
if (method == DataConditionMethods.None) return Refuse(StatusCodes.BadNotSupported); // shelve, enable/disable, …
if (ProjectedConditionMethods is not { } port) return Refuse(StatusCodes.BadNotSupported);
// Step 2 local checks (no I/O, no Lock). The mapping gate first: an unauthorized caller learns nothing else.
// Step 2 local checks (no I/O, no Lock). The mapping gate first: an unauthorized caller learns nothing else
// (review N5: the two answers above are the SDK pre-validation's own — the node and its method exist publicly).
var placements = condition.Placements;
var route = port.AuthorizeMethod(caller, placements, method);
if (route is null || caller is null) return Refuse(StatusCodes.BadUserAccessDenied);
@@ -157,6 +190,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
if (expected is null) return Refuse(StatusCodes.BadEventIdUnknown);
// An identical call already in flight (same caller, condition, EventId, method, comment) joins it: one dispatch.
// Review N4: a joiner shares the first caller's outcome — its cancellation and budget included (it asked for the
// same thing at the same moment; a joiner never dispatches a second time).
var key = string.Join('\n', caller.Principal, condition.Alarm.NodeId.ToString(), Convert.ToHexString(eventId.Span),
((uint)method).ToString(System.Globalization.CultureInfo.InvariantCulture), comment ?? "\u0001");
var mine = new TaskCompletionSource<ServiceResult>(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -168,17 +203,22 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
}
try
{
var result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started,
cancellationToken).ConfigureAwait(false);
ServiceResult result;
try
{
result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started,
cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
// DispatchImportedAsync answers every post-dispatch failure itself: anything escaping it was thrown before
// the port was called — nothing was sent (review S1/S3).
_logger.LogError(ex, "OtOpcUaNodeManager: imported condition method failed before dispatch");
result = Refuse(StatusCodes.BadInternalError);
}
mine.TrySetResult(result);
return result;
}
catch (Exception ex)
{
var unknown = new ServiceResult(StatusCodes.BadCommunicationError, new LocalizedText("OutcomeUnknown: " + ex.GetType().Name));
mine.TrySetResult(unknown);
return unknown;
}
finally
{
_importedMethodsInFlight.TryRemove(new KeyValuePair<string, Task<ServiceResult>>(key, mine.Task));
@@ -194,22 +234,40 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
ImportedConditionMethodRoute route, DataConditionMethods method, DataActivationMarker expected, string? comment,
RoleCarryingUserIdentity caller, DateTime deadline, long started, CancellationToken cancellationToken)
{
// Step 4: timeout = min(request deadline, ConditionMethodTimeout).
var budget = route.Timeout;
// Step 4: timeout = min(request deadline, ConditionMethodTimeout), as ONE end instant (review N7: elapsed time was
// subtracted from the request-deadline leg twice). When the request deadline binds, the grace the node manager waits
// past the budget is taken out of it, so the answer still lands inside the client's TimeoutHint.
var end = started + (long)(route.Timeout.TotalSeconds * Stopwatch.Frequency);
if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue)
{
var left = deadline - DateTime.UtcNow;
if (left < budget) budget = left;
var byDeadline = Stopwatch.GetTimestamp() + (long)((deadline - DateTime.UtcNow - ImportedMethodGrace).TotalSeconds * Stopwatch.Frequency);
if (byDeadline < end) end = byDeadline;
}
budget -= Stopwatch.GetElapsedTime(started);
if (budget <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout);
TimeSpan Remaining() => Stopwatch.GetElapsedTime(Stopwatch.GetTimestamp(), end);
if (Remaining() < ImportedMethodMinimumDispatchBudget) return Refuse(StatusCodes.BadTimeout);
if (!await _importedMethodSlots.WaitAsync(budget, cancellationToken).ConfigureAwait(false))
return Refuse(StatusCodes.BadTooManyOperations);
// Review S4: the connection's sub-limit first, then the node-wide slots. Review S3: a cancel while WAITING is unsent.
var perConnection = _importedMethodConnectionSlots.GetOrAdd(condition.ConnectionId,
static _ => new SemaphoreSlim(DefaultImportedMethodConcurrencyPerConnection, DefaultImportedMethodConcurrencyPerConnection));
bool connectionSlot = false, nodeSlot = false;
try
{
var remaining = budget - Stopwatch.GetElapsedTime(started);
if (remaining <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout);
try
{
connectionSlot = await perConnection.WaitAsync(Remaining() is var w && w > TimeSpan.Zero ? w : TimeSpan.Zero, cancellationToken)
.ConfigureAwait(false);
if (!connectionSlot) return Refuse(StatusCodes.BadTooManyOperations);
nodeSlot = await _importedMethodSlots.WaitAsync(Remaining() is var n && n > TimeSpan.Zero ? n : TimeSpan.Zero, cancellationToken)
.ConfigureAwait(false);
if (!nodeSlot) return Refuse(StatusCodes.BadTooManyOperations);
}
catch (OperationCanceledException)
{
return Refuse(StatusCodes.BadRequestCancelledByClient); // nothing sent
}
var remaining = Remaining();
if (remaining < ImportedMethodMinimumDispatchBudget) return Refuse(StatusCodes.BadTimeout); // review S4 floor: unsent
var call = new ImportedConditionMethodCall(condition.ConnectionId, condition.ConditionKey, route.Placement, method, expected,
comment, "a3-" + Guid.NewGuid().ToString("N"), remaining, caller.Principal);
using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
@@ -224,6 +282,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
catch (TimeoutException)
{
// The port did not answer inside the budget: it may have reached the origin — OutcomeUnknown, never retried.
// Review N1: WaitAsync and CancelAfter share a due time; cancel explicitly so the port's call ends with it.
bounded.Cancel();
return Unknown(StatusCodes.BadTimeout, "OutcomeUnknown: no answer within the condition method timeout.");
}
catch (OperationCanceledException) when (bounded.IsCancellationRequested)
@@ -231,21 +291,29 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
return Unknown(cancellationToken.IsCancellationRequested ? StatusCodes.BadCommunicationError : StatusCodes.BadTimeout,
"OutcomeUnknown: the call was cancelled after dispatch.");
}
return MapOutcome(result, Stopwatch.GetElapsedTime(started) >= budget);
catch (Exception ex)
{
// The port is contracted not to throw for a remote failure; one that does may have sent the request.
return Unknown(StatusCodes.BadCommunicationError, "OutcomeUnknown: " + ex.GetType().Name);
}
return MapOutcome(result);
}
finally
{
_importedMethodSlots.Release();
if (nodeSlot) _importedMethodSlots.Release();
if (connectionSlot) perConnection.Release();
}
}
/// <summary>
/// §5.6 step 5 outcome mapping. Applied (scripted <c>DriverConfirmedSuccess</c>) and accepted (native
/// <c>AcceptedUnconfirmed</c>) ⇒ Good — the confirming record arrives on the stream; <c>RejectedBeforeDispatch</c> ⇒ the
/// origin's status; <c>OutcomeUnknown</c> ⇒ <c>BadTimeout</c> when the budget ran out, else <c>BadCommunicationError</c>
/// — always Bad (the client must not read it as done), with "OutcomeUnknown" in the diagnostic.
/// <c>AcceptedUnconfirmed</c>) ⇒ Good — the confirming record arrives on the stream; <c>RejectedBeforeDispatch</c> and
/// <c>DriverConfirmedFailure</c> ⇒ the origin's status (review S3: a definite failure is not "unknown");
/// <c>OutcomeUnknown</c> ⇒ the status the transport KNEW (review S2: <c>BadTimeout</c> on a deadline, else
/// <c>BadCommunicationError</c>) — always Bad (the client must not read it as done), with "OutcomeUnknown" in the
/// diagnostic.
/// </summary>
internal ServiceResult MapOutcome(DataConditionMethodResult result, bool budgetElapsed)
internal ServiceResult MapOutcome(DataConditionMethodResult result)
{
switch (result.State)
{
@@ -253,11 +321,13 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
case DataWriteState.AcceptedUnconfirmed:
return StatusCode.IsBad(new StatusCode(result.StatusCode)) ? new ServiceResult(new StatusCode(result.StatusCode)) : ServiceResult.Good;
case DataWriteState.RejectedBeforeDispatch:
case DataWriteState.DriverConfirmedFailure:
var refused = new StatusCode(result.StatusCode);
if (!StatusCode.IsBad(refused)) refused = StatusCodes.BadInternalError;
return result.Diagnostic is { Length: > 0 } text ? new ServiceResult(refused, new LocalizedText(text)) : new ServiceResult(refused);
default:
return Unknown(budgetElapsed ? StatusCodes.BadTimeout : StatusCodes.BadCommunicationError,
var known = new StatusCode(result.StatusCode);
return Unknown(StatusCode.IsBad(known) && known.Code == StatusCodes.BadTimeout.Code ? StatusCodes.BadTimeout : StatusCodes.BadCommunicationError,
"OutcomeUnknown: " + (result.Diagnostic ?? "the origin's outcome is unknown."));
}
}
@@ -324,8 +394,13 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
MintImportedEventId(condition, current);
return false;
}
if (previous is null || current is null || previous == current) return false;
if (state.TimeUtc is { } time && previousTime == time)
if (previous == current) return false;
// Review N3: a marker appearing or disappearing is a marker change too — mint and refresh, never leave the current
// EventId bound to a marker no record carries. Review N2: re-binding (F6) is for an origin RESTART only — a new
// incarnation re-announcing the same state at the same time; a same-incarnation sequence bump is, by the origin's
// definition, a new occurrence.
if (previous is not null && current is not null && previous.Incarnation != current.Incarnation
&& state.TimeUtc is { } time && previousTime == time)
{
var node = condition.RecentEvents.First;
while (node is not null)
@@ -19,7 +19,15 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec
public AlarmConditionState Alarm { get; } = alarm;
public string ConnectionId { get; } = connectionId;
public string ConditionKey { get; } = conditionKey;
public IReadOnlyList<ImportedConditionPlacement> Placements { get; set; } = [];
private IReadOnlyList<ImportedConditionPlacement> _placements = [];
private long _supportedMethods = -1;
/// <summary>Written under <c>Lock</c>; read without it by A3b methods (review N8: a volatile publication of an immutable list).</summary>
public IReadOnlyList<ImportedConditionPlacement> Placements
{
get => Volatile.Read(ref _placements);
set => Volatile.Write(ref _placements, value);
}
public HashSet<FolderState> Folders { get; } = new(ReferenceEqualityComparer.Instance);
/// <summary>NIT (review r1): an immutable copy of <see cref="Folders"/> for the delivery paths that read off <c>Lock</c>.</summary>
public FolderState[] WiredFolders { get; set; } = [];
@@ -34,7 +42,12 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec
/// marker under it, never under the node manager's <c>Lock</c>.</summary>
public object MethodGate { get; } = new();
/// <summary>The origin's <c>supported_methods</c> for the service principal (null until a listing carried it).</summary>
public uint? SupportedMethods { get; set; }
/// <remarks>Review N8: read without <c>Lock</c> by A3b methods — stored as one atomic 64-bit word (-1 = not listed yet).</remarks>
public uint? SupportedMethods
{
get => Interlocked.Read(ref _supportedMethods) is var v && v >= 0 ? (uint)v : null;
set => Interlocked.Exchange(ref _supportedMethods, value is { } m ? m : -1);
}
/// <summary>The <c>time</c> of the latest applied record (N6/F6: re-binding requires it unchanged).</summary>
public DateTimeOffset? LastTime { get; set; }
/// <summary>Bumped on every placement change (verdict caches key on it).</summary>
@@ -155,6 +168,13 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
/// <summary>Imported condition events reported (one per genuine origin transition).</summary>
internal long ImportedEventsReported => Interlocked.Read(ref _importedEventsReported);
/// <summary>How many N6 EventId slots a condition holds (test/diagnostic observation, the L2 harness).</summary>
internal int FindImportedConditionRecentEventCount(string connectionId, string conditionKey)
{
if (_importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey)) is not { } c) return 0;
lock (c.MethodGate) return c.RecentEvents.Count;
}
/// <summary>RefreshRequired events queued for imported conditions.</summary>
internal long ImportedRefreshRequiredQueued => Interlocked.Read(ref _importedRefreshRequired);
@@ -16,9 +16,17 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed partial class GrpcDataConnection : IDataConditionMethodService
{
internal const uint BadCommunicationError = 0x80050000u;
private TimeSpan _conditionMethodTimeout = TimeSpan.FromSeconds(5);
/// <summary>
/// The validator's ceiling for a mapping's <c>ConditionMethodTimeoutMilliseconds</c> (3,600,000 ms) — the client's default
/// backstop. A3b review S2: the per-MAPPING ceiling arrives in <see cref="DataConditionMethodRequest.RemainingBudget"/>
/// (the consumer node manager computes min(request deadline, mapping timeout) − elapsed); a connection-wide 5 s default
/// here silently capped a 30 s mapping at 5 s.
/// </summary>
public static readonly TimeSpan MaxConditionMethodTimeout = TimeSpan.FromMilliseconds(3_600_000);
/// <summary>The per-call method ceiling (the mapping's <c>ConditionMethodTimeoutMilliseconds</c>; A3 binds it per mapping).</summary>
private TimeSpan _conditionMethodTimeout = MaxConditionMethodTimeout;
/// <summary>An optional connection-wide backstop over the per-call budget (default <see cref="MaxConditionMethodTimeout"/>).</summary>
public TimeSpan ConditionMethodTimeout
{
get => _conditionMethodTimeout;
@@ -29,7 +37,9 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
public async Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
request.Validate();
// A3b review S3: an invalid request is refused unsent, never thrown into a caller that would read it as "unknown".
try { request.Validate(); }
catch (ArgumentException ex) { return new(DataWriteState.RejectedBeforeDispatch, BadInvalidArgument, "Invalid request: " + ex.Message); }
var start = Clock.GetTimestamp();
var deadline = request.RemainingBudget < ConditionMethodTimeout ? request.RemainingBudget : ConditionMethodTimeout;
if (deadline <= TimeSpan.Zero) return new(DataWriteState.RejectedBeforeDispatch, BadTimeout, "Budget expired before dispatch.");
@@ -82,6 +92,12 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
ex.StatusCode is StatusCode.PermissionDenied or StatusCode.Unauthenticated ? 0x801F0000u : BadNotSupportedMethod,
"Refused by the origin transport: " + ex.StatusCode);
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded && !cancellationToken.IsCancellationRequested)
{
// A3b review S2: the deadline is a KNOWN timeout — say BadTimeout here instead of letting the caller infer it
// from its own clock. Still OutcomeUnknown: the origin may have applied it.
return new(DataWriteState.OutcomeUnknown, BadTimeout, "OutcomeUnknown: no answer before the method deadline.");
}
catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException
or ArgumentException or IOException)
{
@@ -99,4 +115,5 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
}
private const uint BadNotSupportedMethod = 0x803D0000u;
private const uint BadInvalidArgument = 0x80AB0000u;
}
@@ -18,6 +18,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod
private const uint BadNoCommunication = 0x80310000u;
private const uint BadNotSupported = 0x803D0000u;
private const uint BadUserAccessDenied = 0x801F0000u;
private const uint BadInvalidArgument = 0x80AB0000u;
/// <inheritdoc />
public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements,
@@ -57,6 +58,12 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod
if (serving is null)
return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "No condition stream is open on the connection.");
var request = new DataConditionMethodRequest(call.OperationId, call.Placement.Placement, call.Method, call.ExpectedActivation,
call.Comment, serving.Incarnation, call.RemainingBudget, call.OnBehalfOf);
// A3b review S3: validated before the lease — an invalid request is refused unsent, never an "unknown" outcome.
try { request.Validate(); }
catch (ArgumentException ex) { return new(DataWriteState.RejectedBeforeDispatch, BadInvalidArgument, "Invalid request: " + ex.Message); }
IGrpcDataAdapterConnectionLease? lease;
try { lease = await _connections.AcquireAsync(call.ConnectionId, cancellationToken).ConfigureAwait(false); }
catch (Exception ex) when (ex is InvalidOperationException or OperationCanceledException or TimeoutException)
@@ -66,8 +73,6 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod
{
if (lease.Connection is not IDataConditionMethodService methods)
return new(DataWriteState.RejectedBeforeDispatch, BadNotSupported, "The connection does not serve condition methods.");
var request = new DataConditionMethodRequest(call.OperationId, call.Placement.Placement, call.Method, call.ExpectedActivation,
call.Comment, serving.Incarnation, call.RemainingBudget, call.OnBehalfOf);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lease.CancellationToken);
try
{
@@ -20,6 +20,7 @@ public sealed class ImportedConditionMemoryMeasurementTests
{
private const string Connection = "conn-l2";
private const string Mapping = "map-l2";
private const string MappingB = "map-l2b";
private const int Conditions = 1_000;
[Fact]
@@ -29,29 +30,57 @@ public sealed class ImportedConditionMemoryMeasurementTests
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-l2", encrypted: false, ct);
var nm = rig.Nm;
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant");
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(Mapping, root), parent,
"remote", "Plant/remote", Mapping, 1, () => true), out _).ShouldBeTrue();
// Access first: a condition-bearing mapping's anchor folders are event notifiers from materialisation.
var access = new ImportedConditionEventWireTests.FakeConditionAccess();
access.Allowed.Add(ServerEventRig.KeyPrincipal);
nm.ProjectedConditionAccess = access;
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant");
// A3b review S5: worst case — TWO placements per condition (two mappings, two folders it is wired into).
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(Mapping, root), parent,
"remote", "Plant/remote", Mapping, 1, () => true), out var anchorA).ShouldBeTrue();
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingB, root), parent,
"remote-b", "Plant/remote-b", MappingB, 1, () => true), out var anchorB).ShouldBeTrue();
// Event items: the Server object and both placement folders, publishing OFF so the server-side queues hold their events.
using var session = await rig.ConnectAsync(anonymous: false, ct);
var subscription = new Opc.Ua.Client.Subscription(session.DefaultSubscription) { PublishingInterval = 1000, PublishingEnabled = false };
session.AddSubscription(subscription);
await subscription.CreateAsync(ct);
foreach (var source in new[] { ObjectIds.Server, Local(session, anchorA!.Value), Local(session, anchorB!.Value) })
{
var item = new Opc.Ua.Client.MonitoredItem(subscription.DefaultItem)
{
StartNodeId = source, AttributeId = Attributes.EventNotifier, QueueSize = 1000,
Filter = new EventFilter { SelectClauses = [new SimpleAttributeOperand(ObjectTypeIds.BaseEventType, new QualifiedName(BrowseNames.EventId)),
new SimpleAttributeOperand(ObjectTypeIds.BaseEventType, new QualifiedName(BrowseNames.Message))] },
};
subscription.AddItem(item);
}
await subscription.ApplyChangesAsync(ct);
subscription.MonitoredItems.All(m => ServiceResult.IsGood(m.Status.Error)).ShouldBeTrue("all three event items are admitted");
var (heap0, ws0) = Measure();
var keys = Enumerable.Range(0, Conditions).Select(i => KeyOf("l2-" + i)).ToArray();
var first = keys.Select((k, i) => Update(k, i, 3, active: true, acked: false)).ToList();
// Runner state (worst case): the committed Live records AND a full re-snapshot Buffer of the same keys.
var live = keys.Select((k, i) => Update(k, i, 3, active: true, acked: false, sequence: 1)).ToList();
var sw = Stopwatch.StartNew();
nm.ApplyConditions(first);
nm.ApplyConditions(live);
var materialise = sw.Elapsed;
first.Clear();
var (heapMid, _) = Measure();
// One more transition each: every condition reports an event (consumer-minted EventId in its N6 registry).
var second = keys.Select((k, i) => Update(k, i, 4, active: true, acked: true)).ToList();
// Every N6 EventId slot filled: RecentEventIds transitions per condition, each a reported event minting an EventId.
List<ImportedConditionUpdate> buffer = [];
sw.Restart();
nm.ApplyConditions(second);
for (var t = 0; t < OpcUaServer.ProjectedConditionRegistry.RecentEventIds; t++)
{
buffer = keys.Select((k, i) => Update(k, i, 4 + t, active: true, acked: t % 2 == 0, sequence: (ulong)(2 + t / 2))).ToList();
nm.ApplyConditions(buffer);
}
var transition = sw.Elapsed;
nm.ImportedConditionCount.ShouldBe(Conditions);
var slots = nm.FindImportedConditionRecentEventCount(Connection, keys[0]);
slots.ShouldBe(OpcUaServer.ProjectedConditionRegistry.RecentEventIds, "every N6 slot is in use");
// Exercise the verdict cache once per condition (one identity).
var identity = new Security.RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "apikey" }, [], ServerEventRig.KeyPrincipal,
"k", null, null);
@@ -59,17 +88,23 @@ public sealed class ImportedConditionMemoryMeasurementTests
nm.AuthorizeImportedCondition(identity, Core.Abstractions.OpcUaOperation.Read, nm.ImportedConditionNodeId(Connection, k)).ShouldBeTrue();
var (heap1, ws1) = Measure();
GC.KeepAlive(second);
GC.KeepAlive(live);
GC.KeepAlive(buffer);
GC.KeepAlive(subscription);
var heapGrowth = heap1 - heap0;
var wsGrowth = ws1 - ws0;
var line = $"L2: {Conditions} conditions, one mapping: managed heap +{heapGrowth / 1048576.0:F1} MiB ({heapGrowth / Conditions:N0} B/condition; after materialise {(heapMid - heap0) / Conditions:N0}), " +
var line = $"L2 (worst case: 2 placements, {slots} EventId slots, 3 event items, Live+Buffer records): {Conditions} conditions: " +
$"managed heap +{heapGrowth / 1048576.0:F1} MiB ({heapGrowth / Conditions:N0} B/condition; after materialise {(heapMid - heap0) / Conditions:N0}), " +
$"working set +{wsGrowth / 1048576.0:F1} MiB ({wsGrowth / Conditions:N0} B/condition); materialise {materialise.TotalMilliseconds:F0} ms, " +
$"transition {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}";
$"{OpcUaServer.ProjectedConditionRegistry.RecentEventIds} transitions {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}";
TestContext.Current.TestOutputHelper?.WriteLine(line);
if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine);
wsGrowth.ShouldBeLessThanOrEqualTo(200L * 1024 * 1024);
}
private static NodeId Local(Opc.Ua.Client.ISession session, NodeId serverId) =>
new(serverId.IdentifierAsString, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
private static (long Heap, long WorkingSet) Measure()
{
for (var i = 0; i < 3; i++) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GC.WaitForPendingFinalizers(); }
@@ -81,15 +116,19 @@ public sealed class ImportedConditionMemoryMeasurementTests
private static string KeyOf(string seed) =>
Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static ImportedConditionUpdate Update(string key, int index, long version, bool active, bool acked)
private static ImportedConditionUpdate Update(string key, int index, long version, bool active, bool acked, ulong sequence)
{
var path = $"Plant/dev{index / 10}/HR{index}";
var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path);
var placements = new[] { new ImportedConditionPlacement(Mapping, DataRealm.Raw, view, "Plant/remote", path["Plant/".Length..]) };
var placements = new[]
{
new ImportedConditionPlacement(Mapping, DataRealm.Raw, view, "Plant/remote", path["Plant/".Length..]),
new ImportedConditionPlacement(MappingB, DataRealm.Raw, view, "Plant/remote-b", path["Plant/".Length..]),
};
var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", $"HR{index}", DataConditionSourceKind.Native,
[view], (uint)DataConditionMethodSets.Native);
var state = new DataConditionState(key, version, false, true, info, active, acked, true, true, 0, 500, $"HR{index} high",
StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1));
StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", sequence));
return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote/" + placements[0].RelativePath);
}
}
@@ -161,8 +161,7 @@ public sealed class ImportedConditionMethodWireTests
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, fresh, "x", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Count.ShouldBe(2);
f.Port.Calls.Last().ExpectedActivation.ShouldBe(new DataActivationMarker("inc-c", 9));
// RequireRefresh ran (it queues only to items that exist; none here — the counter path is pinned by A3a's tests).
rig.Nm.ImportedRefreshRequiredQueued.ShouldBeGreaterThanOrEqualTo(refresh);
_ = refresh; // review S6: the RefreshRequired itself is pinned over the wire by A_resync_that_cannot_re_bind_…
}
/// <summary>
@@ -170,12 +169,26 @@ public sealed class ImportedConditionMethodWireTests
/// consumer complete in &lt; 200 ms meanwhile, the node manager's <c>Lock</c> is free, and no acknowledged state is
/// observable before the origin's record (positive control: it arrives after release).
/// </summary>
[Fact]
public async Task Lock_freedom_a_5s_stalled_origin_method_delays_no_Read_Browse_or_data_Publish_and_applies_nothing_before_the_record()
/// <param name="realPath">
/// Review S5: false = the stall sits at the consumer's port (the original measurement); true = behind a REAL
/// <c>ProjectedConditionAccess</c> + lease + <c>GrpcDataConnection</c>, the in-process origin's handler stalling 5 s.
/// </param>
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Lock_freedom_a_5s_stalled_origin_method_delays_no_Read_Browse_or_data_Publish_and_applies_nothing_before_the_record(bool realPath)
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-l3", encrypted: false, ct);
var f = Fixture.Install(rig);
await using var real = realPath ? new RealConditionMethodPath(Connection, MappingA, f.Port, TimeSpan.FromSeconds(5)) : null;
if (real is not null)
{
rig.Nm.ProjectedConditionMethods = real.Port;
// The condition stream is open (its serving incarnation addresses the call) before anything is measured.
await WaitUntilAsync(() => real.Access.CallAsync(new ImportedConditionMethodCall(Connection, Key1, Fixture.DefaultPlacements[0],
DataConditionMethods.Acknowledge, Marker1, null, "probe", TimeSpan.Zero, null), ct).Result.StatusCode != 0x80310000u);
}
var tag = rig.EnsureRawVariable("l3", "Double", writable: false);
rig.Sink.WriteValue(tag, 0.0, 0, DateTime.UtcNow, AddressSpaceRealm.Raw);
f.Apply(Update(version: 3, active: true, acked: false));
@@ -226,7 +239,7 @@ public sealed class ImportedConditionMethodWireTests
f.Port.Handler = async (_, token) => { await Task.WhenAny(release.Task, Task.Delay(TimeSpan.FromSeconds(5), token)); return Applied(); };
var stall = Stopwatch.StartNew();
var ack = CallAsync(caller, f.ConditionId(caller), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "l3", ct);
await WaitUntilAsync(() => f.Port.Calls.Count == 1);
await WaitUntilAsync(() => real is null ? f.Port.Calls.Count == 1 : Volatile.Read(ref real.Server.MethodCalls) == 1);
var during = new List<(double Read, double Browse, double Publish, double LockWait)>();
for (var i = 0; i < 10 && !ack.IsCompleted; i++)
@@ -238,6 +251,7 @@ public sealed class ImportedConditionMethodWireTests
ack.IsCompleted.ShouldBeFalse("the measurements ran while the remote call was stalled");
during.Count.ShouldBe(10);
(await ack).ShouldBe(StatusCodes.Good);
if (real is not null) Volatile.Read(ref real.Server.MethodAnswers).ShouldBe(1, "the origin's stalled handler answered once, after the stall");
var stalled = stall.Elapsed;
f.Acked().ShouldBeFalse();
f.Apply(Update(version: 4, active: true, acked: true));
@@ -248,7 +262,7 @@ public sealed class ImportedConditionMethodWireTests
var maxPublish = during.Max(m => m.Publish);
var maxLock = during.Max(m => m.LockWait);
var line =
$"L3: stall {stalled.TotalMilliseconds:F0} ms; baseline read {baseline.Read:F1} browse {baseline.Browse:F1} publish {baseline.Publish:F1} lock {baseline.LockWait:F2}; " +
$"L3 ({(realPath ? "real ProjectedConditionAccess + GrpcDataConnection" : "port")}): stall {stalled.TotalMilliseconds:F0} ms; baseline read {baseline.Read:F1} browse {baseline.Browse:F1} publish {baseline.Publish:F1} lock {baseline.LockWait:F2}; " +
$"during (n={during.Count}) max read {maxRead:F1} browse {maxBrowse:F1} publish {maxPublish:F1} lock {maxLock:F2} ms";
TestContext.Current.TestOutputHelper?.WriteLine(line);
if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine);
@@ -312,12 +326,14 @@ public sealed class ImportedConditionMethodWireTests
f.Port.Handler = async (_, token) =>
{
try { await Task.Delay(Timeout.Infinite, token); }
catch (OperationCanceledException) { cancelled = true; throw; }
catch (OperationCanceledException) { Volatile.Write(ref cancelled, true); throw; }
return Applied();
};
var sw = Stopwatch.StartNew();
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadTimeout);
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(3), "bounded by the mapping's method timeout (+ grace), not the request's");
// Review N1: the port's call is cancelled explicitly on the timeout (it used to rely on a timer sharing WaitAsync's due
// time, disposed unfired when WaitAsync won).
await WaitUntilAsync(() => Volatile.Read(ref cancelled));
f.Port.Calls.Count.ShouldBe(1, "dispatched once, never retried");
f.Acked().ShouldBeFalse();
@@ -325,6 +341,13 @@ public sealed class ImportedConditionMethodWireTests
f.Port.Timeout = TimeSpan.FromSeconds(5);
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.OutcomeUnknown, 0x80050000u, "transport failed"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadCommunicationError);
// Review S2: the transport's KNOWN timeout passes through (it used to be inferred from the consumer's own clock, so a
// deadline the transport hit before the consumer's budget elapsed read as BadCommunicationError).
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, "deadline"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadTimeout);
// Review S3: a definite failure at the origin is the origin's status, not "unknown".
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.DriverConfirmedFailure, StatusCodes.BadConditionAlreadyEnabled.Code, "refused"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadConditionAlreadyEnabled);
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadInvalidState.Code, "not Primary"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadInvalidState);
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "No condition stream"));
@@ -332,6 +355,251 @@ public sealed class ImportedConditionMethodWireTests
f.Acked().ShouldBeFalse("no outcome applies anything locally");
}
/// <summary>
/// A3b review S6 (non-vacuous RefreshRequired) + N2: a same-incarnation marker move at an unchanged time is a NEW
/// occurrence — not re-bound; the old EventId is unknown, a fresh one is ackable, and a subscriber that can see the
/// condition receives RefreshRequired over the wire.
/// </summary>
[Fact]
public async Task A_resync_that_cannot_re_bind_sends_RefreshRequired_to_a_subscriber_and_a_same_incarnation_bump_is_not_re_bound()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-refreshreq", encrypted: false, ct);
var f = Fixture.Install(rig);
var t0 = DateTimeOffset.UtcNow.AddMinutes(-1);
f.Apply(Update(version: 3, active: true, acked: false, time: t0));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
var id = f.ConditionId(session);
var before = f.CurrentEventId();
events.HasType(serverItem, ObjectTypeIds.RefreshRequiredEventType).ShouldBeFalse();
// Same incarnation, sequence bumped, same time and state: by the origin's definition a new occurrence (review N2).
f.Apply(Update(version: 4, active: true, acked: false, time: t0, marker: new DataActivationMarker(Marker1.Incarnation, 2)));
await RecordedEvents.WaitUntilAsync(() => events.HasType(serverItem, ObjectTypeIds.RefreshRequiredEventType));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown);
var fresh = f.CurrentEventId();
fresh.ShouldNotBe(before);
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, fresh, "x", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Single().ExpectedActivation.ShouldBe(new DataActivationMarker(Marker1.Incarnation, 2));
}
/// <summary>Review N3: a record that first carries a marker (the previous one had none) binds a fresh, ackable EventId.</summary>
[Fact]
public async Task A_marker_appearing_on_an_unchanged_state_mints_an_ackable_EventId()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-nullmarker", encrypted: false, ct);
var f = Fixture.Install(rig);
var t0 = DateTimeOffset.UtcNow.AddMinutes(-1);
f.Apply(Update(version: 3, active: true, acked: false, time: t0, noMarker: true));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var id = f.ConditionId(session);
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
.ShouldBe(StatusCodes.BadEventIdUnknown, "no marker: nothing to address the origin's occurrence with");
f.Apply(Update(version: 4, active: true, acked: false, time: t0));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Single().ExpectedActivation.ShouldBe(Marker1);
}
/// <summary>
/// Review S6: the native-Confirm guard and the supported-methods guard, each isolated — a native condition whose listing
/// DOES carry Confirm is still refused; a scripted one whose listing lacks it is refused; a scripted one with it dispatches.
/// </summary>
[Fact]
public async Task Native_Confirm_is_refused_even_when_listed_and_a_scripted_Confirm_follows_the_listing()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-confirm", encrypted: false, ct);
var f = Fixture.Install(rig);
var native = KeyOf("native-listed"); var scriptedNo = KeyOf("scripted-no"); var scriptedYes = KeyOf("scripted-yes");
var all = (uint)DataConditionMethodSets.All;
f.Apply(Update(version: 3, active: true, acked: true, key: native, methods: all));
f.Apply(Update(version: 3, active: true, acked: true, native: false, key: scriptedNo,
methods: (uint)(DataConditionMethods.Acknowledge | DataConditionMethods.AddComment)));
f.Apply(Update(version: 3, active: true, acked: true, native: false, key: scriptedYes, methods: all));
using var session = await rig.ConnectAsync(anonymous: false, ct);
(await CallAsync(session, f.ConditionId(session, key: native), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: native), "c", ct))
.ShouldBe(StatusCodes.BadNotSupported, "native: no upstream confirm path, whatever the listing says");
(await CallAsync(session, f.ConditionId(session, key: scriptedNo), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: scriptedNo), "c", ct))
.ShouldBe(StatusCodes.BadNotSupported, "the origin's supported_methods lacks Confirm");
f.Port.Calls.ShouldBeEmpty();
(await CallAsync(session, f.ConditionId(session, key: scriptedYes), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: scriptedYes), "c", ct))
.ShouldBe(StatusCodes.Good);
f.Port.Calls.Single().Method.ShouldBe(DataConditionMethods.Confirm);
}
/// <summary>
/// Review S1 + S6: a fault BEFORE dispatch (the gate throws) is that item's <c>BadInternalError</c>, unsent — the batch
/// still answers and a local item after the imported one is applied and Good (imported-first ordering); a batch
/// carrying a pre-validation failure answers it per item while its imported call dispatches; a port that THROWS after
/// dispatch is OutcomeUnknown (<c>BadCommunicationError</c>), dispatched once.
/// </summary>
[Fact]
public async Task A_fault_before_dispatch_is_a_per_item_BadInternalError_and_the_rest_of_the_batch_still_answers()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-fault", encrypted: false, ct);
rig.Enforce(true, [ServerEventRig.Key()], ServerEventRig.ClusterGrant(Granted, "acl-key", NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead
| NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.MethodCall));
rig.MaterialiseNative();
var routed = 0;
rig.Nm.NativeAlarmAckRouter = _ => Interlocked.Increment(ref routed);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
rig.Project(true, new AlarmConditionSnapshot(true, false, true, true, AlarmShelvingKind.Unshelved, 700, "local"));
await RecordedEvents.WaitUntilAsync(() => events.Has(serverItem, "local"));
var localEventId = events.LatestEventId(serverItem, "local");
f.Port.AuthorizeThrows = true;
var response = await session.CallAsync(null,
[
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] },
new CallMethodRequest { ObjectId = ServerEventRig.ConditionNodeId(session, native: true), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(ByteString.From(localEventId)), new Variant(new LocalizedText("local ack"))] },
], ct);
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInternalError.Code, "the imported item faulted before dispatch");
response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the local item after it was applied and answers");
Volatile.Read(ref routed).ShouldBe(1);
f.Port.Calls.ShouldBeEmpty("nothing was sent");
// A pre-validation failure in the same batch as a good imported call: answered per item, the imported one dispatched.
f.Port.AuthorizeThrows = false;
response = await session.CallAsync(null,
[
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = NodeId.Null },
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] },
], ct);
StatusCode.IsBad(response.Results[0].StatusCode).ShouldBeTrue();
response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
f.Port.Calls.Count.ShouldBe(1);
// A port that throws after dispatch: OutcomeUnknown, never retried.
f.Port.Handler = (_, _) => throw new InvalidOperationException("port fault");
(await CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), "n", ct))
.ShouldBe(StatusCodes.BadCommunicationError);
f.Port.Calls.Count.ShouldBe(2);
f.Acked().ShouldBeFalse();
}
/// <summary>
/// Review S4: one stalled connection holds at most its sub-limit (4) of the node's 8 slots — a call to another connection
/// still dispatches at once; the stalled connection's further calls wait out their budget and answer
/// <c>BadTooManyOperations</c> unsent (slot exhaustion).
/// </summary>
[Fact]
public async Task One_stalled_connection_cannot_starve_another_and_its_excess_calls_are_BadTooManyOperations_unsent()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-slots", encrypted: false, ct);
var f = Fixture.Install(rig);
const string other = "conn-b";
f.Apply(Update(version: 3, active: true, acked: false));
f.Apply(Update(version: 3, active: true, acked: false, connection: other));
using var session = await rig.ConnectAsync(anonymous: false, ct);
f.Port.Timeout = TimeSpan.FromSeconds(3);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
f.Port.Handler = async (call, token) =>
{
if (call.ConnectionId == Connection) await release.Task.WaitAsync(token);
return Applied();
};
var stalled = Enumerable.Range(0, OtOpcUaNodeManager.DefaultImportedMethodConcurrency)
.Select(i => CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), $"c{i}", ct)).ToArray();
await WaitUntilAsync(() => f.Port.Calls.Count == OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection);
var sw = Stopwatch.StartNew();
(await CallAsync(session, f.ConditionId(session, other), MethodIds.ConditionType_AddComment, f.CurrentEventId(other), "b", ct))
.ShouldBe(StatusCodes.Good, "a healthy origin is not starved by a stalled one");
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(1.5));
var outcomes = await Task.WhenAll(stalled);
outcomes.Count(o => o == StatusCodes.BadTooManyOperations).ShouldBe(
OtOpcUaNodeManager.DefaultImportedMethodConcurrency - OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection);
outcomes.Count(o => o == StatusCodes.BadTimeout).ShouldBe(OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection);
f.Port.Calls.Count(c => c.ConnectionId == Connection).ShouldBe(OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection,
"the excess calls never dispatched");
release.SetResult();
}
/// <summary>Review S4 floor: a request whose own deadline leaves less than the minimum dispatch budget is BadTimeout, unsent.</summary>
[Fact]
public async Task A_request_deadline_below_the_dispatch_floor_is_BadTimeout_unsent()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-floor", encrypted: false, ct);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var response = await session.CallAsync(new RequestHeader { TimeoutHint = 450 },
[new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("x"))] }], ct);
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
f.Port.Calls.ShouldBeEmpty("450 ms − 250 ms grace leaves less than the 250 ms floor: refused before dispatch");
// Positive control: a roomy deadline dispatches, and the port's budget ends before the client's TimeoutHint (N7).
response = await session.CallAsync(new RequestHeader { TimeoutHint = 2_000 },
[new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("x"))] }], ct);
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
f.Port.Calls.Single().RemainingBudget.ShouldBeLessThanOrEqualTo(TimeSpan.FromMilliseconds(2_000) - OtOpcUaNodeManager.ImportedMethodGrace);
}
/// <summary>Review S6: a Warm standby refuses an imported method locally (<c>BadInvalidState</c>), nothing sent.</summary>
[Fact]
public async Task A_warm_standby_refuses_an_imported_method_unsent()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await WarmRedundancyWireTests.StartModeAsync("a3b-standby", "Warm", ct);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
var projection = rig.Server.CreateStandbyProjection()!;
WarmRedundancyWireTests.Demote(projection);
using var session = await rig.ConnectAsync(anonymous: false, ct);
(await CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
.ShouldBe(StatusCodes.BadInvalidState);
f.Port.Calls.ShouldBeEmpty();
WarmRedundancyWireTests.Promote(projection);
(await CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
.ShouldBe(StatusCodes.Good);
}
/// <summary>Review S6: identical calls from DIFFERENT principals never join — each is its own dispatch.</summary>
[Fact]
public async Task Identical_calls_from_different_principals_do_not_join()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-nojoin", encrypted: false, ct);
var f = Fixture.Install(rig);
f.Port.Granted.Add("anonymous");
f.Apply(Update(version: 3, active: true, acked: false));
using var keyed = await rig.ConnectAsync(anonymous: false, ct);
using var anonymous = await rig.ConnectAsync(anonymous: true, ct);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
f.Port.Handler = async (_, _) => { await release.Task; return Applied(); };
var eventId = f.CurrentEventId();
var a = CallAsync(keyed, f.ConditionId(keyed), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "same", ct);
var b = CallAsync(anonymous, f.ConditionId(anonymous), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "same", ct);
await WaitUntilAsync(() => f.Port.Calls.Count == 2);
rig.Nm.ImportedMethodsJoined.ShouldBe(0);
release.SetResult();
(await a).ShouldBe(StatusCodes.Good);
(await b).ShouldBe(StatusCodes.Good);
f.Port.Calls.Select(c => c.OnBehalfOf).Order().ShouldBe(new[] { "anonymous", Granted }.Order());
}
// ---------------------------------------------------------------------------------------------------------------------
private static DataConditionMethodResult Applied() => new(DataWriteState.AcceptedUnconfirmed, 0, null);
@@ -340,15 +608,16 @@ public sealed class ImportedConditionMethodWireTests
Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static ImportedConditionUpdate Update(long version, bool active, bool acked, DataActivationMarker? marker = null,
string message = "HR200 high", bool native = true, DateTimeOffset? time = null)
string message = "HR200 high", bool native = true, DateTimeOffset? time = null, string connection = Connection, string? key = null,
uint? methods = null, bool noMarker = false)
{
var placements = Fixture.DefaultPlacements;
var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", "HR200",
native ? DataConditionSourceKind.Native : DataConditionSourceKind.Scripted, placements.Select(p => p.Placement).ToArray(),
(uint)(native ? DataConditionMethodSets.Native : DataConditionMethodSets.Scripted));
var state = new DataConditionState(Key1, version, false, true, info, active, acked, true, true, 0, 777, message,
StatusCodes.Good.Code, null, 0, time ?? DateTimeOffset.UtcNow, active || !acked, marker ?? Marker1);
return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote-a/" + placements[0].RelativePath);
methods ?? (uint)(native ? DataConditionMethodSets.Native : DataConditionMethodSets.Scripted));
var state = new DataConditionState(key ?? Key1, version, false, true, info, active, acked, true, true, 0, 777, message,
StatusCodes.Good.Code, null, 0, time ?? DateTimeOffset.UtcNow, active || !acked, noMarker ? null : marker ?? Marker1);
return new ImportedConditionUpdate(connection, state, info, placements, "Plant/remote-a/" + placements[0].RelativePath);
}
/// <summary>Calls one method and returns its status (never throws for a Bad result).</summary>
@@ -379,6 +648,8 @@ public sealed class ImportedConditionMethodWireTests
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(5);
public ConcurrentQueue<(string Principal, DataConditionMethods Method)> AuthorizedFor { get; } = new();
public ConcurrentQueue<ImportedConditionMethodCall> Calls { get; } = new();
/// <summary>The gate throws (an unexpected fault BEFORE dispatch — review S1).</summary>
public bool AuthorizeThrows { get; set; }
public Func<ImportedConditionMethodCall, CancellationToken, Task<DataConditionMethodResult>> Handler { get; set; } =
(_, _) => Task.FromResult(Applied());
@@ -386,6 +657,7 @@ public sealed class ImportedConditionMethodWireTests
DataConditionMethods method)
{
AuthorizedFor.Enqueue((caller?.Principal ?? "", method));
if (AuthorizeThrows) throw new InvalidOperationException("gate fault");
return caller is not null && Granted.Contains(caller.Principal) && (GrantedMethods & method) == method
? new ImportedConditionMethodRoute(placements[0], Timeout) : null;
}
@@ -427,12 +699,14 @@ public sealed class ImportedConditionMethodWireTests
return new Fixture { Rig = rig, Port = port };
}
public NodeId ConditionId(ISession session) =>
new(Identifier, (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri));
public NodeId ConditionId(ISession session, string connection = Connection, string? key = null) =>
new(ImportedConditionIds.Identifier(connection, key ?? Key1), (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri));
public ByteString CurrentEventId() => Rig.Nm.FindImportedCondition(Connection, Key1)!.EventId!.Value;
public ByteString CurrentEventId(string connection = Connection, string? key = null) =>
Rig.Nm.FindImportedCondition(connection, key ?? Key1)!.EventId!.Value;
public bool Acked() => Rig.Nm.FindImportedCondition(Connection, Key1)!.AckedState!.Id!.Value;
public bool Acked(string connection = Connection, string? key = null) =>
Rig.Nm.FindImportedCondition(connection, key ?? Key1)!.AckedState!.Id!.Value;
public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]);
@@ -0,0 +1,206 @@
using System.Buffers.Binary;
using System.Net;
using System.Runtime.CompilerServices;
using Google.Protobuf;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// A3b review S5 (L3 on the REAL dispatch path): the consumer's method port is a real <see cref="ProjectedConditionAccess"/>
/// whose lease hands out a real <see cref="GrpcDataConnection"/>; the origin is an in-process gRPC endpoint (HTTP/2 framing
/// over an <see cref="HttpMessageHandler"/>) whose <c>CallConditionMethod</c> handler stalls for <see cref="Stall"/>. Only the
/// condition STREAM is a quiet stand-in (it opens, carries the Primary's provenance and never delivers) — the conditions
/// themselves are applied by the test, as in every other A3b wire test. The per-caller gate stays the test's fake (its own
/// tests are the Runtime gate tests); everything after it is production code.
/// </summary>
internal sealed class RealConditionMethodPath : IAsyncDisposable
{
public const string Incarnation = "boot-a";
private readonly IProjectedConditionMethods _gate;
private readonly DataConnectionManager _manager = new("consumer", 1);
private readonly GrpcDataConnection _grpc;
private readonly IDisposable? _demand;
public Origin Server { get; }
public ProjectedConditionAccess Access { get; }
public IProjectedConditionMethods Port { get; }
public RealConditionMethodPath(string connectionId, string mappingId, IProjectedConditionMethods gate, TimeSpan stall)
{
_gate = gate;
Server = new Origin(stall);
_manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { [connectionId] = new HashSet<string> { "consumer" } });
_grpc = new GrpcDataConnection(connectionId, new(DataTargetMode.Cluster, "c", null), [new Uri("https://origin.test")],
new Security(Server), _manager.Acquire(connectionId), 1 << 22, 1, eligibleNodeIds: new HashSet<string> { "origin" });
var mapping = new RemoteNamespaceMapping
{
RemoteNamespaceMappingId = mappingId, DataConnectionId = connectionId, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe
| DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm,
MaxConditions = 10, ConditionStaleTimeoutMilliseconds = 60_000, ConditionSnapshotTimeoutMilliseconds = 60_000,
ConditionMethodTimeoutMilliseconds = 20_000, BranchName = mappingId, RemoteNamespaceUri = "https://zb.com/otopcua/raw",
RemoteIdentifierKind = "string", RemoteIdentifier = "Plant",
};
var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", "Plant"), DataRealm.Raw, mappingId, 1, "Plant/" + mappingId);
var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", mappingId] };
var placement = new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority());
var state = new DataPlaneAuthorityState();
var policy = new DataOperationPolicy(state, new TriePermissionEvaluator(state.Tries, TimeProvider.System), TimeProvider.System);
Access = new ProjectedConditionAccess(new Mappings([placement]), new Connections(new Hybrid(_grpc)), policy, () => new NoSink(),
TimeProvider.System, new ProjectedConditionOptions(TimeSpan.FromSeconds(30), 122_500, long.MaxValue, TimeSpan.FromSeconds(1)),
NullLogger.Instance);
_demand = Access.AcquireEventDemand(null); // opens the condition stream (the serving incarnation calls are addressed to)
Port = new Adapter(this);
}
public async ValueTask DisposeAsync()
{
_demand?.Dispose();
Access.Dispose();
await _grpc.DisposeAsync();
_manager.Dispose();
}
private sealed class Adapter(RealConditionMethodPath owner) : IProjectedConditionMethods
{
public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements,
DataConditionMethods method) => owner._gate.AuthorizeMethod(caller, placements, method);
public Task<DataConditionMethodResult> CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken) =>
owner.Access.CallAsync(call, cancellationToken);
}
/// <summary>The in-process origin: capabilities (Primary, conditions with every method) and a stalling method handler.</summary>
internal sealed class Origin(TimeSpan stall) : HttpMessageHandler
{
private static readonly DataLimits Limits = new(16, 16, 1 << 20, 16, 4, 1 << 20, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5));
private static readonly ServingIdentity Serving = new("origin", Incarnation, "Primary", 1, 1, 1);
public int MethodCalls;
public int MethodAnswers;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
{
var path = request.RequestUri!.AbsolutePath;
IMessage message;
if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal))
{
var asked = request.Headers.Contains("x-otopcua-data-features");
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, DataReadiness.Ready,
DataOperationSets.V1 | (asked ? DataOperationSets.ConditionGrants : DataOperations.None),
new HashSet<DataValueKind> { DataValueKind.Double }, Limits, false, 0, "c", true, true, true, true, true,
Conditions: asked ? new DataConditionCapabilities(true, 7, 1000) : null));
}
else
{
Interlocked.Increment(ref MethodCalls);
var bytes = await request.Content!.ReadAsByteArrayAsync(token);
_ = W.ConditionMethodRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray());
await Task.Delay(stall, token); // the origin's handler stalls
Interlocked.Increment(ref MethodAnswers);
message = DataConditionProtoMapper.EncodeMethodResponse(new(DataWriteState.AcceptedUnconfirmed, 0, "AcceptedUnconfirmed", Serving));
}
var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5];
BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5);
var ok = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) };
ok.Content.Headers.ContentType = new("application/grpc"); ok.TrailingHeaders.Add("grpc-status", "0");
return ok;
}
}
private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider
{
public event Action<string>? Changed { add { } remove { } }
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca1", "key", () => new NonDisposing(handler)));
}
private sealed class NonDisposing(HttpMessageHandler inner) : HttpMessageHandler
{
private readonly HttpMessageInvoker _invoker = new(inner, disposeHandler: false);
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
_invoker.SendAsync(request, cancellationToken);
}
private sealed class Mappings(IReadOnlyList<ProjectedMappingPlacement> current) : IProjectedConditionMappings
{
public IReadOnlyList<ProjectedMappingPlacement> Current { get; } = current;
public event Action? Changed { add { } remove { } }
}
private sealed class ActiveAuthority : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => 1;
public bool IsActive => true;
}
private sealed class Connections(IDataConnection connection) : IGrpcDataAdapterConnectionSource
{
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(connection));
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
/// <summary>The real gRPC connection for everything but the condition stream and root metadata (quiet stand-ins).</summary>
private sealed class Hybrid(GrpcDataConnection grpc) : IDataConnection, IDataPrimarySubscriptionSource, IDataConditionMethodService
{
public DataTarget Target => grpc.Target;
public TimeProvider Clock => grpc.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => grpc.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) =>
grpc.BrowseAsync(request, cancellationToken);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select(v => new DataItemResult<DataMetadata>("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());
public Task<IReadOnlyList<Core.Abstractions.DataConnections.ReadResult>> ReadAsync(Core.Abstractions.DataConnections.ReadRequest request,
CancellationToken cancellationToken) => grpc.ReadAsync(request, cancellationToken);
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => grpc.WriteAsync(request, cancellationToken);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => Task.FromResult<IDataSubscription>(new QuietStream());
public Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken) => SubscribeAsync(cancellationToken);
public Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken) =>
grpc.CallConditionMethodAsync(request, cancellationToken);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class QuietStream : IDataSubscription, IDataSubscriptionProvenance
{
private readonly CancellationTokenSource _closed = new();
public ServingIdentity Serving { get; } = new("origin", Incarnation, "Primary", 1, 1);
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) => Task.CompletedTask;
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _closed.Token);
try { await Task.Delay(Timeout.Infinite, linked.Token); }
catch (OperationCanceledException) { }
yield break;
}
public ValueTask DisposeAsync() { _closed.Cancel(); return ValueTask.CompletedTask; }
}
private sealed class NoSink : IProjectedConditionSink
{
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates) { }
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys) { }
public void MarkConnectionStale(string connectionId) { }
public void MarkConditionsStale(string connectionId, IReadOnlyCollection<string> conditionKeys) { }
public void RequireRefresh(string connectionId) { }
}
}
@@ -97,14 +97,51 @@ public sealed class GrpcDataConditionMethodClientTests
a.MethodCalls.ShouldBe(1);
}
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? methodTimeout = null)
[Fact]
public async Task Without_a_connection_ceiling_the_deadline_is_the_requests_budget_not_a_hidden_5s()
{
// A3b review S2: the per-mapping timeout rides RemainingBudget; a 30 s mapping must not be cut at a client-wide 5 s.
var a = new Endpoint("a");
await using var connection = Connect([a], methodTimeout: null, setCeiling: false);
(await connection.CallConditionMethodAsync(Request(budget: TimeSpan.FromSeconds(8)), Ct)).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
a.LastTimeout.ShouldNotBeNull().ShouldBeGreaterThan(TimeSpan.FromSeconds(6));
TimeSpan.FromTicks(a.LastRequest!.RemainingBudgetTicks).ShouldBeGreaterThan(TimeSpan.FromSeconds(6));
}
[Fact]
public async Task A_deadline_passing_after_send_is_OutcomeUnknown_with_BadTimeout_known_not_inferred()
{
var a = new Endpoint("a") { Hang = true };
await using var connection = Connect([a]);
var result = await connection.CallConditionMethodAsync(Request(budget: TimeSpan.FromMilliseconds(400)), Ct);
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
result.StatusCode.ShouldBe(0x800A0000u, "BadTimeout: the transport knows the deadline passed");
a.MethodCalls.ShouldBe(1);
}
[Fact]
public async Task An_invalid_request_is_RejectedBeforeDispatch_never_thrown()
{
var a = new Endpoint("a");
await using var connection = Connect([a]);
var result = await connection.CallConditionMethodAsync(Request() with { OperationId = new string('x', 10_000) }, Ct);
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
result.StatusCode.ShouldBe(0x80AB0000u);
a.MethodCalls.ShouldBe(0);
}
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? methodTimeout = null, bool setCeiling = true)
{
var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
var router = new Router(endpoints);
return new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), endpoints.Select(e => new Uri($"https://{e.Name}.test")),
new Security(router), manager.Acquire("link"), 1 << 22, endpoints.Length,
eligibleNodeIds: endpoints.Select(e => e.Name).ToHashSet()) { ConditionMethodTimeout = methodTimeout ?? TimeSpan.FromSeconds(5) };
var uris = endpoints.Select(e => new Uri($"https://{e.Name}.test")).ToArray();
var eligible = endpoints.Select(e => e.Name).ToHashSet();
return setCeiling
? new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), uris, new Security(router), manager.Acquire("link"), 1 << 22,
endpoints.Length, eligibleNodeIds: eligible) { ConditionMethodTimeout = methodTimeout ?? TimeSpan.FromSeconds(5) }
: new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), uris, new Security(router), manager.Acquire("link"), 1 << 22,
endpoints.Length, eligibleNodeIds: eligible);
}
private sealed class Endpoint(string name)
@@ -57,6 +57,44 @@ public sealed class GrpcDataProjectedConditionMethodTests
f.Access.AuthorizeMethod(f.Identity("reader"), [placement with { MappingId = "unknown" }], DataConditionMethods.Acknowledge).ShouldBeNull();
}
[Fact]
public async Task The_gate_routes_through_the_first_authorized_placement_and_refuses_a_realm_mismatch()
{
// A3b review S6: the real gate with several placements (the "first authorized placement" deviation) and a realm mismatch.
await using var f = new Fixture();
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe | NodePermissions.AlarmAcknowledge);
var good = f.Placement();
var realmMismatch = good with { Realm = DataRealm.Uns };
var unknownMapping = good with { MappingId = "map-x" };
var ungranted = good with { FolderLocalSubject = "Elsewhere/map-a/dev1" };
var alsoGood = good with { RelativePath = "dev1/HR200-b" };
var id = f.Identity("reader");
f.Access.AuthorizeMethod(id, [realmMismatch], DataConditionMethods.Acknowledge).ShouldBeNull("a placement's realm must be its mapping's");
f.Access.AuthorizeMethod(id, [unknownMapping, realmMismatch, good, alsoGood], DataConditionMethods.Acknowledge)
.ShouldNotBeNull().Placement.ShouldBe(good, "the first placement the caller passes the gate on, in primary order");
f.Access.AuthorizeMethod(id, [alsoGood, good], DataConditionMethods.Acknowledge).ShouldNotBeNull().Placement.ShouldBe(alsoGood);
f.Access.AuthorizeMethod(id, [ungranted], DataConditionMethods.Acknowledge).ShouldBeNull("the grant is on the placement's folder scope");
f.Access.AuthorizeMethod(id, [ungranted, good], DataConditionMethods.Acknowledge).ShouldNotBeNull().Placement.ShouldBe(good);
}
[Fact]
public async Task An_invalid_request_is_refused_unsent_before_the_lease()
{
// A3b review S3: a validation failure is RejectedBeforeDispatch, never an exception the node manager reads as "unknown".
await using var f = new Fixture();
using var demand = f.Access.AcquireEventDemand(null);
await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode != BadNoCommunication);
var acquired = f.Connections.Acquired;
var sent = f.Connections.Sent.Count;
var result = await f.Access.CallAsync(f.Call() with { OperationId = new string('x', 10_000) }, TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
result.StatusCode.ShouldBe(0x80AB0000u);
f.Connections.Sent.Count.ShouldBe(sent);
f.Connections.Acquired.ShouldBe(acquired, "not even leased");
}
[Fact]
public async Task With_no_open_condition_stream_a_call_is_BadNoCommunication_and_nothing_is_sent()
{