feat(grpc-data): A2b — consumer CallConditionMethodAsync (no retry, OutcomeUnknown after send), validator + AdminUI method bits, Galaxy opt-in checkbox, capacity warnings at the deploy gate

This commit is contained in:
Joseph Doherty
2026-11-24 13:33:36 -05:00
parent 1e78c64b92
commit f6c9c9d7fe
7 changed files with 136 additions and 3 deletions
@@ -118,6 +118,7 @@ else
<label class="form-label" for="export-history-page">History values per page</label><input id="export-history-page" type="number" min="1" max="@DataConnectionValidator.MaxHistoryValuesPerPageLimit" class="form-control mb-2" @bind="e.MaxHistoryValuesPerPage" />
<label class="form-label" for="export-history-bytes">History response bytes</label><input id="export-history-bytes" type="number" min="@DataConnectionValidator.MinHistoryResponseBytesLimit" max="@DataConnectionValidator.MaxHistoryResponseBytesLimit" class="form-control mb-2" @bind="e.MaxHistoryResponseBytes" /><div class="form-text">Larger answers are sent in bounded chunks.</div>
<label class="form-label" for="export-max-conditions">Conditions per alarm subscription</label><input id="export-max-conditions" type="number" min="1" max="@DataConnectionValidator.MaxConditionsLimit" class="form-control mb-2" @bind="e.MaxConditions" /><div class="form-text">A remote AlarmSubscribe scope with more conditions than this is refused (ConditionCapacity) before anything is imported.</div>
<label class="d-block"><input id="export-galaxy-ack" type="checkbox" @bind="e.AllowGalaxyServiceAck" disabled="@(!e.AllowedOperations.HasFlag(DataOperations.AlarmAcknowledge) && !e.AllowGalaxyServiceAck)" /> Allow remote acknowledge of Galaxy alarms</label><div class="form-text">Galaxy-sourced alarms are acknowledged under this peer's API-key Galaxy ack identity (provision <code>otopcua/apikeys/&lt;keyId&gt;/galaxy-ack-user</code> and <code>…/galaxy-ack-password</code> on this cluster). Requires AlarmAcknowledge.</div>
<label><input type="checkbox" @bind="e.Enabled" /> Enabled in next deployment</label>@Actions(e, e.DataExportRowId != Guid.Empty)
</div></section>
}
@@ -13,7 +13,7 @@ public static class DataOperationAuthoring
/// <summary>The operation bits an operator can tick, in display order.</summary>
public static IReadOnlyList<DataOperations> AuthorableOperations { get; } =
[DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Subscribe, DataOperations.Write, DataOperations.HistoryRead,
DataOperations.AlarmSubscribe];
DataOperations.AlarmSubscribe, DataOperations.AlarmAcknowledge, DataOperations.AlarmConfirm];
/// <summary>The checkbox label of a bit.</summary>
public static string Label(DataOperations operation) => operation.ToString();
@@ -489,6 +489,10 @@ public sealed class AdminOperationsActor : ReceiveActor
foreach (var w in writableWarnings)
_log.Warning("StartDeployment: Sql writable mismatch (non-blocking): {Warning}", w);
// A2b (plan §6): Σ MaxConditions × 49 of a consumer node's alarm mappings over the host cap — non-blocking.
foreach (var w in DataConnectionValidator.DeployWarnings(draft))
_log.Warning("StartDeployment: data-connection warning (non-blocking): {Warning}", w);
if (errors.Count > 0)
{
var summary = string.Join("; ", errors.Select(e => $"[{e.Code}] {e.Message}"));
@@ -0,0 +1,99 @@
using Grpc.Core;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>
/// A2b consumer side of <c>CallConditionMethod</c> (plan §5.6 consumer steps 4–5). One bounded call: deadline =
/// min(the request's remaining budget, <see cref="ConditionMethodTimeout"/> — the mapping's
/// <c>ConditionMethodTimeoutMilliseconds</c>, 5 s by default). Only an endpoint that advertised <c>conditions</c> with
/// the method, is Primary and serves the incarnation the caller expects is eligible; nothing is dispatched otherwise.
/// <b>No retry anywhere:</b> once the request has been handed to the transport, a failure answers
/// <see cref="DataWriteState.OutcomeUnknown"/> (<c>BadCommunicationError</c>) and no other endpoint is tried — the
/// origin may have applied it, and a duplicate operation id would only join there anyway.
/// </summary>
public sealed partial class GrpcDataConnection : IDataConditionMethodService
{
internal const uint BadCommunicationError = 0x80050000u;
private TimeSpan _conditionMethodTimeout = TimeSpan.FromSeconds(5);
/// <summary>The per-call method ceiling (the mapping's <c>ConditionMethodTimeoutMilliseconds</c>; A3 binds it per mapping).</summary>
public TimeSpan ConditionMethodTimeout
{
get => _conditionMethodTimeout;
init => _conditionMethodTimeout = value > TimeSpan.Zero ? value : throw new ArgumentOutOfRangeException(nameof(value));
}
/// <summary>Remote condition method (<see cref="IDataConditionMethodService"/>).</summary>
public async Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
request.Validate();
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.");
var budget = new DataBudget(deadline, 1, Math.Min(_maxMessageBytes, 1 << 20));
EnterWork();
var admitted = false;
try
{
using var admission = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, _shutdown.Token);
admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false);
if (!admitted) return new(DataWriteState.RejectedBeforeDispatch, BadTooManyOperations, "Unary capacity exhausted.");
var unsupported = false;
foreach (var endpoint in _endpoints)
{
Check();
cancellationToken.ThrowIfCancellationRequested();
Selected selected;
try { selected = await SelectAsync(endpoint, start, budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
catch (Exception ex) when (!cancellationToken.IsCancellationRequested
&& ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException or ArgumentException)
{ RecordFailure(ex); continue; }
var caps = selected.Capabilities;
if (caps.Conditions is null || (caps.Conditions.Methods & (uint)request.Method) == 0
|| !caps.Operations.HasFlag(DataConditionMethodSets.OperationFor(request.Method))
|| !string.Equals(caps.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
|| !string.Equals(caps.Serving.Incarnation, request.ExpectedServingIncarnation, StringComparison.Ordinal))
{ unsupported = true; continue; }
TimeSpan remaining;
try { remaining = Remaining(start, budget); }
catch (TimeoutException) { return new(DataWriteState.RejectedBeforeDispatch, BadTimeout, "Budget expired before dispatch."); }
var wire = DataConditionProtoMapper.EncodeMethodRequest(request with { RemainingBudget = remaining });
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken,
selected.Channel.Retired.Token, _shutdown.Token);
var options = new CallOptions(Headers(selected.Channel, RequestedFeatures(caps)), DateTime.UtcNow + remaining, linked.Token);
// From here on the request may reach the origin: never retried, never moved to another endpoint.
try
{
var response = await selected.Channel.Client.CallConditionMethodAsync(wire, options).ResponseAsync.ConfigureAwait(false);
var result = DataConditionProtoMapper.DecodeMethodResponse(response);
if (result.Serving is { } serving && (serving.NodeId != caps.Serving.NodeId || serving.Incarnation != caps.Serving.Incarnation))
return new(DataWriteState.OutcomeUnknown, BadCommunicationError, "OutcomeUnknown: the answer came from another serving incarnation.");
return result;
}
catch (RpcException ex) when (ex.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented
or StatusCode.InvalidArgument or StatusCode.PermissionDenied or StatusCode.Unauthenticated)
{
// Refused by the transport before the origin facade ran: nothing was applied.
return new(DataWriteState.RejectedBeforeDispatch,
ex.StatusCode is StatusCode.PermissionDenied or StatusCode.Unauthenticated ? 0x801F0000u : BadNotSupportedMethod,
"Refused by the origin transport: " + ex.StatusCode);
}
catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException
or ArgumentException or IOException)
{
if (cancellationToken.IsCancellationRequested && ex is OperationCanceledException) throw;
return new(DataWriteState.OutcomeUnknown, BadCommunicationError, "OutcomeUnknown: the transport failed after the request was sent.");
}
}
return new(DataWriteState.RejectedBeforeDispatch, unsupported ? BadNotSupportedMethod : BadNoCommunication,
unsupported ? "No Primary endpoint serves this condition method." : "No ready endpoint.");
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
}
private const uint BadNotSupportedMethod = 0x803D0000u;
}