using System.Collections.Immutable;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
///
/// The lock-free snapshot the OPC UA node manager consults to refuse, synchronously, a native-condition
/// Acknowledge the owning driver would refuse anyway (lmxopcua#760). owns
/// the condition → driver map and the driver objects, and publishes a fresh immutable snapshot whenever
/// either changes; is a single volatile read, safe under the SDK node-manager lock.
///
///
/// Racy by design against a change published a moment later — it covers static misconfiguration only. An
/// ack it lets through can still be refused or fail at the driver; that path reverts the condition to
/// unacknowledged ('s NativeAlarmAckFailed handling).
///
public sealed class NativeAlarmAckPreflightView
{
private volatile ImmutableDictionary _byConditionNodeId =
ImmutableDictionary.Empty.WithComparers(StringComparer.Ordinal);
private volatile string? _hostUnavailableReason;
///
/// Returns why the driver owning would refuse an acknowledge from a
/// session authenticated with , or null to proceed (unknown condition, a
/// driver without a pre-check, or one that cannot tell without I/O).
///
/// The bare condition NodeId identifier the node manager routes by.
/// The session's API key id, or null for anonymous.
/// The refusal reason, or null.
public string? Check(string conditionNodeId, string? apiKeyId)
{
if (string.IsNullOrEmpty(conditionNodeId)) return null;
// A host that cannot route any native ack (Stale — lmxopcua#765) refuses every one, whatever its driver.
if (_hostUnavailableReason is { } unavailable) return unavailable;
if (!_byConditionNodeId.TryGetValue(conditionNodeId, out var preflight)) return null;
try
{
return preflight.GetAcknowledgeRefusal(apiKeyId);
}
catch
{
// A buggy pre-check must never break the Part 9 method path; let the ack proceed (the driver's own
// refusal + the host's revert still apply).
return null;
}
}
///
/// Marks the whole driver host unable to route a native acknowledge (lmxopcua#765): while set,
/// refuses every condition with . Null clears it. Called by
/// only — set on entering Stale, cleared on returning to Steady.
///
/// Why no native ack can be routed, or null when acks are routable.
internal void SetHostUnavailable(string? reason) => _hostUnavailableReason = reason;
/// Replaces the snapshot. Called by only.
/// Condition NodeId → the owning driver's pre-check.
internal void Publish(IEnumerable> byConditionNodeId) =>
_byConditionNodeId = ImmutableDictionary.CreateRange(StringComparer.Ordinal, byConditionNodeId);
}