feat: preserve grpc write admission and uncertain outcomes

This commit is contained in:
Joseph Doherty
2026-11-16 03:56:13 -05:00
parent 8f28a0eabf
commit 862dbc8e90
37 changed files with 3686 additions and 70 deletions
@@ -1,3 +1,5 @@
using System.Security.Cryptography;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
public enum DataValueKind { Unspecified = 0, Null = 1, Boolean = 2, Int8 = 3, Int16 = 4, Int32 = 5, Int64 = 6, UInt8 = 7, UInt16 = 8, UInt32 = 9, UInt64 = 10, Float = 11, Double = 12, String = 13, Bytes = 14, Timestamp = 15, Guid = 16, Array = 17 }
@@ -90,6 +92,32 @@ public sealed class DataValue : IDisposable
public DataValueKind ArrayElementKind { get { ThrowIfDisposed(); return (_payload as ArrayPayload)?.Kind ?? throw new InvalidOperationException(); } }
public IReadOnlyList<object> GetArray() { ThrowIfDisposed(); return _payload is ArrayPayload a ? Array.AsReadOnly((object[])a.Elements.Clone()) : throw new InvalidOperationException(); }
public DataValue Retain() { ThrowIfDisposed(); return new(Kind, _payload, Dimensions); }
/// <summary>Appends a private canonical value encoding without exposing or copying owned payload storage.</summary>
internal void AppendSemanticFingerprint(IncrementalHash hash)
{
ArgumentNullException.ThrowIfNull(hash);
ThrowIfDisposed();
DataFingerprintEncoding.AppendInt32(hash, 1);
DataFingerprintEncoding.AppendInt32(hash, (int)Kind);
if (Kind == DataValueKind.Null) return;
if (Kind == DataValueKind.Bytes)
{
var bytes = (byte[])_payload!;
DataFingerprintEncoding.AppendInt32(hash, bytes.Length);
hash.AppendData(bytes);
return;
}
if (_payload is ArrayPayload array)
{
DataFingerprintEncoding.AppendInt32(hash, (int)array.Kind);
DataFingerprintEncoding.AppendInt32(hash, Dimensions!.Count);
for (var i = 0; i < Dimensions.Count; i++) DataFingerprintEncoding.AppendInt32(hash, Dimensions[i]);
DataFingerprintEncoding.AppendInt32(hash, array.Elements.Length);
foreach (var element in array.Elements) DataFingerprintEncoding.AppendScalar(hash, array.Kind, element);
return;
}
DataFingerprintEncoding.AppendScalar(hash, Kind, _payload!);
}
public void Dispose() => _disposed = true;
private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this);
private sealed record ArrayPayload(DataValueKind Kind, object[] Elements);
@@ -0,0 +1,69 @@
using System.Buffers.Binary;
using System.Security.Cryptography;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
// Internal fingerprint framing only. This is not a transport or persisted format.
internal static class DataFingerprintEncoding
{
internal static void AppendByte(IncrementalHash hash, byte value)
{
Span<byte> scratch = stackalloc byte[1];
scratch[0] = value;
hash.AppendData(scratch);
}
internal static void AppendInt32(IncrementalHash hash, int value)
{
Span<byte> scratch = stackalloc byte[4];
BinaryPrimitives.WriteInt32LittleEndian(scratch, value);
hash.AppendData(scratch);
}
internal static void AppendInt64(IncrementalHash hash, long value)
{
Span<byte> scratch = stackalloc byte[8];
BinaryPrimitives.WriteInt64LittleEndian(scratch, value);
hash.AppendData(scratch);
}
internal static void AppendString(IncrementalHash hash, string value)
{
AppendInt32(hash, value.Length);
Span<byte> scratch = stackalloc byte[256];
var offset = 0;
while (offset < value.Length)
{
var chars = Math.Min(scratch.Length / 2, value.Length - offset);
for (var i = 0; i < chars; i++)
BinaryPrimitives.WriteUInt16LittleEndian(scratch.Slice(i * 2, 2), value[offset + i]);
hash.AppendData(scratch[..(chars * 2)]);
offset += chars;
}
}
internal static void AppendScalar(IncrementalHash hash, DataValueKind kind, object value)
{
Span<byte> scratch = stackalloc byte[16];
var count = 0;
switch (kind)
{
case DataValueKind.Boolean: scratch[0] = (bool)value ? (byte)1 : (byte)0; count = 1; break;
case DataValueKind.Int8: scratch[0] = unchecked((byte)(sbyte)value); count = 1; break;
case DataValueKind.UInt8: scratch[0] = (byte)value; count = 1; break;
case DataValueKind.Int16: BinaryPrimitives.WriteInt16LittleEndian(scratch, (short)value); count = 2; break;
case DataValueKind.UInt16: BinaryPrimitives.WriteUInt16LittleEndian(scratch, (ushort)value); count = 2; break;
case DataValueKind.Int32: BinaryPrimitives.WriteInt32LittleEndian(scratch, (int)value); count = 4; break;
case DataValueKind.UInt32: BinaryPrimitives.WriteUInt32LittleEndian(scratch, (uint)value); count = 4; break;
case DataValueKind.Int64: BinaryPrimitives.WriteInt64LittleEndian(scratch, (long)value); count = 8; break;
case DataValueKind.UInt64: BinaryPrimitives.WriteUInt64LittleEndian(scratch, (ulong)value); count = 8; break;
case DataValueKind.Float: BinaryPrimitives.WriteInt32LittleEndian(scratch, BitConverter.SingleToInt32Bits((float)value)); count = 4; break;
case DataValueKind.Double: BinaryPrimitives.WriteInt64LittleEndian(scratch, BitConverter.DoubleToInt64Bits((double)value)); count = 8; break;
case DataValueKind.Timestamp: BinaryPrimitives.WriteInt64LittleEndian(scratch, ((DateTimeOffset)value).UtcTicks); count = 8; break;
case DataValueKind.Guid: ((Guid)value).TryWriteBytes(scratch); count = 16; break;
case DataValueKind.String: AppendString(hash, (string)value); return;
default: throw new ArgumentOutOfRangeException(nameof(kind));
}
hash.AppendData(scratch[..count]);
}
}
@@ -11,6 +11,8 @@
<ItemGroup>
<None Include="README.md" />
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests" />
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Runtime" />
</ItemGroup>
</Project>
@@ -22,6 +22,8 @@ public sealed class DataOperationPolicy
{
/// <summary>The currently installed local authority generation, rechecked at publication boundaries.</summary>
public long AuthorityEpoch => _authority.Current.GenerationId;
/// <summary>Checks that a mutation gate and this policy use the same authority publisher.</summary>
public bool UsesAuthority(IDataPlaneAuthoritySource authority) => ReferenceEquals(_authority, authority);
private readonly IDataPlaneAuthoritySource _authority;
private readonly IPermissionEvaluator _evaluator;
private readonly TimeProvider _clock;
@@ -563,6 +563,11 @@ public interface IDataPlaneAuthoritySink
/// </remarks>
public sealed class DataPlaneAuthorityState : IDataPlaneAuthoritySource, IDataPlaneAuthoritySink
{
/// <summary>Creates an authority state ordered with rich-write dispatch when a shared fence is supplied.</summary>
public DataPlaneAuthorityState(DataWriteDispatchFence? dispatchFence = null) => DispatchFence = dispatchFence ?? new();
/// <summary>The ordering fence used for publication of this authority.</summary>
public DataWriteDispatchFence DispatchFence { get; }
/// <summary>
/// Generations of the trie retained per cluster. One is enough for correctness now — every
/// authorization call stamps itself with the current generation — but an in-flight request that
@@ -637,7 +642,7 @@ public sealed class DataPlaneAuthorityState : IDataPlaneAuthoritySource, IDataPl
clusterId, revisionHash, generation, staged.Keys, staged.Grants, staged.ScopePaths, dropped,
staged.EquipmentScopePaths, staged.ScriptedAlarmOwners, staged.UnsFolderScopes,
staged.TagReferencingEquipment);
Volatile.Write(ref _current, published);
using (DispatchFence.Enter()) Volatile.Write(ref _current, published);
}
// Outside the lock, deliberately. Subscribers walk live subscriptions and take the SDK's own
@@ -0,0 +1,33 @@
namespace ZB.MOM.WW.OtOpcUa.Core.Authorization;
/// <summary>Orders mutation dispatch commitments with security and routing publications.</summary>
/// <remarks>The holder performs only bounded state publication or validation; never invoke external code while held.</remarks>
public sealed class DataWriteDispatchFence
{
private readonly object _gate = new();
/// <summary>Enter synchronously. Dispose on the same thread; never hold across an await.</summary>
public IDisposable Enter()
{
Monitor.Enter(_gate);
return new Releaser(_gate);
}
/// <summary>Attempts entry without waiting; callers must fail closed when contention prevents entry.</summary>
public bool TryEnter(out IDisposable? lease)
{
if (!Monitor.TryEnter(_gate)) { lease = null; return false; }
lease = new Releaser(_gate);
return true;
}
private sealed class Releaser(object gate) : IDisposable
{
private object? _gate = gate;
public void Dispose()
{
var held = Interlocked.Exchange(ref _gate, null);
if (held is not null) Monitor.Exit(held);
}
}
}
@@ -24,6 +24,13 @@ public interface IModbusTransport : IAsyncDisposable
Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct);
}
/// <summary>Transport that can issue one transaction without resending it after an ambiguous failure.</summary>
public interface IModbusWriteOnceTransport : IModbusTransport
{
/// <summary>Sends once; reconnecting before the first send is permitted, replay after send is not.</summary>
Task<byte[]> SendWithoutRetryAsync(byte unitId, byte[] pdu, CancellationToken ct);
}
/// <summary>Represents a Modbus protocol exception.</summary>
public sealed class ModbusException(byte functionCode, byte exceptionCode, string message)
: Exception(message)
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
@@ -20,7 +21,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// <see cref="PollGroupEngine"/> since Modbus has no native push model.
/// </remarks>
public sealed class ModbusDriver
: IDriver, ITagDiscovery, IReadable, IWritable, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable
: IDriver, ITagDiscovery, IReadable, IWritable, IWriteOutcomeCapability, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable
{
/// <summary>Authored tags this driver could not build into its poll table.</summary>
private readonly SkippedTagLedger _skippedTags = new();
@@ -1477,6 +1478,112 @@ public sealed class ModbusDriver
// ---- IWritable ----
/// <inheritdoc />
public async Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
var (generation, transport, table) = CaptureLifecycle();
var results = new DataWriteOutcome[writes.Count];
var batch = new BatchOutcome();
for (var i = 0; i < writes.Count; i++)
{
var write = writes[i];
if (!table.TryGetValue(write.FullReference, out var tag))
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNodeIdUnknown, "Unknown tag.");
continue;
}
if (!tag.Writable || tag.Region is ModbusRegion.DiscreteInputs or ModbusRegion.InputRegisters)
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNotWritable, "Tag is not writable.");
continue;
}
if (transport is not IModbusWriteOnceTransport once)
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNotSupported, "Transport cannot guarantee a single send.");
continue;
}
if (cancellationToken.IsCancellationRequested)
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadTimeout, "Canceled before dispatch.");
continue;
}
if (_options.WriteOnChangeOnly && IsRedundantWrite(write.FullReference, write.Value))
{
results[i] = new(DataWriteState.AcceptedUnconfirmed, 0, "Write suppressed without a new device acknowledgement.");
continue;
}
var unit = ResolveUnitId(tag);
if (batch.IsFailedFast(unit))
{
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadCommunicationError, "Batch stopped before dispatch.");
continue;
}
var tracked = new SingleSendWriteTransport(once);
try
{
await WriteOneAsync(tracked, tag, write.Value, cancellationToken).ConfigureAwait(false);
results[i] = tracked.ValidWriteAcknowledged
? new(DataWriteState.DriverConfirmedSuccess, 0, null)
: new(DataWriteState.OutcomeUnknown, StatusBadCommunicationError, "No confirmed write response.");
batch.Answered = true;
if (_options.WriteOnChangeOnly && tracked.ValidWriteAcknowledged)
lock (_lastWrittenLock) _lastWrittenByRef[write.FullReference] = write.Value;
}
catch (Exception ex)
{
var status = MapWriteFailure(ex, unit, write.FullReference, batch, cancellationToken);
var state = tracked.DefinitiveRefusal ? DataWriteState.DriverConfirmedFailure :
!tracked.WriteAttempted && ex is (ModbusWriteRefusedException or OverflowException or FormatException or
InvalidCastException or ArgumentException or NotSupportedException)
? DataWriteState.RejectedBeforeDispatch : DataWriteState.OutcomeUnknown;
results[i] = new(state, status, ex.Message);
InvalidateWriteCache(write.FullReference);
}
}
ReportOutcome(generation, batch, DateTime.UtcNow);
return results;
}
/// <summary>Tracks actual write PDUs and validates their protocol responses without altering the legacy path.</summary>
private sealed class SingleSendWriteTransport(IModbusWriteOnceTransport transport) : IModbusTransport
{
public bool WriteAttempted { get; private set; }
public bool ValidWriteAcknowledged { get; private set; }
public bool DefinitiveRefusal { get; private set; }
public Task ConnectAsync(CancellationToken ct) => throw new NotSupportedException();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
{
var isWrite = pdu[0] is 0x05 or 0x06 or 0x0F or 0x10 or 0x17;
if (isWrite)
{
WriteAttempted = true;
ValidWriteAcknowledged = false;
DefinitiveRefusal = false;
}
byte[] reply;
try { reply = await transport.SendWithoutRetryAsync(unitId, pdu, ct).ConfigureAwait(false); }
catch (ModbusException ex)
{
// A response for another function cannot establish that this write was refused.
// In particular, don't let FC23's illegal-function fallback replay an ambiguous write.
if (isWrite && ex.FunctionCode != pdu[0])
throw new InvalidDataException("Modbus exception function did not match the write request.", ex);
DefinitiveRefusal = isWrite && ex.FunctionCode == pdu[0] && ex.ExceptionCode is (1 or 2 or 3);
throw;
}
if (!isWrite) return reply;
var valid = pdu[0] == 0x17
? reply.Length == 2 + 2 * ((pdu[3] << 8) | pdu[4]) && reply[0] == pdu[0] && reply[1] == reply.Length - 2
: reply.Length == 5 && reply.AsSpan().SequenceEqual(pdu.AsSpan(0, 5));
if (!valid) throw new InvalidDataException("Modbus write acknowledgement did not match the request.");
ValidWriteAcknowledged = true;
return reply;
}
}
/// <inheritdoc />
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
@@ -41,7 +41,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// skipped (a raw injected stream cannot reconnect).
/// </para>
/// </remarks>
public sealed class ModbusRtuOverTcpTransport : IModbusTransport
public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
{
private readonly ModbusSocketLifecycle? _life;
private readonly Stream? _testStream;
@@ -89,7 +89,12 @@ public sealed class ModbusRtuOverTcpTransport : IModbusTransport
_life is null ? Task.CompletedTask : _life.ConnectAsync(ct);
/// <inheritdoc />
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, true);
/// <inheritdoc />
public Task<byte[]> SendWithoutRetryAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, false);
private async Task<byte[]> SendCoreAsync(byte unitId, byte[] pdu, CancellationToken ct, bool allowRetry)
{
if (Volatile.Read(ref _disposed) != 0) throw new ObjectDisposedException(nameof(ModbusRtuOverTcpTransport));
if (_life is null && _testStream is null) throw new InvalidOperationException("Transport not connected");
@@ -117,7 +122,7 @@ public sealed class ModbusRtuOverTcpTransport : IModbusTransport
_life?.MarkSuccess();
return result;
}
catch (Exception ex) when (!freshlyConnected && _life is not null && _life.AutoReconnect
catch (Exception ex) when (allowRetry && !freshlyConnected && _life is not null && _life.AutoReconnect
&& !ct.IsCancellationRequested
&& ModbusSocketLifecycle.IsSocketLevelFailure(ex))
{
@@ -131,6 +136,11 @@ public sealed class ModbusRtuOverTcpTransport : IModbusTransport
_life.MarkSuccess();
return result;
}
catch (Exception ex) when (!allowRetry && (ex is OperationCanceledException || ModbusSocketLifecycle.IsSocketLevelFailure(ex)))
{
if (_life is not null) await _life.TearDownAsync().ConfigureAwait(false);
throw;
}
}
finally
{
@@ -31,7 +31,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
/// socket in reasonable time even when the application is mostly idle.
/// </para>
/// </remarks>
public sealed class ModbusTcpTransport : IModbusTransport
public sealed class ModbusTcpTransport : IModbusWriteOnceTransport
{
private readonly ModbusSocketLifecycle _life;
private readonly TimeSpan _timeout;
@@ -68,7 +68,12 @@ public sealed class ModbusTcpTransport : IModbusTransport
public Task ConnectAsync(CancellationToken ct) => _life.ConnectAsync(ct);
/// <inheritdoc />
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, true);
/// <inheritdoc />
public Task<byte[]> SendWithoutRetryAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, false);
private async Task<byte[]> SendCoreAsync(byte unitId, byte[] pdu, CancellationToken ct, bool allowRetry)
{
if (Volatile.Read(ref _disposed) != 0) throw new ObjectDisposedException(nameof(ModbusTcpTransport));
@@ -92,11 +97,11 @@ public sealed class ModbusTcpTransport : IModbusTransport
try
{
var result = await SendOnceAsync(unitId, pdu, ct).ConfigureAwait(false);
var result = await SendOnceAsync(unitId, pdu, ct, strictResponse: !allowRetry).ConfigureAwait(false);
_life.MarkSuccess();
return result;
}
catch (Exception ex) when (!freshlyConnected && _life.AutoReconnect
catch (Exception ex) when (allowRetry && !freshlyConnected && _life.AutoReconnect
&& !ct.IsCancellationRequested
&& ModbusSocketLifecycle.IsSocketLevelFailure(ex))
{
@@ -106,10 +111,16 @@ public sealed class ModbusTcpTransport : IModbusTransport
// dialled is not retried: it proved nothing about a stale connection.
await _life.TearDownAsync().ConfigureAwait(false);
await _life.EnsureConnectedAsync(ct).ConfigureAwait(false);
var result = await SendOnceAsync(unitId, pdu, ct).ConfigureAwait(false);
var result = await SendOnceAsync(unitId, pdu, ct, strictResponse: false).ConfigureAwait(false);
_life.MarkSuccess();
return result;
}
catch (Exception ex) when (!allowRetry && (ex is OperationCanceledException || ModbusSocketLifecycle.IsSocketLevelFailure(ex)))
{
// The response might still arrive; do not reuse this socket and never replay the PDU.
await _life.TearDownAsync().ConfigureAwait(false);
throw;
}
}
finally
{
@@ -138,7 +149,7 @@ public sealed class ModbusTcpTransport : IModbusTransport
/// per-op timeout (the caller token is NOT cancelled) is a desync.
/// </para>
/// </remarks>
private async Task<byte[]> SendOnceAsync(byte unitId, byte[] pdu, CancellationToken ct)
private async Task<byte[]> SendOnceAsync(byte unitId, byte[] pdu, CancellationToken ct, bool strictResponse)
{
var stream = _life.Stream;
if (stream is null) throw new InvalidOperationException("Transport not connected");
@@ -169,6 +180,9 @@ public sealed class ModbusTcpTransport : IModbusTransport
var header = _header;
await ReadExactlyAsync(stream, header, cts.Token).ConfigureAwait(false);
if (strictResponse && (header[2] != 0 || header[3] != 0 || header[6] != unitId))
throw new ModbusTransportDesyncException(ModbusTransportDesyncException.DesyncReason.UnitMismatch,
"Modbus response protocol or unit does not match the request.");
var respTxId = (ushort)((header[0] << 8) | header[1]);
if (respTxId != txId)
throw new ModbusTransportDesyncException(
@@ -15,6 +15,8 @@ using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
// the SDK result stays unqualified as the dominant name in the override; the source DTO is HistorianRead.
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
using DataWriteOutcome = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataWriteOutcome;
using DataWriteState = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataWriteState;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
@@ -3396,6 +3398,41 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
return ServiceResult.Good;
}
/// <summary>
/// Observes a rich mapped-write result without blocking the SDK write callback. The caller supplies
/// the authoritative pre-write tuple and the exact active SDK write stamp. Mapped dispatch is wired
/// separately once its remote route and authorization are available.
/// </summary>
internal Task ObserveMappedWriteCompletion(Task<DataWriteOutcome> completion, string nodeId,
AddressSpaceRealm realm, object? optimisticValue, object? priorValue, StatusCode priorStatus,
DateTime priorSourceTimestamp, EquipmentVariableState.WriteStamp stamp)
{
ArgumentNullException.ThrowIfNull(completion);
return completion.ContinueWith(t =>
{
// A fault, cancellation or unrecognized result says nothing definitive about device execution.
var outcome = t.IsCompletedSuccessfully ? t.Result : null;
if (t.IsFaulted) _ = t.Exception;
if (outcome?.State is DataWriteState.RejectedBeforeDispatch or DataWriteState.DriverConfirmedFailure)
{
RevertOptimisticWriteIfNeeded(nodeId, new NodeWriteOutcome(false, outcome.Diagnostic),
optimisticValue, priorValue, priorStatus, null, realm, stamp, priorSourceTimestamp);
return;
}
if (outcome?.State == DataWriteState.DriverConfirmedSuccess) return;
lock (Lock)
{
if (!_variables.TryGetValue(MapKey(realm, nodeId), out var variable) ||
variable is not EquipmentVariableState equipment || !equipment.OwnsWrite(stamp)) return;
variable.Value = SdkValueBoundary.FromClr(priorValue,
variable.DataType == DataTypeIds.Byte && variable.ValueRank == ValueRanks.OneDimension);
variable.StatusCode = StatusCodes.UncertainLastUsableValue;
variable.Timestamp = priorSourceTimestamp;
variable.ClearChangeMasks(SystemContext, includeChildren: false);
}
}, CancellationToken.None, TaskContinuationOptions.RunContinuationsAsynchronously, TaskScheduler.Default);
}
/// <summary>
/// Pure role + availability gate for an inbound equipment-tag write, extracted off
/// <see cref="OnEquipmentTagWrite"/> so it is unit-testable without booting an SDK server. Fails closed:
@@ -3781,7 +3818,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// <param name="writeStamp">The actual production node and accepted write attempt; absent only for legacy direct tests.</param>
internal void RevertOptimisticWriteIfNeeded(
string nodeId, NodeWriteOutcome outcome, object? optimisticValue, object? priorValue, StatusCode priorStatus,
string? clientUserId, AddressSpaceRealm realm, EquipmentVariableState.WriteStamp? writeStamp = null)
string? clientUserId, AddressSpaceRealm realm, EquipmentVariableState.WriteStamp? writeStamp = null,
DateTime? priorSourceTimestamp = null)
{
// Built under Lock if (and only if) a revert is performed, then reported AFTER Lock is released.
AuditWriteUpdateEventState? auditEvent = null;
@@ -3815,7 +3853,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
if (variable is EquipmentVariableState restored) restored.InvalidateWriteOwnership();
variable.Value = prior;
variable.StatusCode = priorStatus;
variable.Timestamp = now;
variable.Timestamp = priorSourceTimestamp ?? now;
variable.ClearChangeMasks(SystemContext, includeChildren: false); // notify — restore prior
// Item C: build the audit event-state while we hold the node reference + Lock, but DON'T report yet.
@@ -5,6 +5,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A publication barrier between desired authority and successfully served topology.</summary>
public sealed class CatalogActivation
{
public CatalogActivation(DataWriteDispatchFence? dispatchFence = null) => DispatchFence = dispatchFence ?? new();
public DataWriteDispatchFence DispatchFence { get; }
private readonly object _sync = new();
private CatalogActivationState _current = new(0, "", 0, false);
@@ -53,7 +55,7 @@ public sealed class CatalogActivation
lock (_sync)
{
var epoch = checked(_current.CatalogEpoch + 1);
Volatile.Write(ref _current, new(epoch, revision, 0, false));
using (DispatchFence.Enter()) Volatile.Write(ref _current, new(epoch, revision, 0, false));
return epoch;
}
}
@@ -64,7 +66,7 @@ public sealed class CatalogActivation
lock (_sync)
{
if (_current.CatalogEpoch != catalogEpoch) return false;
Volatile.Write(ref _current, _current with { AuthorityEpoch = authorityEpoch, IsReady = false });
using (DispatchFence.Enter()) Volatile.Write(ref _current, _current with { AuthorityEpoch = authorityEpoch, IsReady = false });
return true;
}
}
@@ -75,7 +77,7 @@ public sealed class CatalogActivation
{
if (_current.CatalogEpoch != catalogEpoch) return false;
var ready = topologySucceeded && _current.AuthorityEpoch > 0;
Volatile.Write(ref _current, _current with { IsReady = ready });
using (DispatchFence.Enter()) Volatile.Write(ref _current, _current with { IsReady = ready });
return ready;
}
}
@@ -0,0 +1,65 @@
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.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Revalidates a trusted catalog-bound ticket and commits dispatch against live publications.</summary>
internal sealed class DataWriteDispatchGate
(LocalCatalogCoordinator coordinator, CatalogActivation activation, DataPlaneAuthorityState authority,
DataOperationPolicy policy, RedundancyRoleView role, WriteRouteState routes, TimeProvider clock,
DriverWriteBounds bounds) : IWriteDispatchGate
{
private static DataWriteOutcome Denied => new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write no longer admitted.");
public DataWriteOutcome? TryCommit(WriteAdmissionTicket ticket, WriteClaim claim)
{
var fence = authority.DispatchFence;
if (!policy.UsesAuthority(authority) || !ReferenceEquals(fence, coordinator.DispatchFence) || !ReferenceEquals(fence, activation.DispatchFence)
|| !ReferenceEquals(fence, role.DispatchFence) || !ReferenceEquals(fence, routes.DispatchFence)) return Denied;
var proof = ticket.Proof;
var admission = proof.Admission;
var snapshot = authority.Current;
// Capture the currently deployed key facts before policy evaluation, while the key is still
// valid. The copied row is local to this invocation; no mutable credential object enters the fence.
var key = snapshot.FindUsableKey(admission.ApiKeyId, clock.GetUtcNow().UtcDateTime);
if (key is null || !string.Equals(key.Principal, admission.PrincipalId, StringComparison.OrdinalIgnoreCase)
|| !string.Equals(DataCallerIdentity.CredentialVersionFor(key), admission.CredentialVersion, StringComparison.Ordinal))
return Denied;
var currentKeyExpiry = key.ExpiresUtc;
var catalog = coordinator.Current;
var activationSnapshot = activation.Current;
var caller = new DataCallerIdentity(admission.PrincipalId, admission.ApiKeyId,
admission.CredentialVersion, admission.CredentialExpiresUtc);
if (catalog is null || !catalog.IsActive || catalog.AuthorityEpoch != snapshot.GenerationId
|| !catalog.TryResolve(admission.View, out var node) || !node.SourceEnabled || !node.Supported || !node.Metadata.Writable
|| node.EntityKind != proof.EntityKind || node.EntityId != proof.EntityId || node.Source != proof.Source
|| node.Scope.ClusterId != proof.Scope.ClusterId || node.Scope.Kind != proof.Scope.Kind
|| !node.Scope.Segments.SequenceEqual(proof.Scope.Segments)
|| (node.Metadata.AllowedOperations & DataOperations.Write) == 0
|| !catalog.AllowsExport(admission.PrincipalId, node, DataOperations.Write)
|| !policy.IsCallerUsable(caller) || !policy.AuthorizeLocal(caller, OpcUaOperation.WriteOperate, node.Scope)) return Denied;
var target = new WriteRouteTarget(proof.DriverInstanceId, proof.DriverReference, admission.DriverIncarnation,
proof.RouteGeneration, proof.PrimaryGeneration);
using (fence.Enter())
{
// These are immutable reads only. Writers acquire their own state lock first, then this fence.
var utcNow = clock.GetUtcNow();
if (!ReferenceEquals(snapshot, authority.Current) || !ReferenceEquals(activationSnapshot, activation.Current)
|| !coordinator.IsPublished(catalog) || !activationSnapshot.IsReady
|| admission.AuthorityEpoch != snapshot.GenerationId || admission.CatalogRevision != activationSnapshot.CatalogEpoch
|| admission.ServingIncarnation != catalog.Serving.Incarnation
|| !role.ShouldActAsPrimary || role.PrimaryGeneration <= 0 || role.PrimaryGeneration != proof.PrimaryGeneration
|| !string.Equals(catalog.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
|| !routes.IsCurrent(admission.View, target)
|| (admission.CredentialExpiresUtc is { } expiry && expiry <= utcNow)
|| (currentKeyExpiry is { } currentExpiry && currentExpiry <= utcNow.UtcDateTime)
|| clock.GetTimestamp() >= admission.MonotonicExpiry
|| clock.GetElapsedTime(clock.GetTimestamp(), admission.MonotonicExpiry) < bounds.RunBound + DriverWriteBounds.ReplyMargin)
return Denied;
return claim.TryMarkDispatched() ? null : claim.CurrentOutcome ?? Denied;
}
}
}
@@ -0,0 +1,191 @@
using System.Collections.Immutable;
using System.Security.Cryptography;
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.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
internal sealed class WriteValueBudget(long limit)
{
private long _used;
public IDisposable? TryReserve(long bytes)
{
if (bytes <= 0 || limit <= 0) return null;
while (true)
{
var used = Volatile.Read(ref _used);
if (bytes > limit - used) return null;
if (Interlocked.CompareExchange(ref _used, used + bytes, used) == used) return new Lease(this, bytes);
}
}
private sealed class Lease(WriteValueBudget owner, long bytes) : IDisposable
{
private int _released;
public void Dispose() { if (Interlocked.Exchange(ref _released, 1) == 0) Interlocked.Add(ref owner._used, -bytes); }
}
}
/// <summary>Caller-bound origin-local mutation admission; routes only catalog-resolved views.</summary>
internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<LocalExportCatalog?> catalog,
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, IDataWriteRoute route,
WriteOperationRegistry registry, WriteValueBudget values, TimeProvider clock, DriverWriteBounds bounds) : IDataWriteService
{
private static DataWriteOutcome Rejected(string reason) => new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, reason);
private static readonly DataWriteOutcome Unknown = new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown.");
public async Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(request.Items);
request.Budget.Validate();
cancellationToken.ThrowIfCancellationRequested();
if (request.Items.Count > Math.Min(request.Budget.MaxItems, capabilities.Limits.MaxBatchItems))
throw new ArgumentOutOfRangeException(nameof(request), "Write batch exceeds the item limit.");
var totalBytes = 0L;
foreach (var item in request.Items)
{
ArgumentNullException.ThrowIfNull(item);
ArgumentNullException.ThrowIfNull(item.Value);
totalBytes = checked(totalBytes + RetainedBytes(item));
}
if (totalBytes > request.Budget.MaxBytes) throw new ArgumentOutOfRangeException(nameof(request), "Write batch exceeds its byte limit.");
var started = clock.GetTimestamp();
var pending = request.Items.Select(item => ExecuteItem(item, request.Budget, started, cancellationToken)).ToArray();
return await Task.WhenAll(pending).ConfigureAwait(false);
}
private async Task<WriteItemResult> ExecuteItem(WriteItem item, DataBudget budget, long start, CancellationToken cancellationToken)
{
WriteItemResult Reject(string reason) => new(item.CorrelationId, Rejected(reason));
if (item.View is null || item.View.Address is null) return Reject("Write unavailable or denied before dispatch.");
var current = catalog();
var caller = new DataCallerIdentity(context.PrincipalId, context.ApiKeyId, context.CredentialVersion, context.CredentialExpiresUtc);
if (current is null || !current.IsActive || !capabilities.IsReady || current.AuthorityEpoch != policy.AuthorityEpoch
|| current.Serving != capabilities.Serving || !policy.IsCallerUsable(caller)
|| !current.TryResolve(item.View, out var node) || !current.AllowsExport(context.PrincipalId, node, DataOperations.Write)
|| (node.Metadata.AllowedOperations & DataOperations.Write) == 0
|| !policy.AuthorizeLocal(caller, OpcUaOperation.WriteOperate, node.Scope))
return Reject("Write unavailable or denied before dispatch.");
// Role and structure are intentionally checked after authorization.
if (!string.Equals(current.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
|| !node.SourceEnabled || !node.Supported || !node.Metadata.Writable
|| !ValueMatches(node.Metadata, item.Value) || item.ExpectedCatalogRevision != current.Serving.CatalogEpoch
|| item.ExpectedServingIncarnation != current.Serving.Incarnation)
return Reject("Write unavailable before dispatch.");
if (string.IsNullOrWhiteSpace(item.OperationId) || string.IsNullOrWhiteSpace(item.CorrelationId))
return Reject("Invalid write identity.");
byte[] hash;
try { hash = SemanticHash(node.Metadata.View, item); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{ return Reject("Invalid write value."); }
var result = registry.Claim(context.PrincipalId, item.OperationId, item.ExpectedServingIncarnation, hash);
if (result.Kind is WriteClaimKind.Conflict or WriteClaimKind.Stale or WriteClaimKind.Capacity || result.Claim is null)
return Reject("Write operation conflict or capacity exhausted.");
var claim = result.Claim;
if (result.Kind == WriteClaimKind.Existing)
{
var existing = claim.CurrentOutcome ?? await claim.Completion.WaitAsync(cancellationToken).ConfigureAwait(false);
return new(item.CorrelationId, existing);
}
var remaining = budget.Timeout - clock.GetElapsedTime(start);
if (item.RemainingBudget < remaining) remaining = item.RemainingBudget;
WriteRouteTarget? target;
try { target = remaining >= bounds.GatewayAsk && route.TryResolve(node.Metadata.View, out var resolved) ? resolved : null; }
catch { target = null; }
if (target is null)
{
var rejected = Rejected("Insufficient budget or no active driver route.");
claim.Complete(rejected);
return new(item.CorrelationId, rejected);
}
var lease = values.TryReserve(RetainedBytes(item));
if (lease is null)
{
var rejected = Rejected("Retained write byte budget exhausted.");
claim.Complete(rejected);
return new(item.CorrelationId, rejected);
}
WriteAdmissionTicket ticket;
try
{
var issued = clock.GetTimestamp();
var expiration = checked(issued + (long)(remaining.TotalSeconds * clock.TimestampFrequency));
var admission = new DataWriteAdmission(context.PrincipalId, node.Metadata.View, current.AuthorityEpoch,
current.Serving.CatalogEpoch, current.Serving.Incarnation, target.DriverIncarnation, item.OperationId,
expiration, context.ApiKeyId, context.CredentialExpiresUtc, context.CredentialVersion);
var scope = new FrozenWriteScope(node.Scope.ClusterId, node.Scope.Kind, node.Scope.Segments.ToImmutableArray());
var proof = new WriteRouteProof(admission, scope, node.EntityKind, node.EntityId, node.Source,
target.DriverInstanceId, target.DriverReference, target.RouteGeneration, target.PrimaryGeneration);
ticket = new WriteAdmissionTicket(proof, item.Value.Retain(), issued, lease);
}
catch
{
lease.Dispose();
var rejected = Rejected("Invalid write deadline or value.");
claim.Complete(rejected);
return new(item.CorrelationId, rejected);
}
_ = DispatchAsync(route, ticket, claim);
return new(item.CorrelationId, await claim.Completion.WaitAsync(cancellationToken).ConfigureAwait(false));
}
private static async Task DispatchAsync(IDataWriteRoute route, WriteAdmissionTicket ticket, WriteClaim claim)
{
try
{
var outcome = await route.DispatchAsync(ticket, claim, CancellationToken.None).ConfigureAwait(false);
// The physical observer is the sole publisher of definitive dispatched outcomes. A route
// reply can establish only a proven no-call rejection or an ambiguous post-dispatch outcome;
// otherwise it could refine an Unknown after late-result retention has already expired.
if (outcome.State == DataWriteState.RejectedBeforeDispatch)
{
if (claim.Complete(outcome)) ticket.Dispose();
}
else if (outcome.State == DataWriteState.OutcomeUnknown)
claim.Complete(outcome);
}
catch
{
var rejection = Rejected("Write route failed before dispatch.");
if (claim.Complete(rejection)) ticket.Dispose();
else claim.Complete(Unknown);
}
}
private static bool ValueMatches(DataMetadata metadata, DataValue value) =>
value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind &&
(value.Kind != DataValueKind.Array || metadata.ArrayElementKind == value.ArrayElementKind &&
metadata.Dimensions.Count == value.Dimensions!.Count &&
metadata.Dimensions.Zip(value.Dimensions).All(x => x.First == 0 || x.First == x.Second));
private static long RetainedBytes(WriteItem item) => checked(3 * item.Value.EstimatedRetainedBytes + 512L + 2L *
((item.CorrelationId?.Length ?? 0) + (item.OperationId?.Length ?? 0) + (item.View?.Subject?.Length ?? 0)
+ (item.View?.MappingId?.Length ?? 0) + (item.View?.Address?.OriginClusterId?.Length ?? 0)
+ (item.View?.Address?.NamespaceUri?.Length ?? 0) + (item.View?.Address?.IdentifierKind?.Length ?? 0)
+ (item.View?.Address?.Identifier?.Length ?? 0) + (item.ExpectedServingIncarnation?.Length ?? 0)));
private static byte[] SemanticHash(DataView canonicalView, WriteItem item)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
// Hash the catalog's actual resolved identity, not a caller's equivalent spelling or subject claim.
// UTF-16 code units are framed directly, so distinct ordinal strings never collapse via replacement.
DataFingerprintEncoding.AppendInt32(hash, 1);
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.OriginClusterId);
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.NamespaceUri);
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.IdentifierKind);
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.Identifier);
DataFingerprintEncoding.AppendInt32(hash, (int)canonicalView.Realm);
DataFingerprintEncoding.AppendByte(hash, canonicalView.MappingId is null ? (byte)0 : (byte)1);
if (canonicalView.MappingId is not null) DataFingerprintEncoding.AppendString(hash, canonicalView.MappingId);
DataFingerprintEncoding.AppendInt64(hash, canonicalView.MappingRevision);
DataFingerprintEncoding.AppendString(hash, canonicalView.Subject);
DataFingerprintEncoding.AppendInt64(hash, item.ExpectedCatalogRevision);
DataFingerprintEncoding.AppendString(hash, item.ExpectedServingIncarnation);
item.Value.AppendSemanticFingerprint(hash);
return hash.GetHashAndReset();
}
}
@@ -0,0 +1,91 @@
using Akka.Actor;
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.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Shared node-incarnation write state, explicitly wired only when the data plane is ready.</summary>
public sealed class DataWriteRuntime
{
private readonly LocalCatalogCoordinator _catalog;
private readonly DataOperationPolicy _policy;
private readonly DataCapabilitiesProvider _capabilities;
private readonly RedundancyRoleView _role;
private readonly WriteOperationRegistry _registry;
private readonly WriteValueBudget _values;
private readonly TimeProvider _clock;
private readonly DriverWriteBounds _bounds;
internal readonly WriteRouteState Routes;
internal readonly IWriteDispatchGate Gate;
internal readonly LateWriteObserver Observer;
internal Action<string>? BeforeDriverStopForTests { get; set; }
public DataWriteRuntime(LocalCatalogCoordinator catalog, CatalogActivation activation, DataPlaneAuthorityState authority,
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, RedundancyRoleView role,
TimeProvider clock, DriverWriteBounds bounds, string servingIncarnation,
int maxOperations, long maxRegistryBytes, long maxWriteBytes, int maxPhysicalWrites, TimeSpan retention)
{
if (!ReferenceEquals(authority.DispatchFence, catalog.DispatchFence)
|| !ReferenceEquals(authority.DispatchFence, activation.DispatchFence)
|| !ReferenceEquals(authority.DispatchFence, role.DispatchFence) || !policy.UsesAuthority(authority)
|| capabilities.Serving.Incarnation != servingIncarnation)
throw new ArgumentException("Rich write publishers must share one fence and authority.");
_catalog = catalog; _policy = policy; _capabilities = capabilities; _role = role; _clock = clock; _bounds = bounds;
Routes = new(authority.DispatchFence);
Gate = new DataWriteDispatchGate(catalog, activation, authority, policy, role, Routes, clock, bounds);
Observer = new(maxPhysicalWrites, retention, clock);
_registry = new(servingIncarnation, maxOperations, maxRegistryBytes, retention, clock);
_values = new(maxWriteBytes);
}
internal bool MatchesHost(LocalCatalogCoordinator? coordinator, IDriverPrimaryRoleSource? role,
TimeProvider clock, DriverWriteBounds bounds) => ReferenceEquals(_catalog, coordinator)
&& ReferenceEquals(_role, role) && ReferenceEquals(_clock, clock) && _bounds == bounds;
/// <summary>Creates an executor for an authenticated transport context and this node's driver host.</summary>
public IDataWriteService ForCaller(DataAuthenticatedContext context, Func<IActorRef?> resolveHost) =>
new DataWriteExecutor(context, () => _catalog.Current, _policy, _capabilities,
new ActorDataWriteRoute(resolveHost, Routes, _role, _bounds, _clock), _registry, _values, _clock, _bounds);
}
internal sealed class ActorDataWriteRoute(Func<IActorRef?> resolveHost, WriteRouteState routes,
RedundancyRoleView role, DriverWriteBounds bounds, TimeProvider? clock = null) : IDataWriteRoute
{
public bool TryResolve(DataView view, out WriteRouteTarget? target)
{
if (!routes.TryResolve(view, out var found) || found is null || role.PrimaryGeneration <= 0)
{ target = null; return false; }
target = found with { PrimaryGeneration = role.PrimaryGeneration };
return true;
}
public async Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct)
{
var host = resolveHost();
if (host is null)
{
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Driver host unavailable.");
if (claim.Complete(rejected)) ticket.Dispose();
return claim.CurrentOutcome ?? rejected;
}
try
{
using var deadline = new CancellationTokenSource(bounds.GatewayAsk, clock ?? TimeProvider.System);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token, ct);
return await host.Ask<DataWriteOutcome>(new DriverHostActor.RouteRichWrite(ticket, claim),
Timeout.InfiniteTimeSpan, linked.Token)
.ConfigureAwait(false);
}
catch
{
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Route timed out before dispatch.");
if (claim.Complete(rejected)) { ticket.Dispose(); return rejected; }
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0x800A0000u, "Route outcome unknown.");
claim.Complete(unknown);
return claim.CurrentOutcome ?? unknown;
}
}
}
@@ -0,0 +1,131 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Limits physical outstanding driver operations, including token-ignoring operations.</summary>
public sealed class LateWriteObserver
{
private readonly int _maxOutstanding;
private readonly TimeSpan _retention;
private readonly TimeProvider _clock;
private readonly object _gate = new();
private readonly Dictionary<(string Driver, string Reference), LateWriteReservation> _targets = new(new TargetComparer());
private int _outstanding;
public LateWriteObserver(int maxOutstanding, TimeSpan retention, TimeProvider? clock = null)
{
if (maxOutstanding <= 0 || retention <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maxOutstanding));
_maxOutstanding = maxOutstanding;
_retention = retention;
_clock = clock ?? TimeProvider.System;
}
public bool TryReserve(out LateWriteReservation? reservation)
{
lock (_gate)
{
if (_outstanding >= _maxOutstanding) { reservation = null; return false; }
reservation = new LateWriteReservation(this, _retention, _clock, null);
_outstanding++;
return true;
}
}
/// <summary>Reserves both a global slot and the exact backing target until physical completion.</summary>
public bool TryReserve(string driverInstanceId, string driverReference, out LateWriteReservation? reservation)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
ArgumentException.ThrowIfNullOrWhiteSpace(driverReference);
var target = (driverInstanceId, driverReference);
lock (_gate)
{
if (_outstanding >= _maxOutstanding || _targets.ContainsKey(target))
{
reservation = null;
return false;
}
reservation = new LateWriteReservation(this, _retention, _clock, target);
_targets.Add(target, reservation);
_outstanding++;
return true;
}
}
internal void Release(LateWriteReservation reservation, (string Driver, string Reference)? target)
{
lock (_gate)
{
if (target is { } key)
{
if (!_targets.TryGetValue(key, out var owner) || !ReferenceEquals(owner, reservation)) return;
_targets.Remove(key);
}
_outstanding--;
}
}
private sealed class TargetComparer : IEqualityComparer<(string Driver, string Reference)>
{
public bool Equals((string Driver, string Reference) x, (string Driver, string Reference) y) =>
StringComparer.OrdinalIgnoreCase.Equals(x.Driver, y.Driver) && StringComparer.Ordinal.Equals(x.Reference, y.Reference);
public int GetHashCode((string Driver, string Reference) key) =>
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(key.Driver), StringComparer.Ordinal.GetHashCode(key.Reference));
}
}
/// <summary>A reservation transfers the physical permit and optional resources to the raw task.</summary>
public sealed class LateWriteReservation : IDisposable
{
private readonly LateWriteObserver _owner;
private readonly TimeSpan _retention;
private readonly TimeProvider _clock;
private readonly (string Driver, string Reference)? _target;
// 0 reserved, 1 transferred, 2 released.
private int _state;
internal LateWriteReservation(LateWriteObserver owner, TimeSpan retention, TimeProvider clock,
(string Driver, string Reference)? target)
{ _owner = owner; _retention = retention; _clock = clock; _target = target; }
public void Observe(Task<DataWriteOutcome> actualDriverTask, WriteClaim claim, IDisposable? lifetime = null)
{
ArgumentNullException.ThrowIfNull(actualDriverTask);
ArgumentNullException.ThrowIfNull(claim);
if (Interlocked.CompareExchange(ref _state, 1, 0) != 0) throw new InvalidOperationException("Reservation already consumed.");
var started = _clock.GetTimestamp();
_ = ObserveCore(actualDriverTask, claim, lifetime, started);
}
private async Task ObserveCore(Task<DataWriteOutcome> task, WriteClaim claim, IDisposable? lifetime, long started)
{
try
{
DataWriteOutcome outcome;
try { outcome = await task.ConfigureAwait(false); }
catch { outcome = new(DataWriteState.OutcomeUnknown, 0, "Driver completion failed or was canceled."); }
if (_clock.GetElapsedTime(started, _clock.GetTimestamp()) < _retention)
{
try
{
if (!claim.Complete(outcome)) claim.LateRefine(outcome);
}
catch (ArgumentException)
{
claim.Complete(new(DataWriteState.OutcomeUnknown, 0, "Invalid driver outcome."));
}
}
else claim.Complete(new(DataWriteState.OutcomeUnknown, 0, "Late-result retention expired."));
}
finally
{
claim.PhysicalFinished();
try { lifetime?.Dispose(); }
finally { Interlocked.Exchange(ref _state, 2); _owner.Release(this, _target); }
}
}
public void Dispose()
{
if (Interlocked.CompareExchange(ref _state, 2, 0) == 0) _owner.Release(this, _target);
}
}
@@ -16,6 +16,9 @@ public sealed record CatalogAttempt(long Epoch, string Revision)
/// <summary>Coordinates desired authority, private catalog staging and served topology activation.</summary>
public sealed class LocalCatalogCoordinator
{
public DataWriteDispatchFence DispatchFence => _activation.DispatchFence;
internal bool IsPublished(LocalExportCatalog catalog) => ReferenceEquals(Volatile.Read(ref _published), catalog);
internal IReadOnlyList<LocalDataNode> StagedNodes => Volatile.Read(ref _staged)?.Nodes ?? [];
private readonly object _gate = new();
private readonly CatalogActivation _activation;
private readonly DataPlaneAuthorityState _authority;
@@ -56,8 +59,12 @@ public sealed class LocalCatalogCoordinator
return catalog.IsActive ? catalog : null;
}
var adjusted = catalog.WithServingRole(catalog.Serving with { Role = current.Role });
if (ReferenceEquals(Interlocked.CompareExchange(ref _published, adjusted, catalog), catalog))
continue;
// Acquisition callers must not wait behind a write-commit or authority publisher.
// Serving will return provisional zero epochs if the role wrapper cannot be refreshed.
if (!DispatchFence.TryEnter(out var lease)) return null;
using (lease)
if (ReferenceEquals(Interlocked.CompareExchange(ref _published, adjusted, catalog), catalog))
continue;
}
return null;
}
@@ -82,7 +89,7 @@ public sealed class LocalCatalogCoordinator
_staged = null;
_terminal = false;
_catalogValid = false;
Volatile.Write(ref _published, null);
using (DispatchFence.Enter()) Volatile.Write(ref _published, null);
return attempt;
}
}
@@ -134,10 +141,10 @@ public sealed class LocalCatalogCoordinator
var state = _activation.Current;
var valid = topologySucceeded && _staged is not null && _catalogValid
&& state.AuthorityEpoch == _authority.Current.GenerationId;
if (valid) Volatile.Write(ref _published, _staged);
if (valid) { using (DispatchFence.Enter()) Volatile.Write(ref _published, _staged); }
if (!_activation.Complete(attempt.Epoch, valid))
{
Volatile.Write(ref _published, null);
using (DispatchFence.Enter()) Volatile.Write(ref _published, null);
return false;
}
return true;
@@ -0,0 +1,133 @@
using System.Collections.Immutable;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
internal sealed record FrozenWriteScope(string ClusterId, NodeHierarchyKind Kind, ImmutableArray<string> Segments);
internal sealed record WriteRouteTarget(string DriverInstanceId, string DriverReference, string DriverIncarnation,
long RouteGeneration, long PrimaryGeneration);
internal sealed record WriteRouteProof(DataWriteAdmission Admission, FrozenWriteScope Scope, string EntityKind,
string EntityId, BackingSourceKey? Source, string DriverInstanceId, string DriverReference,
long RouteGeneration, long PrimaryGeneration);
/// <summary>Owns the value and its byte charge until rejection or actual driver completion.</summary>
internal sealed class WriteAdmissionTicket : IDisposable
{
private IDisposable? _byteLease;
private int _disposed;
public WriteAdmissionTicket(WriteRouteProof proof, DataValue value, long issuedAt, IDisposable? byteLease = null)
{ Proof = proof; Value = value; IssuedAt = issuedAt; _byteLease = byteLease; }
public WriteRouteProof Proof { get; }
public DataValue Value { get; }
public long IssuedAt { get; }
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
try { Value.Dispose(); }
finally { Interlocked.Exchange(ref _byteLease, null)?.Dispose(); }
}
}
internal interface IWriteDispatchGate
{
DataWriteOutcome? TryCommit(WriteAdmissionTicket ticket, WriteClaim claim);
}
internal interface IDataWriteRoute
{
bool TryResolve(DataView view, out WriteRouteTarget? target);
Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct);
}
/// <summary>Immutable, fenced route and physical actor-lifetime snapshots.</summary>
internal sealed class WriteRouteState(DataWriteDispatchFence fence)
{
private sealed record Snapshot(long Generation, ImmutableDictionary<DataView, WriteRouteTarget> Routes,
ImmutableDictionary<string, string> Drivers);
private Snapshot _current = new(0, ImmutableDictionary<DataView, WriteRouteTarget>.Empty,
ImmutableDictionary<string, string>.Empty.WithComparers(StringComparer.Ordinal));
public DataWriteDispatchFence DispatchFence => fence;
public string? CurrentDriverIncarnation(string driver) => Volatile.Read(ref _current).Drivers.GetValueOrDefault(driver);
public string BeginDriverIncarnation(string driver)
{
var incarnation = Guid.NewGuid().ToString("N");
Update(s =>
{
var generation = checked(s.Generation + 1);
var routes = s.Routes;
foreach (var pair in s.Routes)
if (pair.Value.DriverInstanceId == driver)
routes = routes.SetItem(pair.Key, pair.Value with { DriverIncarnation = incarnation, RouteGeneration = generation });
return s with { Generation = generation, Drivers = s.Drivers.SetItem(driver, incarnation), Routes = routes };
});
return incarnation;
}
public void RetireDriver(string driver, string incarnation) => Update(s =>
s.Drivers.TryGetValue(driver, out var current) && current == incarnation
? s with { Generation = checked(s.Generation + 1), Drivers = s.Drivers.Remove(driver) } : s);
public void ReplaceRoutes(IEnumerable<(DataView View, string Driver, string Reference)> desired)
{
var items = desired.ToArray();
Update(s =>
{
var generation = checked(s.Generation + 1);
var next = ImmutableDictionary.CreateBuilder<DataView, WriteRouteTarget>();
foreach (var (view, driver, reference) in items)
{
var incarnation = s.Drivers.GetValueOrDefault(driver) ?? string.Empty;
if (!next.TryAdd(view, new(driver, reference, incarnation, generation, 0)))
throw new InvalidOperationException("Duplicate write view.");
}
var same = next.Count == s.Routes.Count && next.All(pair => s.Routes.TryGetValue(pair.Key, out var old)
&& old.DriverInstanceId == pair.Value.DriverInstanceId && old.DriverReference == pair.Value.DriverReference
&& old.DriverIncarnation == pair.Value.DriverIncarnation);
return same ? s : s with { Generation = generation, Routes = next.ToImmutable() };
});
}
public WriteRouteTarget Publish(DataView view, string driver, string reference, string incarnation)
{
WriteRouteTarget? result = null;
Update(s =>
{
if (s.Routes.TryGetValue(view, out var existing) && existing.DriverInstanceId == driver
&& existing.DriverReference == reference && existing.DriverIncarnation == incarnation
&& s.Drivers.TryGetValue(driver, out var active) && active == incarnation)
{ result = existing; return s; }
var next = checked(s.Generation + 1);
result = new(driver, reference, incarnation, next, 0);
return s with { Generation = next, Routes = s.Routes.SetItem(view, result),
Drivers = s.Drivers.ContainsKey(driver) ? s.Drivers : s.Drivers.Add(driver, incarnation) };
});
return result!;
}
public bool TryResolve(DataView view, out WriteRouteTarget? target)
{
var current = Volatile.Read(ref _current);
if (current.Routes.TryGetValue(view, out var found) && current.Drivers.TryGetValue(found.DriverInstanceId, out var incarnation)
&& incarnation == found.DriverIncarnation) { target = found; return true; }
target = null; return false;
}
public bool IsCurrent(DataView view, WriteRouteTarget target) => TryResolve(view, out var current)
&& current == (target with { PrimaryGeneration = current!.PrimaryGeneration });
private void Update(Func<Snapshot, Snapshot> prepare)
{
while (true)
{
var before = Volatile.Read(ref _current);
var after = prepare(before);
using (fence.Enter())
{
if (!ReferenceEquals(before, _current)) continue;
Volatile.Write(ref _current, after);
return;
}
}
}
}
@@ -0,0 +1,145 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public enum WriteClaimKind { Owner, Existing, Conflict, Stale, Capacity }
public sealed record WriteClaimResult(WriteClaimKind Kind, WriteClaim? Claim = null);
/// <summary>Bounded, incarnation-local duplicate protection. Payload storage is owned by the executor.</summary>
public sealed class WriteOperationRegistry
{
private readonly object _gate = new();
private readonly Dictionary<(string Principal, string Operation), Entry> _entries = new(new KeyComparer());
private readonly string _incarnation;
private readonly int _maxEntries;
private readonly long _maxBytes;
private readonly TimeSpan _retention;
private readonly TimeProvider _clock;
private long _retainedBytes;
public WriteOperationRegistry(string servingIncarnation, int maxEntries, long maxRetainedBytes,
TimeSpan retention, TimeProvider? clock = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(servingIncarnation);
if (maxEntries <= 0 || maxRetainedBytes <= 0 || retention <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(maxEntries));
_incarnation = servingIncarnation;
_maxEntries = maxEntries;
_maxBytes = maxRetainedBytes;
_retention = retention;
_clock = clock ?? TimeProvider.System;
}
public WriteClaimResult Claim(string principal, string operationId, string expectedServingIncarnation,
ReadOnlyMemory<byte> semanticHash)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
ArgumentException.ThrowIfNullOrWhiteSpace(operationId);
ArgumentException.ThrowIfNullOrWhiteSpace(expectedServingIncarnation);
if (semanticHash.Length != 32) throw new ArgumentException("A SHA-256 hash is required.", nameof(semanticHash));
if (!StringComparer.Ordinal.Equals(_incarnation, expectedServingIncarnation)) return new(WriteClaimKind.Stale);
var bytes = 256L + 2L * principal.Length + 2L * operationId.Length + semanticHash.Length;
lock (_gate)
{
Prune();
var key = (principal, operationId);
if (_entries.TryGetValue(key, out var existing))
return existing.Hash.AsSpan().SequenceEqual(semanticHash.Span)
? new(WriteClaimKind.Existing, existing.Claim) : new(WriteClaimKind.Conflict);
if (_entries.Count >= _maxEntries || bytes > _maxBytes - _retainedBytes)
return new(WriteClaimKind.Capacity);
var claim = new WriteClaim(_clock);
_entries.Add(key, new Entry(semanticHash.ToArray(), claim, bytes));
_retainedBytes += bytes;
return new(WriteClaimKind.Owner, claim);
}
}
private void Prune()
{
var now = _clock.GetTimestamp();
foreach (var pair in _entries.ToArray())
{
if (!pair.Value.Claim.CanRetire(now, _retention)) continue;
_entries.Remove(pair.Key);
_retainedBytes -= pair.Value.Bytes;
}
}
private sealed record Entry(byte[] Hash, WriteClaim Claim, long Bytes);
private sealed class KeyComparer : IEqualityComparer<(string Principal, string Operation)>
{
public bool Equals((string Principal, string Operation) x, (string Principal, string Operation) y) =>
StringComparer.OrdinalIgnoreCase.Equals(x.Principal, y.Principal) &&
StringComparer.Ordinal.Equals(x.Operation, y.Operation);
public int GetHashCode((string Principal, string Operation) key) =>
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(key.Principal),
StringComparer.Ordinal.GetHashCode(key.Operation));
}
}
/// <summary>One shared operation. Dispatch and rejection compete through a lock-free transition.</summary>
public sealed class WriteClaim
{
// 0 pending, 1 dispatched, 2/3 completing before/after dispatch, 4/5 completed before/after dispatch.
private int _state;
private int _physicalFinished;
private long _completedTimestamp;
private readonly TimeProvider _clock;
private readonly object _outcomeGate = new();
private DataWriteOutcome? _outcome;
private readonly TaskCompletionSource<DataWriteOutcome> _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal WriteClaim(TimeProvider clock) => _clock = clock;
public Task<DataWriteOutcome> Completion => _completion.Task;
public bool IsDispatched => Volatile.Read(ref _state) is 1 or 3 or 5;
public DataWriteOutcome? CurrentOutcome => Volatile.Read(ref _outcome);
public bool TryMarkDispatched() => Interlocked.CompareExchange(ref _state, 1, 0) == 0;
public bool Complete(DataWriteOutcome outcome)
{
ArgumentNullException.ThrowIfNull(outcome);
outcome.Validate();
while (true)
{
var state = Volatile.Read(ref _state);
if (state is not (0 or 1)) return false;
if ((state == 0) != (outcome.State == DataWriteState.RejectedBeforeDispatch)) return false;
if (Interlocked.CompareExchange(ref _state, state + 2, state) != state) continue;
lock (_outcomeGate)
{
Volatile.Write(ref _outcome, outcome);
_completedTimestamp = _clock.GetTimestamp();
Volatile.Write(ref _state, state + 4);
_completion.TrySetResult(outcome);
}
return true;
}
}
public bool LateRefine(DataWriteOutcome outcome)
{
ArgumentNullException.ThrowIfNull(outcome);
outcome.Validate();
if (outcome.State is not (DataWriteState.DriverConfirmedSuccess or DataWriteState.DriverConfirmedFailure)) return false;
lock (_outcomeGate)
{
if (_outcome?.State is not (DataWriteState.OutcomeUnknown or DataWriteState.AcceptedUnconfirmed)) return false;
Volatile.Write(ref _completedTimestamp, _clock.GetTimestamp());
Volatile.Write(ref _outcome, outcome);
return true;
}
}
internal void PhysicalFinished() => Volatile.Write(ref _physicalFinished, 1);
internal bool CanRetire(long now, TimeSpan retention)
{
var state = Volatile.Read(ref _state);
return state is 4 or 5 && (state == 4 || Volatile.Read(ref _physicalFinished) != 0)
&& _clock.GetElapsedTime(Volatile.Read(ref _completedTimestamp), now) >= retention;
}
}
@@ -21,11 +21,13 @@ using ZB.MOM.WW.OtOpcUa.Configuration;
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.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Runtime.Telemetry;
@@ -186,6 +188,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
private readonly CommonsNodeId _localNode;
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? _catalogCoordinator;
private readonly DataWriteRuntime? _dataWriteRuntime;
private ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.CatalogAttempt? _catalogAttempt;
private readonly IActorRef? _ackRouter;
private readonly IDriverFactory _driverFactory;
@@ -619,6 +622,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// <param name="Success">True when the driver accepted the write.</param>
/// <param name="Reason">Failure detail when <paramref name="Success"/> is false; null on success.</param>
public sealed record NodeWriteResult(bool Success, string? Reason);
internal sealed record RouteRichWrite(WriteAdmissionTicket Ticket, WriteClaim Claim);
/// <summary>
/// Routes an inbound native-condition acknowledge to the owning driver child. The host wires the
@@ -796,7 +800,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
TimeSpan? childShutdownTimeout = null,
bool enforceSnapshotOrdering = false,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataWriteRuntime? dataWriteRuntime = null) =>
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
@@ -811,7 +816,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay,
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator));
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime));
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
/// <param name="dbFactory">Database context factory for configuration database access.</param>
@@ -949,8 +954,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
TimeSpan? childShutdownTimeout = null,
bool enforceSnapshotOrdering = false,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
DataWriteRuntime? dataWriteRuntime = null)
{
_dataWriteRuntime = dataWriteRuntime;
_sourcePublisher = sourcePublisher;
_catalogCoordinator = catalogCoordinator;
_snapshotOrdering = enforceSnapshotOrdering ? new SnapshotRevisionGate() : null;
@@ -958,6 +965,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_scriptedAlarmRunner = scriptedAlarmRunner;
_writeBounds = writeBounds ?? DriverWriteBounds.Default;
_writeClock = writeClock ?? TimeProvider.System;
if (_dataWriteRuntime is not null && !_dataWriteRuntime.MatchesHost(_catalogCoordinator, primaryRoleSource, _writeClock, _writeBounds))
throw new ArgumentException("Rich writes require the host's exact catalog, role, clock and bounds.", nameof(dataWriteRuntime));
_ackPreflightView = ackPreflightView;
_scripting = scripting;
_captureWhilePrimaryUnreachable = captureWhilePrimaryUnreachable;
@@ -1061,8 +1070,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// </summary>
private void StartPrimaryVerdictPublishing()
{
PublishHistoryUpdateVerdict();
if (_primaryRoleSource is null) return;
if (_primaryRoleSource is null) { PublishHistoryUpdateVerdict(); return; }
PublishPrimaryVerdict();
try
{
@@ -1086,13 +1094,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// node's new incarnation. A REMOVED member deliberately stays in the set: it never answers again, and
// dropping it would re-derive the verdict from a cached snapshot that may still name it Primary,
// closing the gate on a dead node until the next snapshot (the very hole the reachability tracking closes).
if (evt is Akka.Cluster.ClusterEvent.MemberUp up
&& _unreachableNodes.Remove(ToNodeId(up.Member.Address)))
{
RepublishHistorizationVerdictIfChanged();
}
var becameReachable = evt is Akka.Cluster.ClusterEvent.MemberUp up
&& _unreachableNodes.Remove(ToNodeId(up.Member.Address));
PublishPrimaryVerdictIfChanged();
if (becameReachable) RepublishHistorizationVerdictIfChanged();
// One keyed timer: a burst of member events collapses into a single deferred pass.
Timers.StartSingleTimer("republish-primary-verdict", RepublishPrimaryVerdict.Instance, MembershipRepublishDelay);
}
@@ -1101,20 +1106,23 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
/// The snapshot path publishes on every snapshot, as the other verdicts do.</summary>
private void PublishPrimaryVerdict()
{
if (_primaryRoleSource is not null)
{
var verdict = ShouldServiceAsPrimary();
_lastPublishedPrimaryVerdict = verdict;
_primaryRoleSource.PublishPrimaryRole(verdict);
}
PublishHistoryUpdateVerdict();
if (_primaryRoleSource is null) return;
var verdict = ShouldServiceAsPrimary();
_lastPublishedPrimaryVerdict = verdict;
_primaryRoleSource.PublishPrimaryRole(verdict);
}
/// <summary>The membership path publishes only a CHANGED verdict — member events are frequent and carry no
/// role information, so republishing an unchanged verdict on each would be noise.</summary>
private void PublishPrimaryVerdictIfChanged()
{
PublishHistoryUpdateVerdict();
if (_primaryRoleSource is null || ShouldServiceAsPrimary() == _lastPublishedPrimaryVerdict) return;
PublishPrimaryVerdict();
if (_primaryRoleSource is not null && ShouldServiceAsPrimary() != _lastPublishedPrimaryVerdict)
PublishPrimaryVerdict();
else
PublishHistoryUpdateVerdict();
}
/// <summary>Publishes <see cref="PrimaryGatePolicy.ShouldServeHistoryUpdate"/> (no-op when no view
@@ -1654,6 +1662,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
Receive<ReprovisionDeferred>(m => ReprovisionChild(m.Request, m.Child));
Receive<ReconnectDriver>(HandleReconnectDriver);
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
Receive<RouteRichWrite>(HandleRouteRichWrite);
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
@@ -1719,6 +1728,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
Receive<ReprovisionDeferred>(m => ReprovisionChild(m.Request, m.Child));
Receive<ReconnectDriver>(HandleReconnectDriver);
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
Receive<RouteRichWrite>(HandleRouteRichWrite);
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
@@ -2368,6 +2378,40 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
.PipeTo(replyTo);
}
private static void RejectRichRoute(RouteRichWrite msg, IActorRef replyTo, string reason)
{
var rejection = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x80310000u, reason);
if (msg.Claim.Complete(rejection)) msg.Ticket.Dispose();
replyTo.Tell(msg.Claim.CurrentOutcome ?? new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown."));
}
private void HandleRouteRichWrite(RouteRichWrite msg)
{
var proof = msg.Ticket.Proof;
if (_dataWriteRuntime is null || !ShouldServiceAsPrimary())
{ RejectRichRoute(msg, Sender, "Write route unavailable."); return; }
var realm = proof.Admission.View.Realm == DataRealm.Raw ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns;
var nodeId = proof.Admission.View.Address.Identifier;
if (!_driverRefByNodeId.TryGetValue((realm, nodeId), out var target)
|| target.DriverInstanceId != proof.DriverInstanceId || target.RawPath != proof.DriverReference
|| !_children.TryGetValue(target.DriverInstanceId, out var child))
{ RejectRichRoute(msg, Sender, "Driver route changed."); return; }
var replyTo = Sender;
var deadline = new CancellationTokenSource(_writeBounds.HostAsk, _writeClock);
child.Actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(msg.Ticket, msg.Claim),
System.Threading.Timeout.InfiniteTimeSpan, deadline.Token)
.ContinueWith(t =>
{
deadline.Dispose();
if (t.IsCompletedSuccessfully) return t.Result;
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Driver route expired before dispatch.");
if (msg.Claim.Complete(rejected)) { msg.Ticket.Dispose(); return rejected; }
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0x800A0000u, "Driver outcome unknown.");
msg.Claim.Complete(unknown);
return msg.Claim.CurrentOutcome ?? unknown;
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default).PipeTo(replyTo);
}
/// <summary>
/// Normalise an OPC UA NodeId string to its BARE <c>s=</c> identifier. The node manager's inbound-write
/// hook passes the full ns-qualified form (<c>NodeId.ToString()</c> == <c>"ns=&lt;N&gt;;s=&lt;id&gt;"</c>);
@@ -2608,6 +2652,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_localNode, string.Join(",", msg.Nodes.Select(n => n.NodeId)));
}
// Publish the write fence before independent alarm/history callbacks can block this mailbox.
PublishPrimaryVerdict();
// Publish on EVERY snapshot, including ones that leave the cached role untouched, so a role
// that changes without this node being named still reaches the drain within one heartbeat.
//
@@ -2637,11 +2684,6 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
_historizationRoleView.PublishHistorizationRole(historizationVerdict);
}
// The DATA-PLANE verdict, deliberately — the same one HandleRouteNodeWrite gates on, not the
// drain verdict published immediately above. A driver reading this claims an exclusive identity
// on a shared external system (the Sparkplug host id), where two claimants is the
// harm, so an unknown role with a driver peer present must deny.
PublishPrimaryVerdict();
}
/// <summary>
@@ -2743,6 +2785,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// node-manager's bounded Ask gets an immediate clear status instead of dead-lettering into a timeout.
Receive<RouteNodeWrite>(_ =>
Sender.Tell(new NodeWriteResult(false, "driver host stale (config DB unreachable)")));
Receive<RouteRichWrite>(msg => RejectRichRoute(msg, Sender, "Driver host unavailable."));
// An inbound native-condition ack can't be serviced while Stale either (the alarm inverse map is
// empty until an apply runs). The node manager's pre-check refuses it synchronously while Stale (see the
// top of this method); one that raced that refusal is dropped here with a log.
@@ -3902,6 +3945,19 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
}
}
if (_dataWriteRuntime is not null && _catalogCoordinator is not null)
{
var mapped = new List<(DataView View, string Driver, string Reference)>();
foreach (var node in _catalogCoordinator.StagedNodes)
{
var view = node.Metadata.View;
var realm = view.Realm == DataRealm.Raw ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns;
if (_driverRefByNodeId.TryGetValue((realm, view.Address.Identifier), out var target))
mapped.Add((view, target.DriverInstanceId, target.RawPath));
}
_dataWriteRuntime.Routes.ReplaceRoutes(mapped);
}
if (previousSourceRefs is not null)
foreach (var previous in previousSourceRefs)
if (!_nodeIdByDriverRef.ContainsKey(previous))
@@ -4052,12 +4108,17 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
if (stub)
{
child = Context.ActorOf(
DriverInstanceActor.Props(
_dataWriteRuntime is null ? DriverInstanceActor.Props(
new StubbedDriver(spec.DriverInstanceId, spec.DriverType),
reconnectInterval: null,
startStubbed: true,
healthPublisher: _healthPublisher,
clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation),
clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation)
: DriverInstanceActor.PropsForRichWrites(new StubbedDriver(spec.DriverInstanceId, spec.DriverType),
startStubbed: true, healthPublisher: _healthPublisher, clusterId: clusterId,
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation,
writeDispatchGate: _dataWriteRuntime.Gate, lateWriteObserver: _dataWriteRuntime.Observer,
writeRouteState: _dataWriteRuntime.Routes),
actorName);
}
else
@@ -4068,7 +4129,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
// no-op invoker on nodes without the real resilience factory bound.
var invoker = _invokerFactory.Create(spec.DriverInstanceId, spec.DriverType, spec.ResilienceConfig);
child = Context.ActorOf(
DriverInstanceActor.Props(
_dataWriteRuntime is null ? DriverInstanceActor.Props(
driver!,
healthPublisher: _healthPublisher,
clusterId: clusterId,
@@ -4076,7 +4137,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
writeTimeout: _writeBounds.Timeout,
writeClock: _writeClock,
shutdownTimeout: _childShutdownTimeout,
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation),
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation)
: DriverInstanceActor.PropsForRichWrites(driver!, healthPublisher: _healthPublisher, clusterId: clusterId,
invoker: invoker, writeTimeout: _writeBounds.Timeout, writeClock: _writeClock,
shutdownTimeout: _childShutdownTimeout, sourcePublisher: _sourcePublisher,
sourceIncarnation: sourceIncarnation, writeDispatchGate: _dataWriteRuntime.Gate,
lateWriteObserver: _dataWriteRuntime.Observer, writeRouteState: _dataWriteRuntime.Routes),
actorName);
child.Tell(new DriverInstanceActor.InitializeRequested(spec.DriverConfig));
}
@@ -4137,12 +4203,21 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
Context.Stop(adapter);
}
private void RetireWriteIncarnation(string driverInstanceId)
{
var routes = _dataWriteRuntime?.Routes;
var incarnation = routes?.CurrentDriverIncarnation(driverInstanceId);
if (incarnation is not null) routes!.RetireDriver(driverInstanceId, incarnation);
}
private void StopChild(string driverInstanceId)
{
if (!_children.TryGetValue(driverInstanceId, out var entry)) return;
StopDependencyAdapter(driverInstanceId);
_sourcePublisher?.RetireCurrentDriver(driverInstanceId);
RetireChild(entry.Actor);
RetireWriteIncarnation(driverInstanceId);
_dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(driverInstanceId);
Context.Stop(entry.Actor);
_children.Remove(driverInstanceId);
PublishAckPreflight();
@@ -4262,6 +4337,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
StopDependencyAdapter(msg.DriverInstanceId);
_sourcePublisher?.RetireCurrentDriver(msg.DriverInstanceId);
RetireChild(entry.Actor);
RetireWriteIncarnation(msg.DriverInstanceId);
_dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(msg.DriverInstanceId);
Context.Stop(entry.Actor);
_children.Remove(msg.DriverInstanceId);
// An operator Restart builds a NEW driver object, so the old one's retained values are evicted like a
@@ -6,6 +6,8 @@ using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
@@ -71,6 +73,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// when the host's Ask fires (lmxopcua#777).</param>
public sealed record WriteAttribute(string TagId, object Value, long? IssuedAt = null);
public sealed record WriteAttributeResult(bool Success, string? Reason);
internal sealed record WriteAttributeWithOutcome(WriteAdmissionTicket Ticket, WriteClaim Claim);
/// <summary>
/// Sent by <see cref="DriverHostActor"/> when an OPC UA client Acknowledges a NATIVE Part 9
/// condition (resolved from the condition NodeId to this driver via the host's alarm inverse map).
@@ -307,7 +310,13 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <summary>Writes waiting for a slot (or for their tag), in arrival order, stamped with arrival time.
/// Failed fast on every exit from <c>Connected</c>, so a queued write never reaches a driver that is
/// reconnecting; failed <c>BadTimeout</c> once older than <see cref="_queuedWriteBudget"/> since issued.</summary>
private readonly LinkedList<(WriteAttribute Write, IActorRef ReplyTo, long IssuedAt)> _pendingWrites = new();
private readonly LinkedList<(WriteAttribute Write, IActorRef ReplyTo, long IssuedAt, long Sequence)> _pendingWrites = new();
private readonly LinkedList<(WriteAttributeWithOutcome Write, IActorRef ReplyTo, long Sequence)> _pendingRichWrites = new();
private long _queuedWriteSequence;
private readonly IWriteDispatchGate? _writeDispatchGate;
private readonly LateWriteObserver? _lateWriteObserver;
private readonly WriteRouteState? _writeRouteState;
private string? _writeIncarnation;
/// <summary>Tags with a write currently inside the driver. A second write to the same tag waits in the
/// queue behind it — two concurrent writes v1, v2 to one tag could otherwise land as v1.</summary>
@@ -517,6 +526,23 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
writeTimeout,
writeClock, sourcePublisher, sourceIncarnation));
internal static Props PropsForRichWrites(IDriver driver, IDriverCapabilityInvoker? invoker = null,
TimeSpan? commsLossTimeout = null, int? maxWritesInFlight = null, TimeSpan? writeTimeout = null,
IWriteDispatchGate? writeDispatchGate = null, LateWriteObserver? lateWriteObserver = null,
WriteRouteState? writeRouteState = null, TimeProvider? writeClock = null,
IDriverHealthPublisher? healthPublisher = null, string? clusterId = null, TimeSpan? shutdownTimeout = null,
SourceSamplePublisher? sourcePublisher = null, long? sourceIncarnation = null, bool startStubbed = false) =>
Akka.Actor.Props.CreateBy(new RichWriteActorProducer(() => new DriverInstanceActor(driver, DefaultReconnectInterval, startStubbed, healthPublisher, clusterId,
invoker, null, commsLossTimeout, shutdownTimeout, maxWritesInFlight, null, null, writeTimeout, writeClock,
sourcePublisher, sourceIncarnation, writeDispatchGate, lateWriteObserver, writeRouteState)));
private sealed class RichWriteActorProducer(Func<DriverInstanceActor> create) : IIndirectActorProducer
{
public Type ActorType => typeof(DriverInstanceActor);
public ActorBase Produce() => create();
public void Release(ActorBase actor) { }
}
/// <summary>
/// Returns true when the driver should boot in DEV-STUB mode based on host platform and
/// configured roles. Only the legacy v1 in-process <c>"Galaxy"</c> type stays Windows-only:
@@ -580,7 +606,21 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
TimeProvider? writeClock = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
long? sourceIncarnation = null)
: this(driver, reconnectInterval, startStubbed, healthPublisher, clusterId, invoker, healthPollInterval,
commsLossTimeout, shutdownTimeout, maxWritesInFlight, queuedWriteBudget, initializeTimeout,
writeTimeout, writeClock, sourcePublisher, sourceIncarnation, null, null, null) { }
private DriverInstanceActor(IDriver driver, TimeSpan reconnectInterval, bool startStubbed,
IDriverHealthPublisher? healthPublisher, string? clusterId, IDriverCapabilityInvoker? invoker,
TimeSpan? healthPollInterval, TimeSpan? commsLossTimeout, TimeSpan? shutdownTimeout,
int? maxWritesInFlight, TimeSpan? queuedWriteBudget, TimeSpan? initializeTimeout,
TimeSpan? writeTimeout, TimeProvider? writeClock, SourceSamplePublisher? sourcePublisher,
long? sourceIncarnation, IWriteDispatchGate? writeDispatchGate, LateWriteObserver? lateWriteObserver,
WriteRouteState? writeRouteState)
{
_writeDispatchGate = writeDispatchGate;
_lateWriteObserver = lateWriteObserver;
_writeRouteState = writeRouteState;
_sourcePublisher = sourcePublisher;
_sourceIncarnation = sourceIncarnation;
_writeTimeout = writeTimeout is { } wt && wt > TimeSpan.Zero ? wt : DefaultWriteTimeout;
@@ -618,6 +658,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <inheritdoc />
protected override void PreStart()
{
if (_writeRouteState is not null) _writeIncarnation = _writeRouteState.BeginDriverIncarnation(_driverInstanceId);
if (_sourcePublisher is not null && _sourceIncarnation is { } previous &&
!_sourcePublisher.IsDriverIncarnationActive(_driverInstanceId, previous))
_sourceIncarnation = _sourcePublisher.RegisterDriverIncarnation(_driverInstanceId);
@@ -662,6 +703,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// success without touching real hardware. Read returns null; Write succeeds.
Receive<InitializeRequested>(_ => { /* no-op */ });
Receive<WriteAttribute>(_ => Sender.Tell(new WriteAttributeResult(true, "stubbed")));
Receive<WriteAttributeWithOutcome>(msg => RejectRich(msg, Sender, "driver is stubbed"));
// Stubbed drivers have no upstream alarm system — swallow the ack (it's fire-and-forget, no reply).
Receive<RouteAlarmAck>(_ => { /* stubbed drivers have no alarm backend */ });
Receive<DisconnectObserved>(_ => { /* stubbed drivers don't disconnect */ });
@@ -683,6 +725,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// "write timeout". Synchronous Receive: Sender.Tell on the actor thread is safe.
Receive<WriteAttribute>(_ =>
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
Receive<WriteAttributeWithOutcome>(msg => RejectRich(msg, Sender, "driver not connected"));
// A write launched while Connected can finish after the transition out of it; its slot still frees.
Receive<WriteCompleted>(OnWriteCompleted);
// An ack arriving while still connecting can't reach the upstream alarm system; drop it and report it
@@ -763,6 +806,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// Synchronous Receive: the device call runs off the mailbox (see StartOrQueueWrite), so data changes
// and further writes are never head-of-line blocked behind a slow device.
Receive<WriteAttribute>(msg => StartOrQueueWrite(msg, Sender));
Receive<WriteAttributeWithOutcome>(msg => StartOrQueueRichWrite(msg, Sender));
Receive<WriteCompleted>(OnWriteCompleted);
ReceiveAsync<RouteAlarmAck>(HandleAcknowledgeAsync);
ReceiveAsync<Subscribe>(HandleSubscribeAsync);
@@ -993,6 +1037,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// timeout on an inbound write to a transiently-down driver). Synchronous Receive.
Receive<WriteAttribute>(_ =>
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
Receive<WriteAttributeWithOutcome>(msg => RejectRich(msg, Sender, "driver not connected"));
Receive<WriteCompleted>(OnWriteCompleted);
// An ack arriving while reconnecting can't reach the upstream alarm system; drop it and report it
// failed so the host reverts the locally-committed acknowledge (lmxopcua#760).
@@ -1192,13 +1237,180 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
if (_writesInFlight >= _maxWritesInFlight || _tagsInFlight.Contains(msg.TagId))
{
_pendingWrites.AddLast((msg, replyTo, issuedAt));
_pendingWrites.AddLast((msg, replyTo, issuedAt, ++_queuedWriteSequence));
return;
}
LaunchWrite(writable, msg, replyTo);
}
private static readonly DataWriteOutcome RichRejected = new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Write rejected before dispatch.");
private static readonly DataWriteOutcome RichUnknown = new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Device outcome is unknown.");
private static void RejectRich(WriteAttributeWithOutcome msg, IActorRef replyTo, string reason)
{
var outcome = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, reason);
if (msg.Claim.Complete(outcome)) msg.Ticket.Dispose();
else outcome = msg.Claim.CurrentOutcome ?? RichUnknown;
replyTo.Tell(outcome);
}
private void StartOrQueueRichWrite(WriteAttributeWithOutcome msg, IActorRef replyTo)
{
if (_writeDispatchGate is null || _lateWriteObserver is null || _driver is not (IWritable or IWriteOutcomeCapability))
{ RejectRich(msg, replyTo, "Rich writes are unavailable."); return; }
if (_writeClock.GetElapsedTime(msg.Ticket.IssuedAt) > _queuedWriteBudget ||
_writeClock.GetTimestamp() >= msg.Ticket.Proof.Admission.MonotonicExpiry)
{ RejectRich(msg, replyTo, "Write expired before dispatch."); return; }
var tag = msg.Ticket.Proof.DriverReference;
if (_writesInFlight >= _maxWritesInFlight || _tagsInFlight.Contains(tag))
{ _pendingRichWrites.AddLast((msg, replyTo, ++_queuedWriteSequence)); return; }
LaunchRichWrite(msg, replyTo);
}
private void LaunchRichWrite(WriteAttributeWithOutcome msg, IActorRef replyTo)
{
if (!_lateWriteObserver!.TryReserve(msg.Ticket.Proof.DriverInstanceId,
msg.Ticket.Proof.DriverReference, out var reservation))
{ RejectRich(msg, replyTo, "Outstanding driver write capacity exhausted."); return; }
var tag = msg.Ticket.Proof.DriverReference;
_writesInFlight++;
_tagsInFlight.Add(tag);
_ = RunRichWriteAsync(_driver, _invoker, ResolveHost(tag), msg, replyTo, Self,
_writeDispatchGate!, reservation!, _writeTimeout, _writeClock, _incarnation);
}
private sealed class WriteLifetime(WriteAdmissionTicket ticket, CancellationTokenSource cancellation) : IDisposable
{
public void Dispose() { try { ticket.Dispose(); } finally { cancellation.Dispose(); } }
}
private static async Task RunRichWriteAsync(IDriver driver, IDriverCapabilityInvoker invoker, string hostKey,
WriteAttributeWithOutcome msg, IActorRef replyTo, IActorRef self, IWriteDispatchGate gate,
LateWriteReservation reservation, TimeSpan timeout, TimeProvider clock, int incarnation)
{
var physical = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
var cancellation = new CancellationTokenSource(timeout, clock);
// This task represents the entire physical invocation, including synchronous work before a driver
// returns its task. Its permit and payload live until that invocation really exits.
reservation.Observe(physical.Task, msg.Claim, new WriteLifetime(msg.Ticket, cancellation));
var attempt = Task.Run(async () =>
{
try
{
return await invoker.ExecuteWriteAsync(hostKey, false, ct =>
{
WriteRequest[] request;
try { request = [new WriteRequest(msg.Ticket.Proof.DriverReference, DriverValue(msg.Ticket.Value))]; }
catch
{
var noCall = msg.Claim.Complete(RichRejected) ? RichRejected : msg.Claim.CurrentOutcome ?? RichUnknown;
if (!msg.Claim.IsDispatched) physical.TrySetResult(noCall);
return ValueTask.FromResult(noCall);
}
var rejection = gate.TryCommit(msg.Ticket, msg.Claim);
if (rejection is not null)
{
msg.Claim.Complete(rejection);
physical.TrySetResult(rejection);
return ValueTask.FromResult(rejection);
}
// The commit above is the linearization point. No await or external callback occurs
// between that commit and the invocation below; preemption after commit is post-dispatch.
try
{
if (driver is IWriteOutcomeCapability rich)
_ = ObserveRichDriver(rich.WriteWithOutcomesAsync(request, ct), physical);
else
_ = ObserveLegacyDriver(((IWritable)driver).WriteAsync(request, ct), physical);
}
catch { physical.TrySetResult(RichUnknown); }
return new ValueTask<DataWriteOutcome>(physical.Task);
}, cancellation.Token).ConfigureAwait(false);
}
catch
{
var outcome = msg.Claim.Complete(RichRejected) ? RichRejected : RichUnknown;
if (outcome == RichRejected) physical.TrySetResult(outcome);
else msg.Claim.Complete(outcome);
return outcome;
}
});
try
{
var outcome = await attempt.WaitAsync(timeout + WriteAbandonGrace(timeout), clock).ConfigureAwait(false);
replyTo.Tell(outcome);
}
catch
{
var outcome = msg.Claim.Complete(RichRejected) ? RichRejected : RichUnknown;
if (outcome == RichRejected) physical.TrySetResult(outcome);
else msg.Claim.Complete(outcome);
replyTo.Tell(outcome);
}
finally { self.Tell(new WriteCompleted(msg.Ticket.Proof.DriverReference, incarnation)); }
}
private static async Task ObserveRichDriver(Task<IReadOnlyList<DataWriteOutcome>> task,
TaskCompletionSource<DataWriteOutcome> physical)
{
try
{
var result = await task.ConfigureAwait(false);
var outcome = result is { Count: 1 } ? result[0] : RichUnknown;
if (outcome.State == DataWriteState.RejectedBeforeDispatch || outcome.State == DataWriteState.Unspecified) outcome = RichUnknown;
physical.TrySetResult(outcome);
}
catch { physical.TrySetResult(RichUnknown); }
}
private static async Task ObserveLegacyDriver(Task<IReadOnlyList<WriteResult>> task,
TaskCompletionSource<DataWriteOutcome> physical)
{
try
{
var result = await task.ConfigureAwait(false);
physical.TrySetResult(result is { Count: 1 } && IsGoodStatus(result[0].StatusCode)
? new(DataWriteState.AcceptedUnconfirmed, result[0].StatusCode, null) : RichUnknown);
}
catch { physical.TrySetResult(RichUnknown); }
}
private static object? DriverValue(DataValue value) => value.Kind switch
{
DataValueKind.Null => null,
DataValueKind.Bytes => value.GetBytes().ToArray(),
DataValueKind.Array => ToDriverArray(value),
_ => value.GetScalar(),
};
private static Array ToDriverArray(DataValue value)
{
var elements = value.GetArray();
var type = value.ArrayElementKind switch
{
DataValueKind.Boolean => typeof(bool), DataValueKind.Int8 => typeof(sbyte), DataValueKind.Int16 => typeof(short),
DataValueKind.Int32 => typeof(int), DataValueKind.Int64 => typeof(long), DataValueKind.UInt8 => typeof(byte),
DataValueKind.UInt16 => typeof(ushort), DataValueKind.UInt32 => typeof(uint), DataValueKind.UInt64 => typeof(ulong),
DataValueKind.Float => typeof(float), DataValueKind.Double => typeof(double), DataValueKind.String => typeof(string),
DataValueKind.Timestamp => typeof(DateTimeOffset), DataValueKind.Guid => typeof(Guid),
_ => throw new ArgumentException("Unsupported array element kind."),
};
var dimensions = value.Dimensions!.ToArray();
var result = Array.CreateInstance(type, dimensions);
var index = new int[dimensions.Length];
foreach (var element in elements)
{
result.SetValue(element, index);
for (var d = index.Length - 1; d >= 0; d--)
{
if (++index[d] < dimensions[d]) break;
index[d] = 0;
}
}
return result;
}
private void LaunchWrite(IWritable writable, WriteAttribute msg, IActorRef replyTo)
{
_writesInFlight++;
@@ -1296,7 +1508,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private void DrainWriteQueue()
{
if (_driver is not IWritable writable) return;
var writable = _driver as IWritable;
// Expire FIRST, over the whole queue, regardless of free slots: a write past its budget must be answered
// now, not whenever a slot next frees and the scan happens to reach it — the host's Ask covers the budget
@@ -1308,17 +1520,34 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
node = next;
}
for (var node = _pendingWrites.First; node is not null && _writesInFlight < _maxWritesInFlight;)
while (true)
{
var next = node.Next;
var (write, replyTo, _) = node.Value;
if (!_tagsInFlight.Contains(write.TagId))
var before = _pendingWrites.Count + _pendingRichWrites.Count;
for (var node = _pendingWrites.First; writable is not null && node is not null && _writesInFlight < _maxWritesInFlight;)
{
_pendingWrites.Remove(node);
LaunchWrite(writable, write, replyTo);
var next = node.Next;
var (write, replyTo, _, sequence) = node.Value;
if (!_tagsInFlight.Contains(write.TagId) && !_pendingRichWrites.Any(x =>
x.Sequence < sequence && x.Write.Ticket.Proof.DriverReference == write.TagId))
{
_pendingWrites.Remove(node);
LaunchWrite(writable, write, replyTo);
}
node = next;
}
node = next;
for (var node = _pendingRichWrites.First; node is not null;)
{
var next = node.Next;
var (write, replyTo, sequence) = node.Value;
if (_writeClock.GetElapsedTime(write.Ticket.IssuedAt) > _queuedWriteBudget ||
_writeClock.GetTimestamp() >= write.Ticket.Proof.Admission.MonotonicExpiry)
{ _pendingRichWrites.Remove(node); RejectRich(write, replyTo, "Write expired before dispatch."); }
else if (_writesInFlight < _maxWritesInFlight && !_tagsInFlight.Contains(write.Ticket.Proof.DriverReference)
&& !_pendingWrites.Any(x => x.Sequence < sequence && x.Write.TagId == write.Ticket.Proof.DriverReference))
{ _pendingRichWrites.Remove(node); LaunchRichWrite(write, replyTo); }
node = next;
}
if (_writesInFlight >= _maxWritesInFlight || before == _pendingWrites.Count + _pendingRichWrites.Count) break;
}
}
@@ -1349,6 +1578,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
_pendingWrites.RemoveFirst();
node.Value.ReplyTo.Tell(new WriteAttributeResult(false, reason));
}
while (_pendingRichWrites.First is { } rich)
{
_pendingRichWrites.RemoveFirst();
RejectRich(rich.Value.Write, rich.Value.ReplyTo, reason);
}
}
/// <summary>
@@ -2162,6 +2396,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <inheritdoc />
protected override void PostStop()
{
if (_writeIncarnation is { } writeIncarnation) _writeRouteState?.RetireDriver(_driverInstanceId, writeIncarnation);
if (_sourceIncarnation is { } incarnation) _sourcePublisher?.RetireDriver(_driverInstanceId, incarnation);
// Archreview 03/S15 — announce comms loss on the way out. Every OTHER route into Reconnecting
// (watchdog trip, failed initial connect, Force Reconnect) announces it from the Reconnecting
@@ -1,4 +1,5 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
@@ -113,6 +114,11 @@ public interface IHistoryUpdateRoleView
public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRoleSource, IHistorizationRoleView,
IHistoryUpdateRoleView
{
public RedundancyRoleView(DataWriteDispatchFence? dispatchFence = null) => DispatchFence = dispatchFence ?? new();
public DataWriteDispatchFence DispatchFence { get; }
private sealed record PrimaryVerdict(bool Allowed, long Generation);
private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0);
public long PrimaryGeneration => Volatile.Read(ref _primaryVerdict).Generation;
// seeded CLOSED, unlike the data-plane verdict. HistoryUpdate waits for a real redundancy verdict
// (PrimaryGatePolicy.ShouldServeHistoryUpdate); a node that never publishes here is not a driver node with a
// redundancy manager, and such a node does not register this view as its gate source.
@@ -130,9 +136,6 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
// a node nothing has reported a role for, on a cluster with no driver peer, is a single-node
// deployment and may claim. The moment a snapshot arrives this is replaced by the real verdict,
// and a multi-driver cluster's unknown role denies.
private volatile bool _shouldActAsPrimary =
PrimaryGatePolicy.ShouldServiceAsPrimary(localRole: null, driverMemberCount: 1);
// Seeded for the unknown-role case from the same policy that will later publish here: a node
// nothing has reported a role for captures, exactly as an unpaired or single-node deployment must.
// Defaulting closed would leave a deployment that never publishes a role with no trend data at all.
@@ -146,7 +149,7 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
public bool ShouldRecordHistorizedValues => _shouldRecordHistorizedValues;
/// <inheritdoc/>
public bool ShouldActAsPrimary => _shouldActAsPrimary;
public bool ShouldActAsPrimary => Volatile.Read(ref _primaryVerdict).Allowed;
/// <inheritdoc/>
public bool ShouldServeHistoryUpdate => _shouldServeHistoryUpdate;
@@ -158,7 +161,15 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
public void Publish(bool shouldDrainAlarmHistory) => _shouldDrainAlarmHistory = shouldDrainAlarmHistory;
/// <inheritdoc/>
public void PublishPrimaryRole(bool shouldActAsPrimary) => _shouldActAsPrimary = shouldActAsPrimary;
public void PublishPrimaryRole(bool shouldActAsPrimary)
{
using (DispatchFence.Enter())
{
var current = _primaryVerdict;
if (current.Generation == 0 || current.Allowed != shouldActAsPrimary)
Volatile.Write(ref _primaryVerdict, new(shouldActAsPrimary, checked(current.Generation + 1)));
}
}
/// <inheritdoc/>
public void PublishHistorizationRole(bool shouldRecordHistorizedValues)
@@ -57,6 +57,8 @@ public static class ServiceCollectionExtensions
/// <returns>The same <paramref name="services"/> instance for chaining.</returns>
public static IServiceCollection AddOtOpcUaRuntime(this IServiceCollection services)
{
// Authority and role publishers share the same ordering point as rich write dispatch.
services.TryAddSingleton<DataWriteDispatchFence>();
services.TryAddSingleton<IAlarmHistorianSink>(NullAlarmHistorianSink.Instance);
services.TryAddSingleton<IHistorianDataSource>(NullHistorianDataSource.Instance);
// Historian tag provisioning. Null default (no-op) so the AddressSpaceApplier resolves a real