feat(grpc-data): A3b ICallAsyncNodeManager — claim imported-condition calls, base.Call unchanged for the rest, lock-free remote dispatch, EventId registry gate + N6 re-binding
This commit is contained in:
@@ -0,0 +1,351 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Server;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
/// <summary>
|
||||
/// A3b (plan §5.6 step 2): where an authorized remote condition method goes — the placement the origin resolves (one the
|
||||
/// caller passed the mapping gate on, primary order first) and that mapping's <c>ConditionMethodTimeoutMilliseconds</c>.
|
||||
/// </summary>
|
||||
/// <param name="Placement">The placement to dispatch through.</param>
|
||||
/// <param name="Timeout">The mapping's method ceiling (default 5 s).</param>
|
||||
public sealed record ImportedConditionMethodRoute(ImportedConditionPlacement Placement, TimeSpan Timeout);
|
||||
|
||||
/// <summary>
|
||||
/// A3b (plan §5.6 step 4): one remote condition method the consumer's node manager hands to its condition runtime. Never
|
||||
/// carries the local caller's credentials: the origin sees the connection's service principal; <see cref="OnBehalfOf"/> is
|
||||
/// audit text only.
|
||||
/// </summary>
|
||||
/// <param name="ConnectionId">The connection the condition was imported over.</param>
|
||||
/// <param name="ConditionKey">The origin's opaque key (diagnostics only; the origin resolves <see cref="Placement"/>).</param>
|
||||
/// <param name="Placement">The placement to address the origin with.</param>
|
||||
/// <param name="Method">Exactly one method.</param>
|
||||
/// <param name="ExpectedActivation">The marker of the latest applied record (T3).</param>
|
||||
/// <param name="Comment">The Part 9 comment, or null.</param>
|
||||
/// <param name="OperationId">A fresh id per dispatched call (the origin joins duplicates of it, never retried here).</param>
|
||||
/// <param name="RemainingBudget">min(request deadline, the mapping's method ceiling) minus what was already spent.</param>
|
||||
/// <param name="OnBehalfOf">The local caller's principal, for the origin's audit log.</param>
|
||||
public sealed record ImportedConditionMethodCall(string ConnectionId, string ConditionKey, ImportedConditionPlacement Placement,
|
||||
DataConditionMethods Method, DataActivationMarker ExpectedActivation, string? Comment, string OperationId, TimeSpan RemainingBudget,
|
||||
string? OnBehalfOf);
|
||||
|
||||
/// <summary>
|
||||
/// A3b (plan §5.6): the consumer condition runtime's method port. SDK-free apart from the identity type.
|
||||
/// </summary>
|
||||
public interface IProjectedConditionMethods
|
||||
{
|
||||
/// <summary>
|
||||
/// The per-caller gate (re-evaluated for every local caller — the stream itself runs under the connection's service
|
||||
/// principal): the caller's <c>AlarmAcknowledge</c> (Acknowledge, AddComment) or <c>AlarmConfirm</c> (Confirm) grant on
|
||||
/// the placement's folder scope, on a current, condition-bearing mapping that itself grants the method's bit, with a
|
||||
/// usable key (#563). Regardless of <c>Security:Acl:Enabled</c>. Null = denied.
|
||||
/// </summary>
|
||||
ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements,
|
||||
DataConditionMethods method);
|
||||
|
||||
/// <summary>One remote call. Answers, never throws for a remote failure; never retried.</summary>
|
||||
Task<DataConditionMethodResult> CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A3b (plan §5.6 step 1): the Call service's interception point for imported conditions. The SDK's
|
||||
/// <c>AsyncNodeManagerAdapter</c> forwards <c>CallAsync</c> to a wrapped manager only when it implements
|
||||
/// <see cref="ICallAsyncNodeManager"/>; otherwise it runs the synchronous <c>Call</c>, which takes <c>Lock</c> per request.
|
||||
/// </summary>
|
||||
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>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);
|
||||
|
||||
private readonly SemaphoreSlim _importedMethodSlots = new(DefaultImportedMethodConcurrency, DefaultImportedMethodConcurrency);
|
||||
private readonly ConcurrentDictionary<string, Task<ServiceResult>> _importedMethodsInFlight = new(StringComparer.Ordinal);
|
||||
private long _importedMethodsDispatched, _importedMethodsJoined, _importedMethodsRefused;
|
||||
|
||||
/// <summary>A3b: the consumer's remote condition method port (null ⇒ every imported method is <c>BadNotSupported</c>).</summary>
|
||||
public IProjectedConditionMethods? ProjectedConditionMethods { get; set; }
|
||||
|
||||
/// <summary>Remote condition methods handed to the port (test/diagnostic observation).</summary>
|
||||
internal long ImportedMethodsDispatched => Interlocked.Read(ref _importedMethodsDispatched);
|
||||
|
||||
/// <summary>Calls that joined an identical call already in flight instead of dispatching again.</summary>
|
||||
internal long ImportedMethodsJoined => Interlocked.Read(ref _importedMethodsJoined);
|
||||
|
||||
/// <summary>Imported-condition calls refused locally (nothing sent).</summary>
|
||||
internal long ImportedMethodsRefused => Interlocked.Read(ref _importedMethodsRefused);
|
||||
|
||||
/// <summary>
|
||||
/// §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.
|
||||
/// </summary>
|
||||
public override async ValueTask CallAsync(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall,
|
||||
IList<CallMethodResult> results, IList<ServiceResult> errors, CancellationToken cancellationToken = default)
|
||||
{
|
||||
List<int>? claimed = null;
|
||||
for (var i = 0; i < methodsToCall.Count; i++)
|
||||
{
|
||||
var request = methodsToCall[i];
|
||||
if (request is null || request.Processed || !IsImportedConditionId(request.ObjectId)) continue;
|
||||
request.Processed = true;
|
||||
(claimed ??= []).Add(i);
|
||||
}
|
||||
|
||||
base.Call(context, methodsToCall, results, errors);
|
||||
if (claimed is null) return;
|
||||
|
||||
var caller = context.UserIdentity as RoleCarryingUserIdentity;
|
||||
var deadline = context.OperationDeadline;
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken);
|
||||
var calls = new Task<ServiceResult>[claimed.Count];
|
||||
for (var k = 0; k < claimed.Count; k++)
|
||||
{
|
||||
results[claimed[k]] = new CallMethodResult();
|
||||
calls[k] = CallImportedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token);
|
||||
}
|
||||
var outcomes = await Task.WhenAll(calls).ConfigureAwait(false);
|
||||
for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = outcomes[k];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// §5.6 steps 2–5 for one claimed request. Every refusal returns before anything is sent; nothing here changes local
|
||||
/// condition state — the origin applies, reports and streams, and the record's arrival changes the node (§5.3).
|
||||
/// </summary>
|
||||
private async Task<ServiceResult> CallImportedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var started = Stopwatch.GetTimestamp();
|
||||
try
|
||||
{
|
||||
if (!request.ObjectId.TryGetValue(out string objectIdentifier)
|
||||
|| !ImportedConditionIds.TryParse(objectIdentifier, out var conditionIdentifier, out _, out _, out _)
|
||||
|| _importedConditions.Find(new NodeId(conditionIdentifier, request.ObjectId.NamespaceIndex)) is not { } condition)
|
||||
return Refuse(StatusCodes.BadNodeIdUnknown);
|
||||
var method = ImportedMethodOf(request.MethodId, conditionIdentifier);
|
||||
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.
|
||||
var placements = condition.Placements;
|
||||
var route = port.AuthorizeMethod(caller, placements, method);
|
||||
if (route is null || caller is null) return Refuse(StatusCodes.BadUserAccessDenied);
|
||||
if (method == DataConditionMethods.Confirm && condition.IsNative) return Refuse(StatusCodes.BadNotSupported);
|
||||
if (condition.SupportedMethods is { } supported && (supported & (uint)method) == 0) return Refuse(StatusCodes.BadNotSupported);
|
||||
if (_standby.RefusesMutations) { Interlocked.Increment(ref _importedMethodsRefused); return WarmStandbyState.StandbyRefusal($"call {DataConditionMethodSets.Part9Name(method)}"); }
|
||||
if (!TryReadMethodArguments(request.InputArguments, out var eventId, out var comment, out var argumentError))
|
||||
return Refuse(argumentError);
|
||||
|
||||
// EventId: minted by this consumer for this condition under the SAME marker as the latest applied record (N6/T3).
|
||||
DataActivationMarker? expected = null;
|
||||
lock (condition.MethodGate)
|
||||
{
|
||||
foreach (var (id, activation) in condition.RecentEvents)
|
||||
{
|
||||
if (id != eventId) continue;
|
||||
if (activation is not null && activation == condition.Activation) expected = activation;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (expected is null) return Refuse(StatusCodes.BadEventIdUnknown);
|
||||
|
||||
// An identical call already in flight (same caller, condition, EventId, method, comment) joins it: one dispatch.
|
||||
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);
|
||||
var existing = _importedMethodsInFlight.GetOrAdd(key, mine.Task);
|
||||
if (!ReferenceEquals(existing, mine.Task))
|
||||
{
|
||||
Interlocked.Increment(ref _importedMethodsJoined);
|
||||
return await existing.ConfigureAwait(false);
|
||||
}
|
||||
try
|
||||
{
|
||||
var result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
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));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or FormatException)
|
||||
{
|
||||
return Refuse(StatusCodes.BadInvalidArgument);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ServiceResult> DispatchImportedAsync(IProjectedConditionMethods port, ImportedCondition condition,
|
||||
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;
|
||||
if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue)
|
||||
{
|
||||
var left = deadline - DateTime.UtcNow;
|
||||
if (left < budget) budget = left;
|
||||
}
|
||||
budget -= Stopwatch.GetElapsedTime(started);
|
||||
if (budget <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout);
|
||||
|
||||
if (!await _importedMethodSlots.WaitAsync(budget, cancellationToken).ConfigureAwait(false))
|
||||
return Refuse(StatusCodes.BadTooManyOperations);
|
||||
try
|
||||
{
|
||||
var remaining = budget - Stopwatch.GetElapsedTime(started);
|
||||
if (remaining <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout);
|
||||
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);
|
||||
bounded.CancelAfter(remaining + ImportedMethodGrace);
|
||||
Interlocked.Increment(ref _importedMethodsDispatched);
|
||||
DataConditionMethodResult result;
|
||||
try
|
||||
{
|
||||
result = await port.CallAsync(call, bounded.Token).WaitAsync(remaining + ImportedMethodGrace, CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
// The port did not answer inside the budget: it may have reached the origin — OutcomeUnknown, never retried.
|
||||
return Unknown(StatusCodes.BadTimeout, "OutcomeUnknown: no answer within the condition method timeout.");
|
||||
}
|
||||
catch (OperationCanceledException) when (bounded.IsCancellationRequested)
|
||||
{
|
||||
return Unknown(cancellationToken.IsCancellationRequested ? StatusCodes.BadCommunicationError : StatusCodes.BadTimeout,
|
||||
"OutcomeUnknown: the call was cancelled after dispatch.");
|
||||
}
|
||||
return MapOutcome(result, Stopwatch.GetElapsedTime(started) >= budget);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_importedMethodSlots.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.
|
||||
/// </summary>
|
||||
internal ServiceResult MapOutcome(DataConditionMethodResult result, bool budgetElapsed)
|
||||
{
|
||||
switch (result.State)
|
||||
{
|
||||
case DataWriteState.DriverConfirmedSuccess:
|
||||
case DataWriteState.AcceptedUnconfirmed:
|
||||
return StatusCode.IsBad(new StatusCode(result.StatusCode)) ? new ServiceResult(new StatusCode(result.StatusCode)) : ServiceResult.Good;
|
||||
case DataWriteState.RejectedBeforeDispatch:
|
||||
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,
|
||||
"OutcomeUnknown: " + (result.Diagnostic ?? "the origin's outcome is unknown."));
|
||||
}
|
||||
}
|
||||
|
||||
private ServiceResult Unknown(StatusCode status, string diagnostic)
|
||||
{
|
||||
_logger.LogWarning("OtOpcUaNodeManager: imported condition method outcome unknown ({Status}): {Diagnostic}", status, diagnostic);
|
||||
return new ServiceResult(status, new LocalizedText(diagnostic));
|
||||
}
|
||||
|
||||
private ServiceResult Refuse(StatusCode status)
|
||||
{
|
||||
Interlocked.Increment(ref _importedMethodsRefused);
|
||||
return new ServiceResult(status);
|
||||
}
|
||||
|
||||
/// <summary>The Part 9 method a MethodId names: the type's declaration or this condition's instance child.</summary>
|
||||
private static DataConditionMethods ImportedMethodOf(NodeId methodId, string conditionIdentifier)
|
||||
{
|
||||
if (methodId == MethodIds.AcknowledgeableConditionType_Acknowledge) return DataConditionMethods.Acknowledge;
|
||||
if (methodId == MethodIds.AcknowledgeableConditionType_Confirm) return DataConditionMethods.Confirm;
|
||||
if (methodId == MethodIds.ConditionType_AddComment) return DataConditionMethods.AddComment;
|
||||
if (!methodId.TryGetValue(out string identifier)
|
||||
|| !ImportedConditionIds.TryParse(identifier, out var owner, out _, out _, out var path)
|
||||
|| !string.Equals(owner, conditionIdentifier, StringComparison.Ordinal)) return DataConditionMethods.None;
|
||||
return path switch
|
||||
{
|
||||
"Acknowledge" => DataConditionMethods.Acknowledge,
|
||||
"Confirm" => DataConditionMethods.Confirm,
|
||||
"AddComment" => DataConditionMethods.AddComment,
|
||||
_ => DataConditionMethods.None,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Acknowledge / Confirm / AddComment all take (EventId ByteString, Comment LocalizedText).</summary>
|
||||
private static bool TryReadMethodArguments(ArrayOf<Variant> arguments, out ByteString eventId, out string? comment, out StatusCode error)
|
||||
{
|
||||
eventId = default; comment = null; error = StatusCodes.Good;
|
||||
if (arguments.Count < 2) { error = StatusCodes.BadArgumentsMissing; return false; }
|
||||
if (arguments.Count > 2) { error = StatusCodes.BadTooManyArguments; return false; }
|
||||
if (!arguments[0].TryGetValue(out eventId) || eventId.IsEmpty) { error = StatusCodes.BadTypeMismatch; return false; }
|
||||
if (arguments[1].IsNull) return true;
|
||||
if (!arguments[1].TryGetValue(out LocalizedText text)) { error = StatusCodes.BadTypeMismatch; return false; }
|
||||
comment = string.IsNullOrEmpty(text.Text) ? null : text.Text;
|
||||
if (comment is { Length: > DataConditionMethodRequest.MaxCommentLength }) { error = StatusCodes.BadInvalidArgument; return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// N6 (§5.6 step 3) after a record that changed no state. A moved marker re-binds the retained EventIds only when the
|
||||
/// record's <c>time</c> equals the one they were bound under (F6); otherwise a fresh EventId is bound to the new marker
|
||||
/// (so a ConditionRefresh returns an ackable one) and the caller queues RefreshRequired. A condition with no bound
|
||||
/// EventId yet (its first record reported nothing) gets one. Under <c>Lock</c> (the apply path).
|
||||
/// </summary>
|
||||
/// <returns>True when retained EventIds were invalidated (RefreshRequired).</returns>
|
||||
private bool RebindImportedEventIds(ImportedCondition condition, DataActivationMarker? previous, DateTimeOffset? previousTime,
|
||||
DataConditionState state)
|
||||
{
|
||||
var current = state.Activation;
|
||||
lock (condition.MethodGate)
|
||||
{
|
||||
if (condition.RecentEvents.Count == 0)
|
||||
{
|
||||
MintImportedEventId(condition, current);
|
||||
return false;
|
||||
}
|
||||
if (previous is null || current is null || previous == current) return false;
|
||||
if (state.TimeUtc is { } time && previousTime == time)
|
||||
{
|
||||
var node = condition.RecentEvents.First;
|
||||
while (node is not null)
|
||||
{
|
||||
if (node.Value.Activation == previous) node.Value = (node.Value.EventId, current);
|
||||
node = node.Next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
MintImportedEventId(condition, current);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void MintImportedEventId(ImportedCondition condition, DataActivationMarker? activation)
|
||||
{
|
||||
if (condition.Alarm.EventId is not { } field) return;
|
||||
var eventId = ByteString.From(Guid.NewGuid().ToByteArray());
|
||||
field.Value = eventId;
|
||||
condition.RecentEvents.AddFirst((eventId, activation));
|
||||
while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast();
|
||||
}
|
||||
}
|
||||
@@ -23,9 +23,18 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec
|
||||
public HashSet<FolderState> Folders { get; } = new(ReferenceEqualityComparer.Instance);
|
||||
/// <summary>The last origin record applied (state known), re-applied with another Quality on staleness.</summary>
|
||||
public AlarmConditionSnapshot? Last { get; set; }
|
||||
/// <summary>The marker of the latest applied record. Written under <see cref="MethodGate"/> (A3b reads it without <c>Lock</c>).</summary>
|
||||
public DataActivationMarker? Activation { get; set; }
|
||||
/// <summary>N6: consumer-minted EventIds of this condition's recent events → the activation marker each described.</summary>
|
||||
/// <summary>N6: consumer-minted EventIds of this condition's recent events → the activation marker each described.
|
||||
/// Mutated and read under <see cref="MethodGate"/>.</summary>
|
||||
public LinkedList<(ByteString EventId, DataActivationMarker? Activation)> RecentEvents { get; } = new();
|
||||
/// <summary>A3b (§5.6 step 2): the small EventId registry's own lock — a remote method resolves its EventId and the current
|
||||
/// 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; }
|
||||
/// <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>
|
||||
public long PlacementVersion { get; set; }
|
||||
/// <summary>Native (driver-fed) at the origin: Confirm / shelve / enable have no upstream path.</summary>
|
||||
@@ -216,9 +225,9 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
public bool TryResolveImportedEvent(NodeId conditionId, ByteString eventId, out ImportedConditionBinding? binding)
|
||||
{
|
||||
binding = null;
|
||||
lock (Lock)
|
||||
if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false;
|
||||
lock (c.MethodGate)
|
||||
{
|
||||
if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false;
|
||||
foreach (var (id, activation) in c.RecentEvents)
|
||||
{
|
||||
if (id != eventId) continue;
|
||||
@@ -238,6 +247,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(updates);
|
||||
EnsureAddressSpaceCreated();
|
||||
var refresh = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var start = 0; start < updates.Count; start += ImportedApplyChunk)
|
||||
{
|
||||
lock (Lock)
|
||||
@@ -246,7 +256,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
var index = ProjectedFolderIndex();
|
||||
for (var i = start; i < Math.Min(updates.Count, start + ImportedApplyChunk); i++)
|
||||
{
|
||||
try { ApplyImported(updates[i], index); }
|
||||
try { if (ApplyImported(updates[i], index)) refresh.Add(updates[i].ConnectionId); }
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ServiceResultException)
|
||||
{
|
||||
_logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition update refused (connection {Connection})",
|
||||
@@ -255,6 +265,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
}
|
||||
}
|
||||
}
|
||||
// N6 (G4 step 3): a resync that left retained EventIds un-re-bindable ⇒ RefreshRequired, outside Lock.
|
||||
foreach (var connectionId in refresh) RequireRefresh(connectionId);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -323,7 +335,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
// Materialise / apply / remove (under Lock)
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
private void ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders)
|
||||
/// <returns>True when a resync left retained EventIds un-re-bindable (the caller queues RefreshRequired).</returns>
|
||||
private bool ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders)
|
||||
{
|
||||
var state = update.State;
|
||||
if (update.Placements.Count == 0) throw new ArgumentException("An imported condition needs a placement.", nameof(update));
|
||||
@@ -331,7 +344,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
if (state.Removed)
|
||||
{
|
||||
if (_importedConditions.Find(id) is { } gone) RemoveImported(gone);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
var condition = _importedConditions.Find(id);
|
||||
@@ -364,9 +377,10 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
|
||||
UpdatePlacements(condition, update.Placements, folders);
|
||||
if (condition.Alarm.SourceName is { } sourceName) sourceName.Value = update.SourceName; // display only; rides the next event
|
||||
if ((update.Info ?? state.Info) is { } listed) condition.SupportedMethods = listed.SupportedMethods;
|
||||
|
||||
// §5.1 T2: a record with state_known = false never changes the consumer's last state.
|
||||
if (!state.StateKnown) return;
|
||||
if (!state.StateKnown) return false;
|
||||
var snapshot = new AlarmConditionSnapshot(state.Active, state.Acknowledged, state.Confirmed, state.Enabled,
|
||||
Enum.IsDefined(typeof(AlarmShelvingKind), state.Shelving) ? (AlarmShelvingKind)state.Shelving : AlarmShelvingKind.Unshelved,
|
||||
(ushort)Math.Clamp(state.Severity, 1u, 1000u), state.Message ?? "", state.Quality,
|
||||
@@ -375,9 +389,17 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
var ts = state.TimeUtc?.UtcDateTime ?? UtcNow;
|
||||
if (condition.Alarm.Comment is { } comment && state.Comment is not null) comment.Value = new LocalizedText(state.Comment);
|
||||
if (condition.Alarm.ClientUserId is { } user && state.ClientUserId is not null) user.Value = state.ClientUserId;
|
||||
condition.Activation = state.Activation;
|
||||
var previous = condition.Activation;
|
||||
var previousTime = condition.LastTime;
|
||||
lock (condition.MethodGate) condition.Activation = state.Activation;
|
||||
condition.Last = snapshot;
|
||||
if (ApplyConditionState(condition.Alarm, snapshot, ts)) ReportImported(condition, ts);
|
||||
condition.LastTime = state.TimeUtc;
|
||||
if (ApplyConditionState(condition.Alarm, snapshot, ts))
|
||||
{
|
||||
ReportImported(condition, ts);
|
||||
return false;
|
||||
}
|
||||
return RebindImportedEventIds(condition, previous, previousTime, state);
|
||||
}
|
||||
|
||||
/// <summary>Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter.</summary>
|
||||
@@ -387,8 +409,11 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
Interlocked.Increment(ref _importedEventsReported);
|
||||
if (condition.Alarm.EventId?.Value is { } eventId)
|
||||
{
|
||||
condition.RecentEvents.AddFirst((eventId, condition.Activation));
|
||||
while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast();
|
||||
lock (condition.MethodGate)
|
||||
{
|
||||
condition.RecentEvents.AddFirst((eventId, condition.Activation));
|
||||
while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user