using System.Diagnostics;
using Akka.Actor;
using Akka.Event;
using ZB.MOM.WW.OtOpcUa.Cluster;
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;
// private timer key type — file-scoped so the name stays unique per-file
file sealed class HealthPollTick
{
public static readonly HealthPollTick Instance = new();
private HealthPollTick() { }
}
/// Process-lifetime bound for physical subscription establishments and late cleanup.
public sealed class SubscriptionAcquisitionCapacity
{
private readonly object _gate = new();
private readonly Dictionary<(string Cluster, string Driver), TaskCompletionSource> _inFlight = new();
private readonly int _limit;
private long _ownerSerial;
private long _controlGeneration;
/// Creates a shared capacity with a fixed maximum number of in-flight drivers.
public SubscriptionAcquisitionCapacity(int limit)
{
if (limit <= 0) throw new ArgumentOutOfRangeException(nameof(limit));
_limit = limit;
}
/// Number of driver keys held by active subscriptions, establishments, or cleanup.
public int ReservedDriverCount { get { lock (_gate) return _inFlight.Count; } }
/// Configured maximum concurrent driver reservations.
public int MaxReservations => _limit;
/// Issues a process-lifetime serial for a new bridge owner.
public long NextOwnerSerial()
{
var serial = Interlocked.Increment(ref _ownerSerial);
return serial > 0 ? serial : throw new InvalidOperationException("Acquisition owner serial exhausted.");
}
/// Latest issued bridge owner serial.
public long CurrentOwnerSerial => Interlocked.Read(ref _ownerSerial);
/// Latest process-lifetime control generation.
public long ControlGeneration => Interlocked.Read(ref _controlGeneration);
internal long NextControlGeneration()
{
var generation = Interlocked.Increment(ref _controlGeneration);
return generation > 0 ? generation : throw new InvalidOperationException("Acquisition generation exhausted.");
}
internal IDisposable? TryAcquire(string cluster, string driver, out Task? ready)
{
var key = (cluster.ToUpperInvariant(), driver);
lock (_gate)
{
if (_inFlight.TryGetValue(key, out var existing)) { ready = existing.Task; return null; }
ready = null;
if (_inFlight.Count >= _limit) return null;
var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_inFlight.Add(key, completion);
return new Reservation(this, key, completion);
}
}
private sealed class Reservation(SubscriptionAcquisitionCapacity owner, (string Cluster, string Driver) key,
TaskCompletionSource completion) : IDisposable
{
private SubscriptionAcquisitionCapacity? _owner = owner;
public void Dispose()
{
var current = Interlocked.Exchange(ref _owner, null);
if (current is null) return;
lock (current._gate) current._inFlight.Remove(key);
completion.TrySetResult(true);
}
}
}
///
/// Akka wrapper for a single instance. States:
///
///
/// - Connecting — calling .
/// - Connected — initialised; serving Read/Write/Subscribe requests.
/// - Reconnecting — disconnect observed; periodic retry of Initialize.
/// - Failed — terminal until parent restarts the actor.
///
///
/// Engine wiring (subscriptions → AttributeValueUpdate publishes, per-tag write Asks) is staged for follow-up F7. This skeleton compiles + has a working
/// state machine so the Phase 6 control-plane integration tests can target it.
///
public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
{
public static readonly TimeSpan DefaultReconnectInterval = TimeSpan.FromSeconds(10);
public sealed record InitializeRequested(string DriverConfigJson);
public sealed record InitializeSucceeded(int Generation);
public sealed record InitializeFailed(string Reason, int Generation);
public sealed record DisconnectObserved(string Reason);
/// Sent to the parent () on every connectivity transition:
/// Connected=true on entering the Connected state, false on entering Reconnecting. The host
/// annotates this driver's native alarm conditions' source-data Quality from it (comms lost → Bad,
/// restored → Good) — independently of alarm transitions, since a comms-lost driver emits no alarm
/// events. Fire-and-forget.
public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected, long? ProducerIncarnation = null,
long? ConnectionEpoch = null);
///
/// Sent to the parent from so the host re-provisions THIS incarnation.
///
///
/// A supervision restart recreates the actor object in place: the desired subscription sets are gone
/// (they are instance fields), and PreRestart has already run — which
/// called on the driver object the Props closure re-uses. Nothing
/// else re-sends : its only sender is
/// DriverHostActor.SpawnChild, and a restart does NOT respawn (the child's
/// is unchanged, so the host is not otherwise notified that a new incarnation
/// exists at all). Without this the restarted child sits in Connecting forever around a
/// shut-down driver, with nothing subscribed — silently, since Akka logs the fault but the recovery
/// is invisible.
///
/// The driver instance that was restarted.
/// The type name of the exception that tripped supervision, for the host's log.
public sealed record ReprovisionRequested(string DriverInstanceId, string Reason);
/// An operator write of to the tag .
/// The tag's driver wire reference (RawPath).
/// The value to write.
/// When the asker issued the write, as a timestamp of the actor's write clock
/// (); null = when the actor receives it.
/// stamps it so the time the write spends in this actor's MAILBOX counts against the queue budget too: a write
/// delayed there (behind a hanging alarm subscribe, say) and then started could otherwise still be running
/// when the host's Ask fires (lmxopcua#777).
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);
///
/// Sent by 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).
/// The actor forwards it to the driver's , carrying the
/// authored alarm full-reference (= the driver's ConditionId/AlarmFullReference) and the
/// authenticated principal. Mirrors , but the ack is fire-and-forget:
/// the driver's returns no per-condition status and the
/// OPC UA Part 9 ack already committed the local condition state, so there is no reply to surface.
///
/// The authored alarm full-reference the driver correlates the ack on
/// (= the equipment tag's FullName/AlarmFullReference).
/// Operator-supplied comment forwarded to the upstream alarm system; null when none.
/// The authenticated principal performing the acknowledge.
/// Public id of the API key the session authenticated with; null for anonymous. Not a
/// secret — the Galaxy driver uses it to find the key's Galaxy ack identity (lmxopcua#749).
/// The OPC UA condition NodeId the client acknowledged. When set, an
/// acknowledge that does not reach the upstream alarm system (refused, failed, or dropped because the driver
/// is not connected) is reported back to the sender as an so the host can revert
/// the locally-applied acknowledge (lmxopcua#760). Null ⇒ no report.
/// The host projector's sequence for this acknowledge (lmxopcua#869), echoed on
/// so only a failure of THIS ack reverts it; 0 ⇒ the ack changed nothing.
public sealed record RouteAlarmAck(
string ConditionId, string? Comment, string OperatorUser, string? ApiKeyId = null, string? ConditionNodeId = null,
long AckSequence = 0);
///
/// Reply to a carrying a whose
/// acknowledge never reached the upstream alarm system (lmxopcua#760). Success sends nothing.
///
/// The OPC UA condition NodeId the client acknowledged.
/// Why the acknowledge did not go through; never contains a secret.
/// The failed acknowledge's (lmxopcua#869).
public sealed record AlarmAckFailed(string ConditionNodeId, string Reason, long AckSequence = 0);
public sealed record Subscribe(IReadOnlyList FullReferences, TimeSpan PublishingInterval);
///
/// Sets the set of references this driver should keep subscribed for the lifetime of the
/// current deployment. Unlike the one-shot , the desired set is
/// retained and (re)established automatically every time the actor (re)enters
/// Connected — closing the F8b "re-subscribe across reconnects" gap and giving
/// a single message to drive the SubscribeBulk pass after an
/// apply. Sending an empty set clears the desired subscription.
///
///
/// The native-alarm references (alarm-bearing equipment-tag FullNames = the driver's
/// ConditionId/AlarmFullReference) this driver should keep an alarm subscription open for.
/// An driver suppresses until at
/// least one alarm subscription exists, so the actor calls
/// with this set to un-gate the native feed. Empty
/// (or null) means the driver has no alarm tags. Defaults to null so non-alarm callers are unchanged.
///
public sealed record SetDesiredSubscriptions(
IReadOnlyList FullReferences,
TimeSpan PublishingInterval,
IReadOnlyList? AlarmReferences = null,
long DesiredRevision = 0, long ProducerIncarnation = 0, bool RequireAcquisition = false);
/// Physical demand installation result, including the driver-acknowledged fence.
public sealed record AcquisitionDemandApplied(long DesiredRevision, long ProducerIncarnation,
TimeSpan NominalSamplingInterval, bool Succeeded, bool Busy = false, Task? RetryWhenReady = null,
bool OwnerInvalid = false, bool KeyInvalid = false);
public sealed record SubscriptionEstablished(string DiagnosticId, int ReferenceCount);
public sealed record SubscriptionFailed(string Reason);
public sealed record Unsubscribe;
///
/// Sent by when the AdminUI issues a Reconnect operation.
/// Pushes the actor out of Connected into Reconnecting so the transport is
/// re-established without fully stopping and respawning the actor. Safe to send in any
/// state — a no-op when already Reconnecting or Connecting.
///
public sealed record ForceReconnect;
/// One value within an .
/// is the driver's full OPC UA status code including its sub-code
/// — not a severity bucket. Classify it with and friends rather
/// than comparing it to .
/// A struct deliberately: an AttributeValueItem[] then holds its items inline, so a burst of
/// N values costs one array allocation instead of one array plus N boxes. Indexed access through
/// does not box.
public readonly record struct AttributeValueItem(string FullReference, object? Value, uint StatusCode, DateTime TimestampUtc,
DateTime? SourceTimestampUtc = null, DateTime? ServerTimestampUtc = null);
/// The ONLY value message a driver child sends: every changed attribute of ONE driver production
/// burst in one message (a single data change is a one-item batch). The parent fans the whole batch to the mux and the OPC UA
/// publish path in one hop each. Status codes ride verbatim.
public sealed record AttributeValueBatchPublished(string DriverInstanceId, IReadOnlyList Items);
private sealed record DataChangeForward(string FullReference, DataValueSnapshot Snapshot, long? ProducerIncarnation);
/// Self-sent when a batch-capable driver () raises
/// — marshals the whole burst off the driver's
/// thread onto the actor thread in one hop. Parallels .
private sealed record DataChangeBatchForward(IReadOnlyList Items, long? ProducerIncarnation);
private sealed record RetrySourceBindings(IReadOnlyList References, int Offset, bool Failed,
int Attempt, long Version, long ProducerIncarnation);
/// Published to the parent whenever the subscribed driver (an ) fires
/// . The parent () projects + routes it
/// to the materialised Part 9 condition. Parallels .
public sealed record AttributeAlarmPublished(string DriverInstanceId, AlarmEventArgs Args);
private sealed record NativeAlarmRaised(AlarmEventArgs Args);
/// A1 (plan §5.1 F2): published to the parent when the driver raises
/// . It travels the SAME self-Tell → parent path as
/// , so it reaches after every alarm event the
/// driver raised before it.
/// A1 review S2: is the connection (Connected entry) the driver raised
/// it under, matching of that Good edge.
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args,
long? ConnectionEpoch = null);
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch);
/// Self-sent on Connected entry / when alarm refs are (re)pushed, to establish the native-alarm
/// subscription that un-gates an driver's feed. Handled async so the
/// call is bounded + off the synchronous handlers.
private sealed record SubscribeAlarms;
/// Self-sent when the wrapped driver raises —
/// it observed that the remote's tag set may have changed. Marshals the event off the driver's thread
/// onto the actor thread. Handled in EVERY behaviour, including Stubbed and Reconnecting: the raise has no
/// connection affinity (a Galaxy redeploy or a TwinCAT symbol-version bump can land while the driver is
/// between connects), and dropping it in one state would lose the signal silently.
private sealed record RediscoveryRaised(RediscoveryEventArgs Args);
/// Self-sent when the wrapped driver raises
/// — one of its hosts went Running ↔ Stopped ↔ Faulted. Marshals the event off the driver's probe thread
/// onto the actor thread. Carries NO payload: the handler re-pulls
/// , so the driver stays the single source of truth
/// for the host set and a host that appeared since the last publish is picked up too. Handled in every
/// behaviour for the same reason as — a probe tick can land while the
/// driver is between connects.
private sealed record HostStatusRaised;
/// Self-sent when the wrapped driver raises
/// — it KNOWS its connection is gone for good. Marshals the event off the driver's thread. Acted on only in
/// Connected (it becomes a disconnect at once, instead of after the watchdog's silence window); every other
/// behaviour is already reconnecting or connecting and ignores it.
private sealed record ConnectionLossRaised(DriverConnectionLossEventArgs Args);
public sealed class RetryConnect
{
public static readonly RetryConnect Instance = new();
private RetryConnect() { }
}
/// Interval between periodic health-poll heartbeats sent to the snapshot store.
public static readonly TimeSpan HealthPollInterval = TimeSpan.FromSeconds(30);
///
/// How long a Connected driver may go without a single successful read — while also reporting
/// itself non-Healthy — before the actor declares comms lost. Evaluated on the
/// existing tick, so the effective detection granularity is
/// 30 s and the worst-case detection latency is this value plus one tick.
///
///
/// 90 s = three health-poll ticks. Long enough that a device answering slowly under load is not
/// torn down, short enough that an operator watching a dead PLC sees it inside two minutes.
/// Hardcoded rather than exposed in appsettings, matching and
/// . Unlike the periodic drift-detector removed earlier,
/// this generates no outbound traffic on a healthy system: the watchdog is a local
/// read of , and it only reaches the network once a driver has
/// already stopped reading successfully.
///
public static readonly TimeSpan DefaultCommsLossTimeout = TimeSpan.FromSeconds(90);
///
/// Bound on the driver's (and its dispose) when the child stops or
/// restarts, and on the teardown that precedes every reconnect attempt. PostStop runs on a
/// dispatcher thread and blocks on it, so a driver whose shutdown waits on a dead socket / COM proxy used
/// to pin that thread for as long as the wait took — a few such stops starved the default dispatcher and
/// wedged CoordinatedShutdown and the host's own restart cascade. A shutdown that overruns is
/// abandoned (logged), never awaited further.
///
public static readonly TimeSpan DefaultShutdownTimeout = TimeSpan.FromSeconds(5);
///
/// Default cap on the writes this actor runs against its driver at once. Writes run OFF the mailbox
/// (a ReceiveAsync used to suspend it for the whole device round-trip, so writes serialised and
/// every data change queued behind them — the second of two operator writes to a slow device missed the
/// host's 8 s Ask and was reverted although the device took it). The cap keeps a burst from flooding a
/// device with concurrent commands; writes beyond it queue in order and start as slots free.
///
public const int DefaultMaxWritesInFlight = 4;
///
/// How long a queued write may wait for a slot before it is failed BadTimeout instead of being
/// written, when no explicit budget is given: of the write
/// timeout in force (lmxopcua#777 — it was a fixed 8 s, equal to the host's whole Ask, so a write dequeued
/// just inside it could still be running when the Ask fired). The host's Ask covers this budget PLUS a full
/// write (), so a write started inside the budget is always answered
/// before the host reports it failed.
///
public static readonly TimeSpan DefaultQueuedWriteBudget = DriverWriteBounds.Default.QueueBudget;
///
/// Pessimistic bound on one attempt. The invoker's tier timeout is
/// token-only (optimistic), so a driver whose initialise ignores its token would otherwise hold the
/// single-flight gate forever and wedge the reconnect loop. 2× the longest tier (Tier C: 15 s).
///
public static readonly TimeSpan DefaultInitializeTimeout = TimeSpan.FromSeconds(30);
///
/// Bound on one write round-trip. The write's cancellation token is cancelled when it elapses (the write
/// answers "write timeout"); a driver whose ignores its token is
/// abandoned later (the write answers BadTimeout and frees its slot
/// and tag), so it cannot hold its slot AND its tag forever, piling every later write to that tag up in the
/// queue.
///
///
/// . The host's write Ask is DERIVED from the same value
/// (, lmxopcua#777), so any configured write timeout is answered
/// inside it; until then the Ask was a fixed 8 s and a write timeout above ~6 s let a write outlive it.
///
public static readonly TimeSpan DefaultWriteTimeout = DriverWriteBounds.DefaultTimeout;
///
/// How long after a write's token is cancelled a write that has not returned is abandoned as
/// token-ignoring; see .
///
/// The write timeout in force.
/// The grace between cancelling the write's token and abandoning the write.
internal static TimeSpan WriteAbandonGrace(TimeSpan writeTimeout) => DriverWriteBounds.AbandonGraceFor(writeTimeout);
/// Self-sent by a write task once it has replied, releasing its slot and its tag.
/// The tag the write held.
/// The actor incarnation that launched it — a late completion from a previous
/// incarnation (after a supervision restart) must not free the new incarnation's slot or tag.
private sealed record WriteCompleted(string TagId, int Incarnation);
private readonly IDriver _driver;
/// Phase 6.1 resilience seam: every guarded driver-capability call this actor makes is
/// routed through this invoker (retry / breaker / in-flight accounting / tracker telemetry). Defaults to
/// (a genuine pass-through) when none is supplied — so
/// unit tests + the F7 skeleton path behave exactly as a raw driver call. The fused Host builds a
/// real per-instance invoker via and injects it at
/// spawn. Consumed through the abstraction because Runtime
/// is deliberately Polly-free (it does not reference ZB.MOM.WW.OtOpcUa.Core).
private readonly IDriverCapabilityInvoker _invoker;
private readonly string _driverInstanceId;
private readonly string _clusterId;
private readonly IDriverHealthPublisher _healthPublisher;
private readonly TimeSpan _reconnectInterval;
private readonly TimeSpan _healthPollInterval;
/// Comms-loss watchdog threshold; or negative disables it.
private readonly TimeSpan _commsLossTimeout;
/// Bound on the driver shutdown / dispose; see .
private readonly TimeSpan _shutdownTimeout;
/// Cap on concurrent writes; see .
private readonly int _maxWritesInFlight;
/// Writes currently inside the driver. Actor-thread only (incremented on launch, decremented on
/// the self-sent ).
private int _writesInFlight;
/// Writes waiting for a slot (or for their tag), in arrival order, stamped with arrival time.
/// Failed fast on every exit from Connected, so a queued write never reaches a driver that is
/// reconnecting; failed BadTimeout once older than since issued.
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;
/// 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.
private readonly HashSet _tagsInFlight = new(StringComparer.Ordinal);
/// See .
private readonly TimeSpan _queuedWriteBudget;
/// See .
private readonly TimeSpan _initializeTimeout;
/// See .
private readonly TimeSpan _writeTimeout;
/// The clock the write bounds run on — outside tests.
private readonly TimeProvider _writeClock;
/// This actor object's identity for its own off-mailbox completions (drawn from the process-wide
/// generation source, so it is unique across supervision restarts of the same child).
private readonly int _incarnation;
///
/// Set by so the it triggers skips the dispose. A
/// supervision restart recreates the actor object around the SAME (the Props closure
/// captured it) and the host then re-initialises that driver — disposing it here would hand the new
/// incarnation a dead object. Only a real stop (deploy removal, operator Restart, respawn on config change,
/// host shutdown) disposes.
///
private bool _restarting;
/// When the actor last entered Connected. The comms-loss watchdog's baseline for a
/// driver that has never reported a successful read, so "connected but never read anything" is
/// measurable rather than indefinitely undefined.
private DateTime _connectedSinceUtc;
private readonly ILoggingAdapter _log = Context.GetLogger();
private string? _currentConfigJson;
/// Monotonic token tagging each attempt. An init result is
/// honoured only when its generation matches the latest; an older result is from a superseded attempt
/// (a retry tick that overlapped a still-running attempt) and is dropped. Touched only
/// on the actor thread, so no lock is needed.
private int _initGeneration;
/// Process-wide source of attempt generations. A supervision restart recreates the actor object
/// (fresh fields) while a prior incarnation's attempt may still be running on the same driver; a per-actor
/// counter restarting at 0 would let that late result collide with the new incarnation's first attempt.
private static int s_initGenerationSource;
///
/// True while an attempt is running (set when it is launched, cleared by its
/// piped /). The Reconnecting retry
/// timer fires on its cadence regardless of whether the previous attempt finished, and the generation
/// token only discards an older attempt's RESULT — so with an Initialize bound longer than the cadence
/// (Tier C: 15 s vs. 10 s) attempt N+1's teardown ran while attempt N was still inside the driver: the
/// dispose-before-overwrite race the drivers' rule file forbids, once per overlap. A tick that lands while
/// an attempt is in flight is skipped; the next tick after the result retries. Actor-thread only.
///
private bool _initInFlight;
/// Cancellation for the in-flight attempt, so can cancel it before the
/// shutdown rather than let it race the teardown on a restart.
private CancellationTokenSource? _initCts;
/// Cancelled by to abandon in-flight native-ack confirmations (lmxopcua#869);
/// never disposed — detached confirmation tasks may still hold its token.
private readonly CancellationTokenSource _ackConfirmCts = new();
///
/// Timestamps of recent Faulted-state transitions; used to compute the 5-minute error count.
/// No lock needed — every read/write site runs inside an Akka message handler, which is
/// single-threaded per actor instance.
///
private readonly Queue _faultTimestamps = new();
/// Active subscription handle (null when not subscribed). Tracks the current live
/// subscription; the actor auto-(re)subscribes on (re)connect and on each
/// message via / , so callers
/// do not need to re-send subscription requests after a reconnect.
private ISubscriptionHandle? _subscriptionHandle;
private EventHandler? _dataChangeHandler;
/// The batch data-change handler, attached INSTEAD of when the
/// driver is an . Exactly one of the two is ever non-null.
private EventHandler? _batchChangeHandler;
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
private long? _sourceIncarnation;
private long _sourceBindingVersion;
private sealed class AcquisitionFence(long revision, long producer)
{
internal readonly long Revision = revision;
internal readonly long Producer = producer;
}
private AcquisitionFence? _activeAcquisition;
private int _acquisitionPending;
private readonly SubscriptionAcquisitionCapacity? _acquisitionCapacity;
private PendingAcquisition? _pendingAcquisition;
private PendingAcquisition? _abandonedAcquisition;
private readonly TimeSpan _acquisitionTimeout;
private readonly TimeProvider _acquisitionClock;
private SharedAcquisitionReservation? _activeCapacity;
private IDisposable? _activeCapacityReference;
private Task? _previousAcquisitionCleanup;
private bool _fenceLegacyHandles;
private LegacyAdmission? _legacyAdmission;
private SetDesiredSubscriptions? _desiredAcquisition;
private TimeSpan _acquisitionNominal;
private SetDesiredSubscriptions? _deferredLegacyDemand;
private sealed record ResumeDeferredLegacy;
private const int SourceBindingBatchSize = 128;
private EventHandler? _alarmEventHandler;
// A1 (plan §5.1 G5): attached and detached WITH the alarm handler, so the signal obeys exactly the gate
// OnAlarmEvent obeys.
private EventHandler? _alarmInitialStateHandler;
// A1 review S2: bumped on every Connected entry; read on the driver's thread when it raises its signal.
private long _connectionEpoch;
private EventHandler? _rediscoveryHandler;
private EventHandler? _hostStatusHandler;
private EventHandler? _connectionLossHandler;
/// When the driver last raised , and the reason
/// it gave. Null until the first raise. Carried on every subsequent health snapshot so the AdminUI can
/// prompt an operator to re-browse the device.
/// Deliberately sticky — it is not cleared on reconnect or on a later clean pass. The remote's
/// tag set stayed changed; only an operator re-browsing and committing resolves it, and this actor cannot
/// observe that happening. A redeploy respawns the child, which clears it naturally.
private DateTime? _rediscoveryNeededUtc;
private string? _rediscoveryReason;
/// The references the host wants kept subscribed (set by ).
/// Re-applied on every entry into Connected so values resume after a reconnect or redeploy.
private IReadOnlyList _desiredRefs = Array.Empty();
private TimeSpan _desiredInterval = TimeSpan.FromSeconds(1);
/// The native-alarm references the host wants kept subscribed (set by
/// ). Re-applied on every Connected entry so the alarm
/// feed is re-un-gated after a reconnect/redeploy.
private IReadOnlyList _desiredAlarmRefs = Array.Empty();
/// The active native-alarm subscription handle for an driver, or
/// null when none is established. Reset on so the next Connected entry
/// re-subscribes against the freshly re-initialised driver; the null check makes the subscribe
/// idempotent across repeated pushes.
private IAlarmSubscriptionHandle? _alarmSubscriptionHandle;
/// The alarm references the live was actually established
/// with, so a CHANGED desired set can be told apart from a repeat of the same one.
/// Without this the subscription latched: both and
/// gate on "a handle already exists", which is the right guard
/// for an idempotent re-push and the WRONG one for a deploy that widens or narrows the alarm set —
/// drivers that filter on sourceNodeIds (OPC UA Client, AB CIP, FOCAS) would then never deliver a
/// newly-added alarm for the life of the connection. Empty whenever no handle is held.
private IReadOnlyList _subscribedAlarmRefs = Array.Empty();
/// Consecutive failures; reset on success and on
/// (a new connection starts a new streak).
private int _alarmSubscribeFailures;
/// Health-poll ticks the alarm reconcile still skips before its next retry (backoff).
private int _alarmRetrySkipTicks;
/// Backoff cap: at the production 30 s tick a failing alarm subscribe is retried at least
/// every 4 minutes.
private const int MaxAlarmRetrySkipTicks = 7;
///
/// Gets or sets the timer scheduler for scheduling reconnection attempts.
///
public ITimerScheduler Timers { get; set; } = null!;
///
/// Creates a Props object for instantiating a .
///
/// The driver instance to wrap.
/// Optional interval for reconnection attempts; defaults to 10 seconds.
/// If true, the actor starts in stub mode for testing or unavailable platforms.
/// Optional health publisher; defaults to so tests and
/// stub paths don't need to provide one.
/// Optional cluster identifier forwarded in messages;
/// defaults to an empty string when not provided (e.g. in unit tests).
/// Optional Phase 6.1 resilience invoker wrapping this driver's capability
/// calls; defaults to (pass-through) when not supplied.
/// Optional period of the health-poll heartbeat, which also drives the
/// subscription reconcile (); defaults to
/// . Exists so a test can drive the reconcile without waiting 30 s.
/// Optional comms-loss watchdog threshold; defaults to
/// . disables the watchdog — used by
/// tests that need a Connected driver to stay Connected while reporting non-Healthy.
/// Optional bound on the driver's shutdown / dispose on stop and on the
/// pre-reconnect teardown; defaults to . Exists so a test can prove a
/// hung shutdown is abandoned without waiting 5 s.
/// Optional cap on concurrent writes against the driver; defaults to
/// . Writes beyond it queue in arrival order.
/// Optional bound on how long a queued write may wait before it is failed
/// BadTimeout; defaults to of the write timeout in force.
/// Optional pessimistic bound on one initialise attempt; defaults to
/// .
/// Optional bound on one write round-trip (its token is cancelled when it elapses;
/// a token-ignoring write is abandoned later); defaults to
/// .
/// Optional clock for the write bounds; defaults to .
/// Exists so a test can step past a bound without waiting for it.
/// A instance configured to create the wrapped .
public static Props Props(
IDriver driver,
TimeSpan? reconnectInterval = null,
bool startStubbed = false,
IDriverHealthPublisher? healthPublisher = null,
string? clusterId = null,
IDriverCapabilityInvoker? invoker = null,
TimeSpan? healthPollInterval = null,
TimeSpan? commsLossTimeout = null,
TimeSpan? shutdownTimeout = null,
int? maxWritesInFlight = null,
TimeSpan? queuedWriteBudget = null,
TimeSpan? initializeTimeout = null,
TimeSpan? writeTimeout = null,
TimeProvider? writeClock = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
long? sourceIncarnation = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
TimeSpan? acquisitionTimeout = null, TimeProvider? acquisitionClock = null) =>
Akka.Actor.Props.Create(() => new DriverInstanceActor(
driver,
reconnectInterval ?? DefaultReconnectInterval,
startStubbed,
healthPublisher ?? NullDriverHealthPublisher.Instance,
clusterId ?? string.Empty,
invoker,
healthPollInterval,
commsLossTimeout,
shutdownTimeout,
maxWritesInFlight,
queuedWriteBudget,
initializeTimeout,
writeTimeout,
writeClock, sourcePublisher, sourceIncarnation, acquisitionCapacity, acquisitionTimeout, acquisitionClock));
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,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
TimeSpan? acquisitionTimeout = null, TimeProvider? acquisitionClock = null) =>
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, acquisitionCapacity,
acquisitionTimeout, acquisitionClock)));
private sealed class RichWriteActorProducer(Func create) : IIndirectActorProducer
{
public Type ActorType => typeof(DriverInstanceActor);
public ActorBase Produce() => create();
public void Release(ActorBase actor) { }
}
///
/// Returns true when the driver should boot in DEV-STUB mode based on host platform and
/// configured roles. Only the legacy v1 in-process "Galaxy" type stays Windows-only:
/// the legacy MXAccess COM proxy (retired in PR 7.2; gated for any leftover DriverInstance
/// rows that still reference the old type name).
/// The v2 "GalaxyMxGateway" driver talks gRPC to an external mxaccessgw process,
/// so it runs on any platform .NET 10 supports — Linux containers included. Not stubbed.
///
/// The type identifier of the driver.
/// Operational roles configured for this instance.
/// True if the driver should start in DEV-STUB mode; otherwise false.
public static bool ShouldStub(string driverType, IEnumerable roles)
{
var isWindowsOnly = driverType is "Galaxy";
if (!OperatingSystem.IsWindows() && isWindowsOnly) return true;
// GossipedRolesHave, not a bare "dev" literal Contains — the same
// case-insensitivity the rest of the role authority gives every other consumer.
if (RoleParser.GossipedRolesHave(roles, RoleParser.Dev) && isWindowsOnly) return true;
return false;
}
///
/// Initializes a new instance of the class.
///
/// The driver instance to wrap and manage.
/// Interval between reconnection attempts.
/// If true, start in stub mode for testing or unavailable platforms.
/// Sink for health-change notifications; must not be null.
/// Cluster identifier forwarded in health snapshots.
/// Phase 6.1 resilience invoker wrapping this driver's capability calls;
/// defaults to (pass-through) when null.
/// Period of the health-poll heartbeat, which also drives the
/// subscription reconcile; defaults to when null.
/// Comms-loss watchdog threshold; defaults to
/// when null, and is disabled when zero or negative.
/// Bound on the driver's shutdown / dispose; defaults to
/// when null.
/// Cap on concurrent writes; defaults to
/// when null or non-positive.
/// Bound on a queued write's wait; defaults to
/// of the write timeout when null or non-positive.
/// Pessimistic bound on one initialise attempt; defaults to
/// when null or non-positive.
/// Bound on one write round-trip; defaults to
/// when null or non-positive.
/// Clock for the write bounds; defaults to .
public DriverInstanceActor(
IDriver driver,
TimeSpan reconnectInterval,
bool startStubbed = false,
IDriverHealthPublisher? healthPublisher = null,
string? clusterId = null,
IDriverCapabilityInvoker? invoker = null,
TimeSpan? healthPollInterval = null,
TimeSpan? commsLossTimeout = null,
TimeSpan? shutdownTimeout = null,
int? maxWritesInFlight = null,
TimeSpan? queuedWriteBudget = null,
TimeSpan? initializeTimeout = null,
TimeSpan? writeTimeout = null,
TimeProvider? writeClock = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
long? sourceIncarnation = null,
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
TimeSpan? acquisitionTimeout = null, TimeProvider? acquisitionClock = null)
: this(driver, reconnectInterval, startStubbed, healthPublisher, clusterId, invoker, healthPollInterval,
commsLossTimeout, shutdownTimeout, maxWritesInFlight, queuedWriteBudget, initializeTimeout,
writeTimeout, writeClock, sourcePublisher, sourceIncarnation, null, null, null, acquisitionCapacity,
acquisitionTimeout, acquisitionClock) { }
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, SubscriptionAcquisitionCapacity? acquisitionCapacity,
TimeSpan? acquisitionTimeout, TimeProvider? acquisitionClock)
{
_writeDispatchGate = writeDispatchGate;
_lateWriteObserver = lateWriteObserver;
_writeRouteState = writeRouteState;
_sourcePublisher = sourcePublisher;
_acquisitionCapacity = acquisitionCapacity;
_acquisitionTimeout = acquisitionTimeout is { } timeout && timeout > TimeSpan.Zero ? timeout : TimeSpan.FromSeconds(10);
_acquisitionClock = acquisitionClock ?? TimeProvider.System;
_sourceIncarnation = sourceIncarnation;
_writeTimeout = writeTimeout is { } wt && wt > TimeSpan.Zero ? wt : DefaultWriteTimeout;
_writeClock = writeClock ?? TimeProvider.System;
_incarnation = Interlocked.Increment(ref s_initGenerationSource);
_maxWritesInFlight = maxWritesInFlight is > 0 ? maxWritesInFlight.Value : DefaultMaxWritesInFlight;
_queuedWriteBudget = queuedWriteBudget is { } qb && qb > TimeSpan.Zero
? qb
: new DriverWriteBounds(_writeTimeout).QueueBudget;
_initializeTimeout = initializeTimeout is { } it && it > TimeSpan.Zero ? it : DefaultInitializeTimeout;
_driver = driver;
_invoker = invoker ?? NullDriverCapabilityInvoker.Instance;
_driverInstanceId = driver.DriverInstanceId;
_clusterId = clusterId ?? string.Empty;
_healthPublisher = healthPublisher ?? NullDriverHealthPublisher.Instance;
_reconnectInterval = reconnectInterval;
_healthPollInterval = healthPollInterval ?? HealthPollInterval;
_commsLossTimeout = commsLossTimeout ?? DefaultCommsLossTimeout;
_shutdownTimeout = shutdownTimeout is { } bound && bound > TimeSpan.Zero ? bound : DefaultShutdownTimeout;
OtOpcUaTelemetry.DriverInstanceLifecycle.Add(1,
new KeyValuePair("event", startStubbed ? "spawn_stub" : "spawn"),
new KeyValuePair("driver_type", driver.DriverType));
if (startStubbed)
{
Context.GetLogger().Info("[DEV-STUB] driver={Name} type={Type}",
_driverInstanceId, driver.DriverType);
Become(Stubbed);
}
else
{
Become(Connecting);
}
}
///
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);
// Warm up the snapshot store immediately so AdminUI sees current state as soon as the
// actor starts, before any state transition fires. Also start the periodic heartbeat so
// long-lived Healthy drivers keep their snapshot fresh for newly-joined SignalR clients.
// Attach the rediscovery signal before the first publish. Not per-connect: an IRediscoverable raise
// has no connection affinity, and a driver can observe a remote change while disconnected.
AttachRediscoverySource();
AttachHostStatusSource();
AttachConnectionLossSource();
PublishHealthSnapshot();
Timers.StartPeriodicTimer("health-poll", HealthPollTick.Instance, _healthPollInterval);
}
// Ask the host to re-provision this incarnation - see ReprovisionRequested for why a supervision
// restart otherwise leaves a dead child. base.PostRestart runs first because it runs PreStart, which
// re-attaches the rediscovery / host-status sources and restarts the health timer; the reprovision
// is the part PreStart cannot do, since only the host knows this driver's config and desired set.
///
protected override void PostRestart(Exception reason)
{
base.PostRestart(reason);
Context.Parent.Tell(new ReprovisionRequested(_driverInstanceId, reason.GetType().Name));
}
///
/// Flags the restart before the base implementation runs , so that PostStop
/// shuts the driver down (the host re-initialises it on ) but does
/// NOT dispose it — see .
///
///
protected override void PreRestart(Exception reason, object message)
{
_restarting = true;
base.PreRestart(reason, message);
}
private void Stubbed()
{
// Stubbed drivers accept the standard message contracts but return deterministic
// success without touching real hardware. Read returns null; Write succeeds.
Receive(_ => { /* no-op */ });
Receive(_ => Sender.Tell(new WriteAttributeResult(true, "stubbed")));
Receive(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(_ => { /* stubbed drivers have no alarm backend */ });
Receive(_ => { /* stubbed drivers don't disconnect */ });
Receive(IgnoreConnectionLoss);
Receive(_ => { /* stubbed drivers don't reconnect */ });
Receive(StoreDisconnectedDesiredSubscriptions);
// Stubbed drivers never enter Connected, so they never kick discovery; swallow defensively in case a
// re-discovery self-tick is ever routed here so it doesn't surface as an Akka Unhandled message.
Receive(HandleRediscoveryRaised);
Receive(_ => PublishHealthSnapshot());
Receive(_ => PublishHealthSnapshot());
}
private void Connecting()
{
Receive(msg => InitializeAsync(msg.DriverConfigJson));
// Fast-fail writes while still connecting — without this the inbound WriteAttribute dead-letters
// and DriverHostActor.HandleRouteNodeWrite waits its full Ask before reporting a generic
// "write timeout". Synchronous Receive: Sender.Tell on the actor thread is safe.
Receive(_ =>
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
Receive(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(OnWriteCompleted);
// An ack arriving while still connecting can't reach the upstream alarm system; drop it and report it
// failed so the host reverts the locally-committed acknowledge (lmxopcua#760).
Receive(msg =>
{
_log.Debug("DriverInstance {Id}: alarm ack arrived during connect — dropped (driver not connected)", _driverInstanceId);
ReportAckFailed(Sender, msg, "the driver is not connected");
});
Receive(msg =>
{
if (msg.Generation != _initGeneration) return;
CompleteInitAttempt();
_log.Info("DriverInstance {Id}: connected", _driverInstanceId);
Become(Connected);
PublishHealthSnapshot();
ResubscribeDesired();
AttachAlarmSource();
SubscribeDesiredAlarms();
});
Receive(msg =>
{
if (msg.Generation != _initGeneration) return;
CompleteInitAttempt();
_log.Warning("DriverInstance {Id}: initialize failed: {Reason}", _driverInstanceId, msg.Reason);
RecordFault();
Become(Reconnecting);
PublishHealthSnapshot();
});
Receive(StoreDisconnectedDesiredSubscriptions);
Receive(_ => { /* already connecting — no-op */ });
Receive(IgnoreConnectionLoss);
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive(msg =>
_log.Debug("DriverInstance {Id}: subscription established ({Count} refs, {Diag})",
_driverInstanceId, msg.ReferenceCount, msg.DiagnosticId));
// Symmetric to the SubscriptionEstablished swallow: a failed self-resubscribe replies SubscriptionFailed
// to Self (HandleSubscribeAsync already logged the underlying cause). Swallow it so it doesn't dead-letter.
Receive(msg =>
_log.Debug("DriverInstance {Id}: resubscribe reported failure: {Reason}", _driverInstanceId, msg.Reason));
// A native alarm transition can race in while still (re)connecting (the driver's feed runs on its
// own thread); drop it — the feed re-delivers active alarms once Connected. Trace only.
Receive(_ =>
_log.Debug("DriverInstance {Id}: native alarm arrived during connect — dropped (feed re-delivers)", _driverInstanceId));
// Its initial-state signal is dropped with it: a signal must never outlive the alarm events it covers.
Receive(_ =>
_log.Debug("DriverInstance {Id}: initial alarm-state signal arrived during connect — dropped", _driverInstanceId));
// A SubscribeAlarms self-tell (from Connected) can be overtaken by an already-queued disconnect into
// this state; swallow it so it doesn't dead-letter — the next Connected entry re-subscribes.
Receive(_ => { });
Receive(HandleRediscoveryRaised);
Receive(_ => PublishHealthSnapshot());
Receive(_ => PublishHealthSnapshot());
}
private void Connected()
{
// Announce connectivity to the host so it can clear any comms-lost Quality annotation on this
// driver's native alarm conditions (Bad → Good). Fire-and-forget; the host defaults conditions to a
// non-Good "waiting for initial data" quality at materialise, and this is what confirms them Good.
// A1 review S2: a new connection epoch — a signal the driver raised under an earlier one is dropped below.
var epoch = Interlocked.Increment(ref _connectionEpoch);
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true, ProducerIncarnation: _sourceIncarnation,
ConnectionEpoch: epoch));
// Baseline for the comms-loss watchdog. Re-stamped on every Connected entry so a driver that
// reconnects but never manages a read is measured from THIS connect, not from a stale earlier one.
_connectedSinceUtc = DateTime.UtcNow;
Receive(msg => HandleDisconnectObserved(msg.Reason));
// The driver KNOWS its connection is gone (e.g. OpcUaClient: the upstream server halted or forgot the
// session). Same handling as the watchdog's disconnect, minus the ~90 s of silence it would need to prove it.
// Handled inline rather than re-told as DisconnectObserved (Reconnecting also swallows a stray DisconnectObserved).
Receive(msg => HandleDisconnectObserved($"driver reported connection lost: {msg.Args.Reason}"));
Receive(_ =>
{
_log.Info("DriverInstance {Id}: ForceReconnect requested by admin; re-entering Reconnecting", _driverInstanceId);
DetachSubscription();
FailQueuedWrites("driver not connected");
Become(Reconnecting);
PublishHealthSnapshot();
});
// 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(msg => StartOrQueueWrite(msg, Sender));
Receive(msg => StartOrQueueRichWrite(msg, Sender));
Receive(OnWriteCompleted);
ReceiveAsync(HandleAcknowledgeAsync);
ReceiveAsync(HandleSubscribeAsync);
ReceiveAsync(_ => { CancelSourceBindingRetry(); return UnsubscribeAsync(); });
Receive(RetrySourceBindingBatch);
ReceiveAsync(async msg =>
{
if (msg.RequireAcquisition)
{
var replyTo = Sender;
await ApplyAcquisitionDemandAsync(msg, result => replyTo.Tell(result));
return;
}
if (_abandonedAcquisition is { } abandoned && !abandoned.Finished.IsCompleted)
{
var schedule = _deferredLegacyDemand is null;
_deferredLegacyDemand = msg;
if (schedule)
{
var self = Self;
_ = abandoned.Finished.ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion && t.Result) self.Tell(new ResumeDeferredLegacy()); },
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
return;
}
if (_abandonedAcquisition is { Finished: { IsCompletedSuccessfully: true, Result: false } })
{
_deferredLegacyDemand = msg;
return;
}
if (_previousAcquisitionCleanup is { IsCompletedSuccessfully: true, Result: false } && _activeCapacityReference is not null)
{
_deferredLegacyDemand = msg;
return;
}
if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup && _activeCapacityReference is not null)
{
var schedule = _deferredLegacyDemand is null;
_deferredLegacyDemand = msg;
if (schedule)
{
var self = Self;
_ = cleanup.ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion && t.Result) self.Tell(new ResumeDeferredLegacy()); },
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
return;
}
_deferredLegacyDemand = null;
_desiredAcquisition = null;
CancelSourceBindingRetry();
StoreDesiredSubscriptions(msg);
if (_desiredRefs.Count > 0) Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
else if (_subscriptionHandle is not null) Self.Tell(new Unsubscribe());
// Native-alarm analogue: un-gate the IAlarmSource feed when alarm tags are (now) present. The
// common live path — a deploy delivers SetDesiredSubscriptions while the driver is already
// Connected — flows through HERE, so the alarm subscribe must happen on this message, not only
// on Connected entry. A CHANGED set re-subscribes (release-then-subscribe inside
// HandleSubscribeAlarmsAsync): unlike the value path, "a subscription already exists" is NOT
// sufficient, because several drivers filter their feed on the subscribed sourceNodeIds, so a
// widened set that never re-subscribed would silently never deliver the new alarm.
// Still deliberately no unsubscribe-on-EMPTY: a removed alarm tag's condition node is torn down
// on the address-space rebuild and DriverHostActor.ForwardNativeAlarm drops any transition whose
// ConditionId no longer maps, so a lingering session-less alarm subscription can never surface a
// removed alarm.
SubscribeDesiredAlarms();
});
Receive(_ =>
{
if (_deferredLegacyDemand is not { } desired) return;
_deferredLegacyDemand = null;
Self.Tell(desired);
});
ReceiveAsync(HandleSubscribeAlarmsAsync);
Receive(OnDataChangeForward);
Receive(OnDataChangeBatchForward);
// Native alarm transition marshaled onto the actor thread from the driver's OnAlarmEvent;
// project it to the parent the same way DataChangeForward projects AttributeValueBatchPublished.
Receive(m => Context.Parent.Tell(new AttributeAlarmPublished(_driverInstanceId, m.Args)));
// A1 F2: the same mailbox and the same forward, so the signal follows every alarm event raised before it.
// Review S2: a signal raised under an earlier connection (queued across a Connected→Reconnecting→Connected
// bounce, e.g. while an async reconnect held the mailbox) covers events of a feed that no longer exists — drop it.
Receive(m =>
{
if (m.Epoch != Interlocked.Read(ref _connectionEpoch))
{
_log.Debug("DriverInstance {Id}: initial alarm-state signal from an earlier connection — dropped", _driverInstanceId);
return;
}
Context.Parent.Tell(new AlarmInitialStatePublished(_driverInstanceId, m.Args, m.Epoch));
});
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive(msg =>
_log.Debug("DriverInstance {Id}: subscription established ({Count} refs, {Diag})",
_driverInstanceId, msg.ReferenceCount, msg.DiagnosticId));
// Symmetric to the SubscriptionEstablished swallow: a failed self-resubscribe replies SubscriptionFailed
// to Self (HandleSubscribeAsync already logged the underlying cause). Swallow it so it doesn't dead-letter.
Receive(msg =>
_log.Debug("DriverInstance {Id}: resubscribe reported failure: {Reason}", _driverInstanceId, msg.Reason));
Receive(HandleRediscoveryRaised);
Receive(_ => PublishHealthSnapshot());
Receive(_ =>
{
// One GetHealth observation feeds both the snapshot publish and the watchdog — reading it
// twice would let the two disagree about the same tick.
var health = PublishHealthSnapshot();
EvaluateCommsLossWatchdog(health);
ReconcileSubscription();
});
}
///
/// The comms-loss watchdog. Declares a Connected driver disconnected once it has gone
/// without a single successful read while also reporting
/// itself non-Healthy, by self-sending .
///
///
///
/// Why this exists. had no production sender at all. The only
/// ways into Reconnecting were a failed initial connect and an operator's Force
/// Reconnect, so a driver that connected successfully and then lost its device stayed Connected
/// forever: it published Bad for every tag, never re-initialised, and did not recover when the device
/// came back — live-confirmed against a stopped Modbus fixture, which needed a node restart. Both
/// comms-loss quality paths (native conditions, scripted-alarm inputs) hang off
/// , so both were wired to a signal that never fired.
/// This is also OpcUaClientDriver's only recovery path for a lost upstream
/// session (its in-driver SDK reconnect handler was deleted).
///
///
/// Why the trip condition is a conjunction, and NOT simply "non-Healthy for N polls".
/// means connected but some data is bad — the enum says
/// so. Several drivers publish health per-tag inside their read loop (ModbusDriver.ReadAsync
/// writes Healthy or Degraded once per reference), so a single unreadable address leaves the driver
/// Degraded whenever it happens to be the last tag read, indefinitely, against a perfectly healthy
/// device. Tripping on state alone would tear that driver down every watchdog period forever —
/// strictly worse than the bug being fixed.
///
///
/// is the honest liveness evidence: every driver
/// advances it on any successful read and preserves it across Degraded/Faulted writes. One
/// bad tag among good ones keeps it moving; a device that is genuinely gone freezes it. The state
/// check is still required as the second conjunct, because a Healthy driver with nothing subscribed
/// legitimately never reads at all and must not be declared dead for being idle.
///
///
/// Drivers this cannot fire for, by construction. CalculationDriver reports Healthy
/// whenever it is running (it has no transport to be degraded about), so it never trips — correct,
/// since there is nothing to reconnect to. Every other driver in the tree reaches a non-Healthy
/// state on sustained failure: the nine poll drivers via Degraded, MQTT via its live connection
/// state, Galaxy via its reconnect supervisor.
///
///
/// The grace is per CONNECTION (03/S17). The silence baseline is
/// max(LastSuccessfulRead, _connectedSinceUtc), not LastSuccessfulRead ?? _connectedSinceUtc.
/// Because LastSuccessfulRead is preserved across Degraded/Faulted writes (see above),
/// a device that accepts a connection but serves no data reconnects carrying a stamp that is already
/// older than the threshold, so a ?? baseline re-trips on the FIRST health tick of every new
/// connection — a reconnect cycle at health-tick cadence rather than the designed threshold. Taking
/// the later of the two gives each connection its own full window, which is exactly what re-stamping
/// _connectedSinceUtc on every Connected entry was for. Note this paces the cycle, it
/// does not end it: a permanently half-broken device still reconnects once per threshold, and a
/// driver that stops reading within a stable connection still trips on schedule (its read
/// stamp is the later term, exactly as before).
///
///
/// The health observed on this tick, or null when
/// threw — a failed observation is not evidence of comms loss, so it never advances the watchdog.
private void EvaluateCommsLossWatchdog(DriverHealth? health)
{
if (_commsLossTimeout <= TimeSpan.Zero) return;
if (health is not { } observed) return;
if (observed.State == DriverState.Healthy) return;
// Measure silence from the LATER of the last successful read and THIS connect — the grace is per
// connection. `??` was wrong: drivers PRESERVE LastSuccessfulRead across Degraded/Faulted writes (that
// preservation is the watchdog design), so after a trip + reconnect to a device that accepts the connection
// but still serves no data, the stamp is already older than the threshold and the FIRST tick of the new
// connection re-trips — churn at health-tick cadence instead of the designed grace. `??` only ever helped
// a driver that had never read at all.
var lastEvidence = observed.LastSuccessfulRead is { } read && read > _connectedSinceUtc
? read
: _connectedSinceUtc;
var silence = DateTime.UtcNow - lastEvidence;
if (silence < _commsLossTimeout) return;
_log.Warning(
"DriverInstance {Id}: no successful read for {Silence} while reporting {State} ({Error}) — " +
"declaring comms lost and reconnecting",
_driverInstanceId, silence, observed.State, observed.LastError ?? "no error reported");
Self.Tell(new DisconnectObserved(
$"no successful read for {silence.TotalSeconds:F0}s while reporting {observed.State}"));
}
///
/// Periodic desired-vs-actual subscription reconcile, riding the existing health-poll
/// tick. While Connected, a driver that has a desired subscription set but no live handle is
/// re-subscribed.
///
///
///
/// The desired set is otherwise only (re)applied on a Connected transition
/// () or on a deploy's .
/// Nothing re-asserted it for a subscription that was lost while the driver stayed
/// Connected — a failed subscribe whose retry never came, or a handle dropped down an error
/// path. That is the hole this closes.
///
///
/// This is a state-machine consistency check, not a probe. It can only see that this
/// actor holds no handle; it cannot detect a handle that is present but dead server-side,
/// because ISubscriptionHandle is opaque (a DiagnosticId string and nothing
/// else). Detecting that needs a liveness member on ISubscribable implemented across
/// all eight drivers, each with different subscription mechanics — deliberately deferred
/// until a real occurrence shows the handle outliving the subscription.
///
///
/// Gated on : a driver that cannot subscribe at all may still have
/// been handed a desired set, and re-telling Subscribe to it every tick would fail
/// every tick, forever.
///
///
/// A redundant Subscribe is possible but harmless: a tick sitting in the mailbox ahead
/// of an already-queued Subscribe observes the same "no handle" state and tells a
/// second one. is a ReceiveAsync (so no tick can be
/// processed mid-subscribe) and drops any prior subscription before establishing the new one,
/// so the duplicate costs one extra round-trip and converges. Suppressing it would need a
/// pending-subscribe flag threaded through every self-tell site — more state than the race
/// is worth.
///
///
private void ReconcileSubscription()
{
ReconcileAlarmSubscription();
if (_driver is not ISubscribable) return;
if (_desiredRefs.Count == 0 || _subscriptionHandle is not null) return;
_log.Info(
"DriverInstance {Id}: connected with {Count} desired subscription ref(s) but no live subscription handle — re-subscribing (periodic reconcile)",
_driverInstanceId, _desiredRefs.Count);
if (_desiredAcquisition is { } acquisition) Self.Tell(acquisition);
else Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
}
///
/// The native-alarm half of . The data reconcile above never
/// looked at alarms, so an alarm subscribe that failed on (re)connect — e.g. a session not yet ready
/// after an outage — left the feed gated for the life of the connection, with the driver Healthy and
/// its data streaming. Re-asserts both halves the feed needs: the OnAlarmEvent handler
/// (idempotent attach) and a subscription matching the desired set (
/// is a no-op while the live handle already matches). Gated on + a
/// non-empty desired set, so it costs nothing on a driver with no alarm tags.
/// A persistently failing subscribe backs off: after the n-th consecutive failure the reconcile
/// skips 2^(n-1) − 1 ticks, capped at , because a HANGING subscribe
/// holds the mailbox for its full 10 s bound (writes delayed behind it eat into their queue budget). A
/// Connected entry or a deploy's desired-set push still retries immediately — only the timer backs off.
///
private void ReconcileAlarmSubscription()
{
if (_driver is not IAlarmSource || _desiredAlarmRefs.Count == 0) return;
if (_alarmEventHandler is null)
{
// Unreachable while every Connected entry attaches — so if this ever logs, something regressed.
_log.Warning("DriverInstance {Id}: connected with desired alarm refs but no native-alarm handler — re-attaching (periodic reconcile)",
_driverInstanceId);
AttachAlarmSource();
}
if (_alarmRetrySkipTicks > 0)
{
_alarmRetrySkipTicks--;
return;
}
if (AlarmSubscriptionIsStale())
{
_log.Info(
"DriverInstance {Id}: connected with {Count} desired alarm ref(s) but no matching native-alarm subscription — re-subscribing (periodic reconcile)",
_driverInstanceId, _desiredAlarmRefs.Count);
Self.Tell(new SubscribeAlarms());
}
}
private void Reconnecting()
{
// Announce comms loss to the host so it annotates this driver's native alarm conditions Bad
// (a comms-lost driver emits no alarm events, so this is the ONLY signal that the source is unreachable).
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false, ProducerIncarnation: _sourceIncarnation));
// Tear the dead transport down before re-initialising, or every retry leaks one.
Receive(_ => InitializeAsync(_currentConfigJson ?? "{}", teardownFirst: true));
// Fast-fail writes while reconnecting (same reason as Connecting — avoids the 8s host Ask
// timeout on an inbound write to a transiently-down driver). Synchronous Receive.
Receive(_ =>
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
Receive(msg => RejectRich(msg, Sender, "driver not connected"));
Receive(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).
Receive(msg =>
{
_log.Debug("DriverInstance {Id}: alarm ack arrived during reconnect — dropped (driver not connected)", _driverInstanceId);
ReportAckFailed(Sender, msg, "the driver is not connected");
});
Receive(msg =>
{
if (msg.Generation != _initGeneration) return;
CompleteInitAttempt();
Timers.Cancel("retry-connect");
_log.Info("DriverInstance {Id}: reconnected", _driverInstanceId);
Become(Connected);
PublishHealthSnapshot();
ResubscribeDesired();
AttachAlarmSource();
SubscribeDesiredAlarms();
});
// A failure here changes no state — the retry timer keeps trying the current config; only a
// (generation-matched) InitializeSucceeded transitions. It DOES release the single-flight gate, or
// no later tick could ever retry.
Receive(msg =>
{
if (msg.Generation == _initGeneration) CompleteInitAttempt();
});
Receive(StoreDisconnectedDesiredSubscriptions);
Receive(_ => { /* already reconnecting — no-op */ });
Receive(IgnoreConnectionLoss);
// A watchdog DisconnectObserved self-sent on the Connected tick can still be queued when a ConnectionLossRaised
// (or another trip) has already moved us here — already reconnecting, so it is a no-op, not an Unhandled.
Receive(_ => { /* already reconnecting — no-op */ });
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive(msg =>
_log.Debug("DriverInstance {Id}: subscription established ({Count} refs, {Diag})",
_driverInstanceId, msg.ReferenceCount, msg.DiagnosticId));
// Symmetric to the SubscriptionEstablished swallow: a failed self-resubscribe replies SubscriptionFailed
// to Self (HandleSubscribeAsync already logged the underlying cause). Swallow it so it doesn't dead-letter.
Receive(msg =>
_log.Debug("DriverInstance {Id}: resubscribe reported failure: {Reason}", _driverInstanceId, msg.Reason));
// A native alarm transition can race in while still reconnecting (the driver's feed runs on its
// own thread); drop it — the feed re-delivers active alarms once Connected. Trace only.
Receive(_ =>
_log.Debug("DriverInstance {Id}: native alarm arrived during reconnect — dropped (feed re-delivers)", _driverInstanceId));
Receive(_ =>
_log.Debug("DriverInstance {Id}: initial alarm-state signal arrived during reconnect — dropped", _driverInstanceId));
// A SubscribeAlarms self-tell (from Connected) can be overtaken by an already-queued disconnect into
// this state; swallow it so it doesn't dead-letter — the next Connected entry re-subscribes.
Receive(_ => { });
Receive(HandleRediscoveryRaised);
Receive(_ => PublishHealthSnapshot());
Receive(_ => PublishHealthSnapshot());
Timers.StartPeriodicTimer("retry-connect", RetryConnect.Instance, _reconnectInterval);
}
/// The config blob to initialise the driver with.
///
/// When true, is awaited before
/// — the sequence every driver's own ReinitializeAsync uses. Set on the Reconnecting
/// retry path, because several drivers overwrite their transport field in
/// InitializeAsync without disposing the previous one: ModbusDriver assigns
/// _transport = _transportFactory(...) and MqttDriver assigns _connection, both
/// over an . Re-initialising without tearing down therefore leaks one
/// socket (and, for Modbus, a poll engine) per attempt. That was latent while nothing but an
/// operator's Force Reconnect ever re-entered this path; the watchdog makes it automatic and
/// unbounded — a device down for an hour would leak ~360 transports at the 10 s retry interval.
/// Best-effort and never fatal: a driver that throws on shutdown still gets its initialise attempt.
///
private void InitializeAsync(string driverConfigJson, bool teardownFirst = false)
{
_currentConfigJson = driverConfigJson;
if (_initInFlight)
{
// SINGLE-FLIGHT (02/H2). The previous attempt is still inside the driver; starting another would run
// its teardown against the transport that attempt is building. Skip — the next tick after the
// result retries, and a config handed over meanwhile is already stored for it.
_log.Debug("DriverInstance {Id}: initialise attempt {Gen} still in flight; skipping this one",
_driverInstanceId, _initGeneration);
return;
}
_initInFlight = true;
var generation = Interlocked.Increment(ref s_initGenerationSource);
_initGeneration = generation;
var initCts = new CancellationTokenSource();
_initCts = initCts;
var self = Self;
var log = _log;
var driverInstanceId = _driverInstanceId;
var driver = _driver;
var invoker = _invoker;
var shutdownTimeout = _shutdownTimeout;
var initializeTimeout = _initializeTimeout;
_ = Task.Run(async () =>
{
try
{
if (teardownFirst)
{
try
{
// Deliberately UNWRAPPED: teardown is best-effort cleanup of an already-dead
// transport — a shutdown failure must not count toward the Initialize breaker.
// BOUNDED: a teardown wedged on the dead transport must not hold the retry loop
// (and this thread) for longer than the bound; it is abandoned and the init proceeds.
using var teardownCts = new CancellationTokenSource(shutdownTimeout);
await driver.ShutdownAsync(teardownCts.Token).WaitAsync(shutdownTimeout);
}
catch (TimeoutException)
{
log.Warning(
"DriverInstance {Id}: ShutdownAsync did not complete within {Bound} before a reconnect " +
"attempt; abandoning it and initialising anyway", driverInstanceId, shutdownTimeout);
}
catch (Exception ex)
{
log.Warning(ex,
"DriverInstance {Id}: ShutdownAsync threw before a reconnect attempt; " +
"initialising anyway", driverInstanceId);
}
}
// The connect path was the ONE capability call the invoker never saw, so a
// driver that could not connect contributed zero breaker input and the resilience panel
// stayed quiet for a dead endpoint. Keyed on the driver-instance id (init spans the
// whole driver, like a bulk subscribe). The Initialize policy never retries — this
// actor's RetryConnect timer is the retry loop — and its pipeline timeout now bounds a
// hanging connect via the ct the call site must honour. An open breaker fast-fails the
// attempt with BrokenCircuitException, which lands in the catch below exactly like a
// real connect failure: InitializeFailed → keep retrying on the timer. The 15 s break
// window is shorter than two 10 s timer ticks, so recovery costs at most one extra tick.
// The outer token is this attempt's own: PostStop cancels it so a stop/restart does not run its
// shutdown underneath an attempt still inside the driver.
// PESSIMISTIC bound on top of the invoker's token-only timeout: a driver that ignores its token
// would otherwise hold the single-flight gate forever. An overrun is abandoned (the task keeps
// running, its eventual outcome is observed and discarded), reported as a failure so the retry
// loop continues, and its late Tell is dropped by the generation guard anyway.
var attempt = invoker.ExecuteAsync(
DriverCapability.Initialize,
driverInstanceId,
async ct => await driver.InitializeAsync(driverConfigJson, ct),
initCts.Token).AsTask();
try
{
await attempt.WaitAsync(initializeTimeout);
}
catch (TimeoutException)
{
log.Warning(
"DriverInstance {Id}: initialise attempt {Gen} did not complete within {Bound} (the driver ignored " +
"its cancellation token); attempt abandoned, the retry loop continues",
driverInstanceId, generation, initializeTimeout);
try { initCts.Cancel(); } catch (ObjectDisposedException) { }
_ = attempt.ContinueWith(t => _ = t.Exception, TaskContinuationOptions.OnlyOnFaulted);
self.Tell(new InitializeFailed($"initialise did not complete within {initializeTimeout}", generation));
return;
}
self.Tell(new InitializeSucceeded(generation));
}
catch (Exception ex)
{
self.Tell(new InitializeFailed(ex.Message, generation));
}
finally
{
// The CTS outlives an abandoned attempt (it may still be inside the driver); dispose only once
// nothing can cancel it any more — the actor nulls _initCts when it honours the result.
if (!initCts.IsCancellationRequested) initCts.Dispose();
}
});
}
/// Releases the single-flight gate once the in-flight attempt's result has been honoured.
private void CompleteInitAttempt()
{
_initInFlight = false;
_initCts = null;
}
///
/// Launches a write against the driver off the mailbox, or queues it when
/// writes are already inside the driver. Runs on the actor thread; the
/// only actor state it touches is the in-flight count and the queue. The device round-trip itself
/// () replies to the captured sender from the thread pool and then
/// self-sends to free its slot.
///
private void StartOrQueueWrite(WriteAttribute msg, IActorRef replyTo)
{
if (_driver is not IWritable writable)
{
replyTo.Tell(new WriteAttributeResult(false, "Driver does not implement IWritable"));
return;
}
// Monotonic, so a wall-clock step cannot expire (or extend) a queued write.
var issuedAt = msg.IssuedAt ?? _writeClock.GetTimestamp();
if (TryExpireWrite(replyTo, issuedAt)) return;
if (_writesInFlight >= _maxWritesInFlight || _tagsInFlight.Contains(msg.TagId))
{
_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(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(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> task,
TaskCompletionSource 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> task,
TaskCompletionSource 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++;
_tagsInFlight.Add(msg.TagId);
// Everything the task needs is captured HERE, on the actor thread — ResolveHost reads the driver,
// and Self must not be touched off-context.
var self = Self;
var hostKey = ResolveHost(msg.TagId);
var invoker = _invoker;
_ = RunWriteAsync(writable, invoker, hostKey, msg, replyTo, self, _writeTimeout, _writeClock, _incarnation, _log);
}
private static async Task RunWriteAsync(
IWritable writable, IDriverCapabilityInvoker invoker, string hostKey,
WriteAttribute msg, IActorRef replyTo, IActorRef self, TimeSpan writeTimeout, TimeProvider clock,
int incarnation, ILoggingAdapter log)
{
// Off the actor context from here on: the first await yields, and nothing below reads actor state.
await Task.Yield();
var request = new[] { new WriteRequest(msg.TagId, msg.Value) };
// Bound the write so a hung backend can't hold a slot forever — retry stays
// off by default, but a stalled call still needs an answer. The bound is the configured write timeout
// (lmxopcua#774: it used to be a hard-coded 5 s, so a longer configured bound never took effect).
// Disposed below, except when the write is abandoned (the orphan may still be holding the token).
var cts = new CancellationTokenSource(writeTimeout, clock);
var abandoned = false;
try
{
// Route through the resilience invoker (Write pipeline: timeout, per-host breaker). Writes
// default to NON-idempotent (03/S12): a timed-out write may already have committed at the
// device, and replaying a command-shaped write (pulse coil, counter increment, Galaxy
// supervisory write) can duplicate an irreversible field action. The invoker's no-retry arm is
// therefore authoritative regardless of any configured Write retry. Per-tag opt-in to retries via
// WriteIdempotentAttribute is the unshipped forward path (see WriteIdempotentAttribute). The outer
// cts is retained as a hard backstop above the (typically tighter) tier timeout.
// PESSIMISTIC bound a grace after the token-based cap: a driver that ignores its token would otherwise
// hold the slot and the tag forever, piling every later write to that tag up in the queue.
var attempt = invoker.ExecuteWriteAsync(
hostKey,
isIdempotent: false,
async ct => await writable.WriteAsync(request, ct),
cts.Token).AsTask();
IReadOnlyList results;
try
{
results = await attempt.WaitAsync(writeTimeout + WriteAbandonGrace(writeTimeout), clock);
}
catch (TimeoutException)
{
abandoned = true;
log.Warning(
"DriverInstance write of {Tag} did not complete within {Bound} and ignored its cancellation token " +
"for {Grace} more; abandoned — its slot and tag are released, its eventual outcome is discarded",
msg.TagId, writeTimeout, WriteAbandonGrace(writeTimeout));
try { cts.Cancel(); } catch (ObjectDisposedException) { }
_ = attempt.ContinueWith(t => _ = t.Exception, TaskContinuationOptions.OnlyOnFaulted);
replyTo.Tell(new WriteAttributeResult(false,
$"StatusCode=0x800A0000 (BadTimeout: write did not complete within {writeTimeout.TotalMilliseconds:F0} ms)"));
return;
}
if (results is { Count: 1 } && IsGoodStatus(results[0].StatusCode))
{
replyTo.Tell(new WriteAttributeResult(true, null));
return;
}
var status = results is { Count: > 0 } ? results[0].StatusCode : 0xFFFFFFFF;
replyTo.Tell(new WriteAttributeResult(false, $"StatusCode=0x{status:X8}"));
}
catch (OperationCanceledException)
{
replyTo.Tell(new WriteAttributeResult(false, "write timeout"));
}
catch (Exception ex)
{
replyTo.Tell(new WriteAttributeResult(false, ex.Message));
}
finally
{
if (!abandoned) cts.Dispose();
self.Tell(new WriteCompleted(msg.TagId, incarnation));
}
}
/// Frees the write's slot and tag and drains the queue: the oldest entries whose tag is free are
/// launched (in arrival order) while slots remain; entries older than the budget are failed instead. A
/// completion stamped with another incarnation (a write launched before a supervision restart) is ignored —
/// it never held a slot or tag of THIS incarnation.
private void OnWriteCompleted(WriteCompleted msg)
{
if (msg.Incarnation != _incarnation) return;
if (_writesInFlight > 0) _writesInFlight--;
_tagsInFlight.Remove(msg.TagId);
DrainWriteQueue();
}
private void DrainWriteQueue()
{
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
// plus one write (DriverWriteBounds.HostAsk), not an unbounded wait behind a full set of slots.
for (var node = _pendingWrites.First; node is not null;)
{
var next = node.Next;
if (TryExpireWrite(node.Value.ReplyTo, node.Value.IssuedAt)) _pendingWrites.Remove(node);
node = next;
}
while (true)
{
var before = _pendingWrites.Count + _pendingRichWrites.Count;
for (var node = _pendingWrites.First; writable is not null && node is not null && _writesInFlight < _maxWritesInFlight;)
{
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;
}
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;
}
}
///
/// Fails a write that has waited longer than since it was issued (in the
/// mailbox or the queue). Only a write inside the budget may start: the host's Ask covers the budget plus one
/// full write (), so a write started later could still be running
/// when the Ask reports it failed and its node is reverted — and the device could then take a value the
/// client was told failed. BadTimeout, never written.
///
/// True when the write was expired (and answered).
private bool TryExpireWrite(IActorRef replyTo, long issuedAt)
{
var waited = _writeClock.GetElapsedTime(issuedAt);
if (waited <= _queuedWriteBudget) return false;
replyTo.Tell(new WriteAttributeResult(false,
$"StatusCode=0x800A0000 (BadTimeout: queued for {waited.TotalSeconds:F1}s, over the {_queuedWriteBudget.TotalSeconds:F0}s write budget)"));
return true;
}
/// Replies to every queued write with ; called on each exit from
/// Connected. In-flight writes are left to finish — they already hold the device and reply with its
/// real outcome.
private void FailQueuedWrites(string reason)
{
while (_pendingWrites.First is { } node)
{
_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);
}
}
///
/// Forwards an inbound native-condition acknowledge (routed by from a
/// resolved condition NodeId) to the driver's . The driver
/// correlates on (= the authored alarm
/// full-reference); carries the same reference (the
/// driver's ack path keys on ConditionId). Bounded to 5s so a hung backend can't pin this actor.
/// Success sends no reply (the OPC UA Part 9 ack already committed the local condition state). A refusal
/// or failure is logged and, when the message carries a condition NodeId, reported to the sender as an
/// so the host reverts the condition to unacknowledged (lmxopcua#760) —
/// otherwise the node showed Acknowledged for an alarm the upstream system never acknowledged.
///
private async Task HandleAcknowledgeAsync(RouteAlarmAck msg)
{
// Captured before any await: the failure report goes back to whoever routed the ack.
var replyTo = Sender;
if (_driver is not IAlarmSource src)
{
_log.Warning("DriverInstance {Id}: alarm ack dropped — driver does not implement IAlarmSource", _driverInstanceId);
ReportAckFailed(replyTo, msg, "the driver has no alarm source");
return;
}
var request = new[]
{
new AlarmAcknowledgeRequest(
SourceNodeId: msg.ConditionId,
ConditionId: msg.ConditionId,
Comment: msg.Comment,
OperatorUser: msg.OperatorUser,
ApiKeyId: msg.ApiKeyId),
};
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
// Ack is a write-shaped operation — the AlarmAcknowledge tier policy never retries.
await _invoker.ExecuteAsync(
DriverCapability.AlarmAcknowledge,
ResolveHost(msg.ConditionId),
async ct => await src.AcknowledgeAsync(request, ct),
cts.Token);
_log.Info("DriverInstance {Id}: acknowledged native condition {Cond} by {User}",
_driverInstanceId, msg.ConditionId, msg.OperatorUser);
// lmxopcua#869: an upstream may accept an ack without confirming it was applied (Galaxy: the gateway's
// "sent but unconfirmed" OK). The confirmation wait is seconds long, so it runs OFF this mailbox and
// OUTSIDE the resilience pipeline (a wait on an upstream event — it must neither be cut by the
// AlarmAcknowledge capability timeout nor count toward the breaker). Failure reverts like any other.
// Task.Run, not a bare call: this handler is a ReceiveAsync, so TaskScheduler.Current is the actor's
// scheduler; the confirmation must not depend on this actor's context at all — in particular not after
// PostStop, when it still has to report the abandoned ack (pinned by DriverInstanceActorAckConfirmationTests).
if (src is IAlarmAcknowledgeConfirmation confirmer)
{
var stopToken = _ackConfirmCts.Token;
var driverInstanceId = _driverInstanceId;
var log = _log;
_ = Task.Run(() => RunAckConfirmationAsync(confirmer, request, msg, replyTo, stopToken, driverInstanceId, log));
}
}
catch (DriverOperationRefusedException ex)
{
// A deliberate refusal (e.g. no Galaxy ack credential for this session, lmxopcua#749) — a
// configuration verdict, not a backend fault, so no stack trace; the message names the fix.
_log.Warning("DriverInstance {Id}: native-alarm acknowledge of {Cond} by {User} refused — {Reason}",
_driverInstanceId, msg.ConditionId, msg.OperatorUser, ex.Message);
ReportAckFailed(replyTo, msg, ex.Message);
}
catch (Exception ex)
{
_log.Warning(ex, "DriverInstance {Id}: native-alarm acknowledge of {Cond} failed",
_driverInstanceId, msg.ConditionId);
// The exception TYPE only: a backend message is not ours to vouch for (it could echo a credential).
ReportAckFailed(replyTo, msg, $"the upstream acknowledge failed ({ex.GetType().Name})");
}
}
///
/// Backstop over a driver's own confirmation window (lmxopcua#869): the driver bounds the wait itself; this
/// only guarantees a driver that ignores its window cannot hold a confirmation forever.
///
internal static readonly TimeSpan AckConfirmationCeiling = TimeSpan.FromMinutes(3);
///
/// Awaits off the actor context and, when
/// the upstream does not confirm, reports so the host reverts the condition to
/// unacknowledged — the same report an failure makes. Reads no actor
/// state: everything it needs is captured by the caller on the actor thread.
///
private static async Task RunAckConfirmationAsync(
IAlarmAcknowledgeConfirmation confirmer, IReadOnlyList request, RouteAlarmAck msg,
IActorRef replyTo, CancellationToken stopToken, string driverInstanceId, ILoggingAdapter log)
{
try
{
await confirmer.ConfirmAcknowledgedAsync(request, stopToken)
.WaitAsync(AckConfirmationCeiling, stopToken).ConfigureAwait(false);
}
catch (DriverOperationRefusedException ex)
{
// The driver's verdict (e.g. Galaxy: no acknowledged transition inside its window) — it names why.
log.Warning("DriverInstance {Id}: native-alarm acknowledge of {Cond} by {User} was not confirmed upstream — {Reason}",
driverInstanceId, msg.ConditionId, msg.OperatorUser, ex.Message);
ReportAckFailed(replyTo, msg, ex.Message);
}
catch (OperationCanceledException) when (stopToken.IsCancellationRequested)
{
log.Info("DriverInstance {Id}: confirmation of the native-alarm acknowledge of {Cond} abandoned — the driver stopped",
driverInstanceId, msg.ConditionId);
ReportAckFailed(replyTo, msg, "the driver stopped before the upstream confirmed the acknowledge");
}
catch (Exception ex)
{
log.Warning(ex, "DriverInstance {Id}: confirmation of the native-alarm acknowledge of {Cond} failed",
driverInstanceId, msg.ConditionId);
ReportAckFailed(replyTo, msg, $"the upstream acknowledge was not confirmed ({ex.GetType().Name})");
}
}
/// Tells an when the ack names a condition
/// NodeId (lmxopcua#760); a no-op for an ack routed without one.
private static void ReportAckFailed(IActorRef replyTo, RouteAlarmAck msg, string reason)
{
if (string.IsNullOrEmpty(msg.ConditionNodeId) || replyTo.IsNobody()) return;
replyTo.Tell(new AlarmAckFailed(msg.ConditionNodeId, reason, msg.AckSequence));
}
private async Task HandleSubscribeAsync(Subscribe msg)
{
// Capture Sender/Self BEFORE any await. The re-subscribe path below awaits
// UnsubscribeAsync, and a real async backend can resume the continuation off Akka's
// ActorContext — reading raw Sender/Self/Context past that point throws
// NotSupportedException ("no active ActorContext"). Keep ConfigureAwait off the awaits
// in this handler so continuations resume on the actor context.
var replyTo = Sender;
var self = Self;
CancelSourceBindingRetry();
var sourceBindingVersion = _sourceBindingVersion;
if (_driver is not ISubscribable subscribable)
{
replyTo.Tell(new SubscriptionFailed("Driver does not implement ISubscribable"));
return;
}
if (_subscriptionHandle is not null)
{
// Subscribe-twice — drop the prior subscription before establishing the new one.
await UnsubscribeAsync();
}
try
{
// With a source hub, use the driver's acknowledged physical acquisition feed even
// for the ordinary baseline. A change-only event cannot prove that an unchanged
// device value has been read again. This replaces the baseline poller; it does not
// add a second subscription or change the driver's native change notifications.
if (_sourcePublisher is not null && _sourceIncarnation is > 0 && _acquisitionCapacity is not null &&
_driver is IAcknowledgedBaselineAcquisitionSource && msg.FullReferences.Count > 0)
{
if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup)
await cleanup.WaitAsync(_acquisitionTimeout);
var admission = new LegacyAdmission(this, self, stageSources: false);
Volatile.Write(ref _legacyAdmission, admission);
AttachDataChangeHandler(subscribable, self);
AcquisitionDemandApplied? applied = null;
await ApplyAcquisitionDemandAsync(new SetDesiredSubscriptions(msg.FullReferences, msg.PublishingInterval,
DesiredRevision: 1, ProducerIncarnation: _sourceIncarnation.Value, RequireAcquisition: true),
result => applied = result, baseline: true);
if (applied is not { Succeeded: true } || _subscriptionHandle is null)
throw new InvalidOperationException("Baseline acquisition was not acknowledged.");
if (!admission.Finish(_subscriptionHandle))
{
await UnsubscribeAsync();
throw new InvalidOperationException("Legacy initial callback staging capacity exceeded.");
}
replyTo.Tell(new SubscriptionEstablished(_subscriptionHandle.DiagnosticId, msg.FullReferences.Count));
_log.Info("DriverInstance {Id}: subscribed to {Count} refs ({Diag})",
_driverInstanceId, msg.FullReferences.Count, _subscriptionHandle.DiagnosticId);
return;
}
var sourceBindingNeedsRetry = false;
if (_sourcePublisher is not null && _sourceIncarnation is { } incarnation)
{
var count = Math.Min(msg.FullReferences.Count, SourceBindingBatchSize);
for (var i = 0; i < count; i++)
sourceBindingNeedsRetry |= !TryEnsureSourceBinding(msg.FullReferences[i], incarnation);
sourceBindingNeedsRetry |= count < msg.FullReferences.Count;
}
var legacyAdmission = _fenceLegacyHandles ? new LegacyAdmission(this, self) : null;
Volatile.Write(ref _legacyAdmission, legacyAdmission);
AttachDataChangeHandler(subscribable, self);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
// A bulk subscribe spans potentially many hosts, so key the pipeline on the driver
// instance (single-host fallback) rather than any one reference's host.
_subscriptionHandle = await _invoker.ExecuteAsync(
DriverCapability.Subscribe,
_driverInstanceId,
async ct => await subscribable.SubscribeAsync(msg.FullReferences, msg.PublishingInterval, ct),
cts.Token);
if (legacyAdmission is not null && !legacyAdmission.Finish(_subscriptionHandle))
{
await UnsubscribeAsync();
replyTo.Tell(new SubscriptionFailed("Legacy initial callback staging capacity exceeded."));
return;
}
if (sourceBindingNeedsRetry && _sourceIncarnation is { } retryIncarnation)
Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(msg.FullReferences,
0, false, 0, sourceBindingVersion, retryIncarnation), TimeSpan.FromMilliseconds(250));
replyTo.Tell(new SubscriptionEstablished(_subscriptionHandle.DiagnosticId, msg.FullReferences.Count));
_log.Info("DriverInstance {Id}: subscribed to {Count} refs ({Diag})",
_driverInstanceId, msg.FullReferences.Count, _subscriptionHandle.DiagnosticId);
}
catch (Exception ex)
{
DetachDataSubscription();
_log.Warning(ex, "DriverInstance {Id}: subscribe failed", _driverInstanceId);
replyTo.Tell(new SubscriptionFailed(ex.Message));
}
}
private void AttachDataChangeHandler(ISubscribable subscribable, IActorRef self)
{
if (_dataChangeHandler is not null || _batchChangeHandler is not null) return;
// EXACTLY ONE of the two data-change events is subscribed. An IBatchSubscribable driver raises
// OnDataChangeBatch once per production burst AND the per-tag OnDataChange for every item in
// that same burst (the per-tag event is kept for legacy consumers — Galaxy cold reads, driver
// CLIs). Attaching both here would forward every value twice. The batch event is preferred: one
// Tell, one parent hop, one mux pass per burst instead of per tag.
if (subscribable is IBatchSubscribable batchable)
{
_batchChangeHandler = (_, args) =>
{
// A null/empty raise from a buggy driver must never enter the mailbox: an unguarded null
// would throw in the handler, restart the actor, and tear down the driver transport.
if (args?.Items is not { Count: > 0 }) return;
var admission = Volatile.Read(ref _legacyAdmission);
if (admission is not null ? !admission.Admit(args.SubscriptionHandle, args.Items) : !AcceptLegacyHandle(args.SubscriptionHandle)) return;
var owned = new DataChangeItem[args.Items.Count];
for (var i = 0; i < owned.Length; i++)
{
var item = args.Items[i];
if (item is null) { owned[i] = null!; continue; }
if (Volatile.Read(ref _activeAcquisition) is null) PublishSource(item.FullReference, item.Snapshot);
owned[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot));
}
self.Tell(new DataChangeBatchForward(owned, _sourceIncarnation));
};
batchable.OnDataChangeBatch += _batchChangeHandler;
}
else
{
_dataChangeHandler = (_, args) =>
{
if (args is null)
{
self.Tell(new DataChangeForward(string.Empty, null!, _sourceIncarnation));
return;
}
var admission = Volatile.Read(ref _legacyAdmission);
if (admission is not null ? !admission.Admit(args.SubscriptionHandle,
[new DataChangeItem(args.FullReference, args.Snapshot)]) : !AcceptLegacyHandle(args.SubscriptionHandle)) return;
if (Volatile.Read(ref _activeAcquisition) is null) PublishSource(args.FullReference, args.Snapshot);
self.Tell(new DataChangeForward(args.FullReference, CopyLegacySnapshot(args.Snapshot), _sourceIncarnation));
};
subscribable.OnDataChange += _dataChangeHandler;
}
}
private bool AcceptLegacyHandle(ISubscriptionHandle handle)
{
var current = Volatile.Read(ref _subscriptionHandle);
if (Volatile.Read(ref _fenceLegacyHandles)) return current is not null && ReferenceEquals(current, handle);
return Volatile.Read(ref _acquisitionPending) == 0 && Volatile.Read(ref _activeAcquisition) is null ||
current is not null && ReferenceEquals(current, handle);
}
// The legacy API permits callbacks before SubscribeAsync returns its handle. Stage those
// callbacks under a bounded generation gate, then accept only the returned handle. Source
// reservations capture their own monotonic ingress time at callback time; SDK delivery does
// not depend on source-hub admission.
private sealed class LegacyAdmission(DriverInstanceActor owner, IActorRef self, bool stageSources = true) : IDisposable
{
private const int MaxItems = 4096;
private const long MaxBytes = 16 * 1024 * 1024;
private readonly object _gate = new();
private readonly List _events = new();
private ISubscriptionHandle? _handle;
private long _bytes;
private int _items, _failed;
private int _closed;
private sealed record StagedEvent(ISubscriptionHandle Handle, DataChangeItem[] Items, StagedSource?[] Sources);
internal sealed record StagedSource(SourceSamplePublisher.StagedSourceSample? Sample, SourceTicket Ticket, uint? Status);
// True means the caller may deliver directly; false means staged or rejected.
internal bool Admit(ISubscriptionHandle handle, IReadOnlyList items)
{
var installed = Volatile.Read(ref _handle);
if (installed is not null) return Volatile.Read(ref _closed) == 0 && ReferenceEquals(handle, installed);
if (!Monitor.TryEnter(_gate))
{
Interlocked.Exchange(ref _failed, 1);
owner.InvalidateLegacySources(items);
return false;
}
try
{
if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _failed) != 0) return false;
if (_handle is not null) return ReferenceEquals(handle, _handle);
if (items.Count == 0 || items.Count > MaxItems - _items)
{ Interlocked.Exchange(ref _failed, 1); owner.InvalidateLegacySources(items); return false; }
var copied = new DataChangeItem[items.Count];
var sources = new StagedSource?[items.Count];
long bytes = 0;
try
{
for (var i = 0; i < items.Count; i++)
{
var item = items[i];
if (item?.Snapshot is null) throw new ArgumentException("Malformed legacy callback.");
bytes = checked(bytes + OwnedDataSample.Estimate(item.Snapshot.Value) + 2L * item.FullReference.Length);
if (bytes > MaxBytes - _bytes) throw new ArgumentException("Legacy initial callback budget exceeded.");
copied[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot));
if (stageSources) sources[i] = owner.StageLegacySource(item);
}
_items += items.Count; _bytes += bytes;
_events.Add(new StagedEvent(handle, copied, sources));
}
catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException)
{
foreach (var source in sources) source?.Sample?.Dispose();
Interlocked.Exchange(ref _failed, 1);
owner.InvalidateLegacySources(items);
}
return false;
}
finally { Monitor.Exit(_gate); }
}
internal bool Finish(ISubscriptionHandle handle)
{
lock (_gate)
{
if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _failed) != 0)
{ DisposeEvents(); Volatile.Write(ref _closed, 1); return false; }
foreach (var staged in _events)
{
if (ReferenceEquals(staged.Handle, handle))
{
foreach (var source in staged.Sources)
{
if (source?.Sample is { } sample) sample.Commit();
else if (source?.Status is { } status) owner._sourcePublisher?.TryPublishAcquisitionStatus(source.Ticket, status);
}
self.Tell(new DataChangeBatchForward(staged.Items, owner._sourceIncarnation));
}
else foreach (var source in staged.Sources) source?.Sample?.Dispose();
}
_events.Clear(); _items = 0; _bytes = 0;
if (Volatile.Read(ref _failed) == 0) { Volatile.Write(ref _handle, handle); return true; }
Volatile.Write(ref _closed, 1);
return false;
}
}
private void DisposeEvents()
{
foreach (var entry in _events) foreach (var source in entry.Sources) source?.Sample?.Dispose();
_events.Clear();
}
public void Dispose() { lock (_gate) { Volatile.Write(ref _closed, 1); DisposeEvents(); } }
internal static StagedSource? Stage(SourceSamplePublisher publisher, SourceTicket ticket, DataValueSnapshot snapshot)
{
if (snapshot.Value is null && !OpcUaStatus.IsGood(snapshot.StatusCode)) return new(null, ticket, snapshot.StatusCode);
return publisher.TryStage(ticket, snapshot, out var sample) ? new(sample, ticket, null) : null;
}
}
private LegacyAdmission.StagedSource? StageLegacySource(DataChangeItem item)
{
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation) return null;
if (!_sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out var ticket) &&
(!TryEnsureSourceBinding(item.FullReference, incarnation) ||
!_sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out ticket))) return null;
return LegacyAdmission.Stage(_sourcePublisher, ticket, item.Snapshot);
}
private void InvalidateLegacySources(IReadOnlyList items)
{
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation) return;
foreach (var item in items)
if (item is not null && _sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out var ticket))
_sourcePublisher.Invalidate(ticket, "legacy callback staging overflow");
}
private sealed class SharedAcquisitionReservation(IDisposable reservation)
{
private readonly IDisposable _reservation = reservation;
private int _references = 1;
private int _uncertain;
internal bool IsUncertain => Volatile.Read(ref _uncertain) != 0;
internal void MarkUncertain() => Interlocked.Exchange(ref _uncertain, 1);
internal IDisposable Retain()
{
if (Interlocked.Increment(ref _references) <= 1) throw new InvalidOperationException("Reservation already released.");
return new Reference(this);
}
internal IDisposable InitialReference() => new Reference(this);
private sealed class Reference(SharedAcquisitionReservation owner) : IDisposable
{
private SharedAcquisitionReservation? _owner = owner;
public void Dispose()
{
var current = Interlocked.Exchange(ref _owner, null);
if (current is not null && Interlocked.Decrement(ref current._references) == 0) current._reservation.Dispose();
}
}
}
// Owns the backend task independently of the actor. Admission remains pinned across actor
// death and until an abandoned operation's eventual handle has actually been released.
private sealed class PendingAcquisition(IDisposable reservation, ISubscribable subscribable, SharedAcquisitionReservation shared)
{
private readonly object _gate = new();
private readonly CancellationTokenSource _stop = new();
private readonly TaskCompletionSource _completion =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource _finished = new(TaskCreationOptions.RunContinuationsAsynchronously);
private AcquisitionSubscriptionResult? _result;
private bool _abandoned, _settled;
internal Task Completion => _completion.Task;
internal Task Finished => _finished.Task;
internal void CancelBeforeStart()
{
lock (_gate) _settled = true;
reservation.Dispose();
_stop.Dispose();
_finished.TrySetResult(true);
}
internal void Start(IAcknowledgedAcquisitionSource source, AcquisitionSubscriptionRequest request,
Action callback) => _ = ObserveAsync(Task.Run(() =>
source.SubscribeAcquisitionAsync(request, callback, _stop.Token)));
private async Task ObserveAsync(Task operation)
{
try
{
var result = await operation.ConfigureAwait(false) ?? throw new InvalidOperationException("Acquisition returned no acknowledgment.");
var clean = false;
lock (_gate)
{
if (_abandoned) { _settled = true; clean = true; }
else { _result = result; _completion.TrySetResult(result); }
}
if (clean) await CleanupAsync(result).ConfigureAwait(false);
}
catch (Exception ex)
{
lock (_gate) { _settled = true; _completion.TrySetException(ex); }
reservation.Dispose();
_stop.Dispose();
_finished.TrySetResult(true);
}
}
internal bool TryAdopt(AcquisitionSubscriptionResult result)
{
lock (_gate)
{
if (_abandoned || _settled || !ReferenceEquals(_result, result)) return false;
_settled = true;
}
reservation.Dispose();
_stop.Dispose();
_finished.TrySetResult(true);
return true;
}
internal void Abandon()
{
AcquisitionSubscriptionResult? clean = null;
lock (_gate)
{
if (_settled || _abandoned) return;
_abandoned = true;
if (_result is not null) { _settled = true; clean = _result; }
}
try { _stop.Cancel(); } catch (Exception) { }
if (clean is not null) _ = CleanupAsync(clean);
}
private async Task CleanupAsync(AcquisitionSubscriptionResult result)
{
try
{
if (result.Handle is not null)
await ((IDriverCapabilityInvoker)NullDriverCapabilityInvoker.Instance).ExecuteAsync(DriverCapability.Subscribe, "acquisition-cleanup",
async ct => await subscribable.UnsubscribeAsync(result.Handle, ct), CancellationToken.None).ConfigureAwait(false);
reservation.Dispose();
_finished.TrySetResult(true);
}
catch (Exception) { shared.MarkUncertain(); _finished.TrySetResult(false); /* retain reservation */ }
finally { _stop.Dispose(); }
}
}
private async Task ApplyAcquisitionDemandAsync(SetDesiredSubscriptions desired,
Action reply, bool baseline = false)
{
var failed = new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, TimeSpan.Zero, false);
if (_abandonedAcquisition is { } abandoned)
{
if (!abandoned.Finished.IsCompleted)
{
reply(failed with { Busy = true, RetryWhenReady = abandoned.Finished });
return;
}
if (!abandoned.Finished.IsCompletedSuccessfully || !abandoned.Finished.Result)
{
reply(failed);
return;
}
_abandonedAcquisition = null;
}
if (!baseline && _desiredAcquisition is { } current && _subscriptionHandle is not null &&
Volatile.Read(ref _activeAcquisition) is not null && current.DesiredRevision == desired.DesiredRevision &&
current.ProducerIncarnation == desired.ProducerIncarnation && current.PublishingInterval == desired.PublishingInterval &&
current.FullReferences.SequenceEqual(desired.FullReferences, StringComparer.Ordinal))
{
StoreDesiredSubscriptions(desired);
SubscribeDesiredAlarms();
reply(new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, _acquisitionNominal, true));
return;
}
if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup)
{
reply(failed with { Busy = true, RetryWhenReady = cleanup });
return;
}
if (_driver is not IAcknowledgedAcquisitionSource source || _driver is not ISubscribable subscribable ||
desired.DesiredRevision <= 0 || desired.ProducerIncarnation <= 0 ||
_sourceIncarnation != desired.ProducerIncarnation || desired.FullReferences.Count == 0 ||
_acquisitionCapacity is null || _activeCapacity?.IsUncertain == true || _previousAcquisitionCleanup is { IsCompleted: false } ||
_previousAcquisitionCleanup is { IsCompletedSuccessfully: true, Result: false })
{
reply(failed);
return;
}
var shared = _activeCapacity;
IDisposable operationReference;
if (shared is null)
{
var reservation = _acquisitionCapacity.TryAcquire(_clusterId, _driverInstanceId, out var ready);
if (reservation is null)
{
reply(ready is null ? failed : failed with { Busy = true, RetryWhenReady = ready });
return;
}
shared = new SharedAcquisitionReservation(reservation);
operationReference = shared.InitialReference();
}
else operationReference = shared.Retain();
var hadHandler = _dataChangeHandler is not null || _batchChangeHandler is not null;
var previousHandle = _subscriptionHandle;
var fence = new AcquisitionFence(desired.DesiredRevision, desired.ProducerIncarnation);
var permittedReferences = new HashSet(desired.FullReferences, StringComparer.Ordinal);
using var cts = new CancellationTokenSource(_acquisitionTimeout, _acquisitionClock);
var operation = new PendingAcquisition(operationReference, subscribable, shared);
_pendingAcquisition = operation;
Volatile.Write(ref _acquisitionPending, 1);
var started = false;
try
{
AttachDataChangeHandler(subscribable, Self);
CancelSourceBindingRetry();
var sourceBindingVersion = _sourceBindingVersion;
var sourceBindingNeedsRetry = false;
if (_sourcePublisher is not null)
{
var count = Math.Min(desired.FullReferences.Count, SourceBindingBatchSize);
for (var i = 0; i < count; i++)
sourceBindingNeedsRetry |= !TryEnsureSourceBinding(desired.FullReferences[i], fence.Producer);
sourceBindingNeedsRetry |= count < desired.FullReferences.Count;
}
operation.Start(source, new AcquisitionSubscriptionRequest(desired.FullReferences,
desired.PublishingInterval, fence.Revision, fence.Producer), batch =>
{
if (!ReferenceEquals(Volatile.Read(ref _activeAcquisition), fence) || batch is null ||
batch.DesiredRevision != fence.Revision || batch.ProducerIncarnation != fence.Producer) return;
foreach (var item in batch.Items)
{
if (!ReferenceEquals(Volatile.Read(ref _activeAcquisition), fence)) return;
if (item is not null && permittedReferences.Contains(item.FullReference) && _sourcePublisher is not null &&
_sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, fence.Producer, out var ticket))
{
if (item.Snapshot.Value is null && !OpcUaStatus.IsGood(item.Snapshot.StatusCode))
_sourcePublisher.TryPublishAcquisitionStatus(ticket, item.Snapshot.StatusCode);
else _sourcePublisher.TryPublish(ticket, item.Snapshot);
}
}
});
started = true;
var installed = await operation.Completion.WaitAsync(cts.Token);
if (installed.Handle is null || installed.DesiredRevision != fence.Revision ||
installed.ProducerIncarnation != fence.Producer || installed.NominalSamplingInterval <= TimeSpan.Zero)
{
operation.Abandon();
_abandonedAcquisition = operation;
if (!hadHandler) DetachDataSubscription();
reply(failed);
return;
}
var activeReference = _activeCapacityReference is null ? shared.Retain() : null;
if (!operation.TryAdopt(installed))
{
activeReference?.Dispose();
reply(failed);
return;
}
if (activeReference is not null) { _activeCapacity = shared; _activeCapacityReference = activeReference; }
_subscriptionHandle = installed.Handle;
Volatile.Write(ref _fenceLegacyHandles, true);
if (!baseline) Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose();
Volatile.Write(ref _activeAcquisition, fence);
Volatile.Write(ref _acquisitionPending, 0);
if (!baseline)
{
StoreDesiredSubscriptions(desired);
_desiredAcquisition = desired;
}
_acquisitionNominal = installed.NominalSamplingInterval;
if (sourceBindingNeedsRetry)
Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(desired.FullReferences,
0, false, 0, sourceBindingVersion, fence.Producer), TimeSpan.FromMilliseconds(250));
if (!baseline) SubscribeDesiredAlarms();
if (previousHandle is not null && !ReferenceEquals(previousHandle, installed.Handle))
_previousAcquisitionCleanup = CleanupAcquiredHandleAsync(subscribable, previousHandle, shared.Retain(), shared);
reply(new AcquisitionDemandApplied(fence.Revision, fence.Producer, installed.NominalSamplingInterval, true));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (started) { operation.Abandon(); _abandonedAcquisition = operation; }
else operation.CancelBeforeStart();
if (!hadHandler) DetachDataSubscription();
_log.Warning(ex, "DriverInstance {Id}: acquisition demand failed", _driverInstanceId);
reply(failed);
}
finally { _pendingAcquisition = null; Volatile.Write(ref _acquisitionPending, 0); }
}
private static async Task CleanupAcquiredHandleAsync(ISubscribable subscribable, ISubscriptionHandle handle,
IDisposable reservation, SharedAcquisitionReservation shared)
{
try
{
await ((IDriverCapabilityInvoker)NullDriverCapabilityInvoker.Instance).ExecuteAsync(DriverCapability.Subscribe, "acquisition-cleanup",
async ct => await subscribable.UnsubscribeAsync(handle, ct), CancellationToken.None).ConfigureAwait(false);
reservation.Dispose();
return true;
}
catch (Exception) { shared.MarkUncertain(); return false; } // retain capacity after an uncertain release
}
private void CancelSourceBindingRetry()
{
Timers.Cancel("source-binding-retry");
_sourceBindingVersion++;
}
private bool TryEnsureSourceBinding(string reference, long incarnation)
{
try { return _sourcePublisher?.EnsureDriverBinding(_clusterId, _driverInstanceId, reference, incarnation) == true; }
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Warning(ex, "DriverInstance {Id}: source binding unavailable; legacy subscription remains active", _driverInstanceId);
return false;
}
}
private void RetrySourceBindingBatch(RetrySourceBindings retry)
{
if (retry.Version != _sourceBindingVersion || _sourceIncarnation != retry.ProducerIncarnation || _subscriptionHandle is null)
return;
var end = Math.Min(retry.References.Count, retry.Offset + SourceBindingBatchSize);
var failed = retry.Failed;
for (var i = retry.Offset; i < end; i++)
failed |= !TryEnsureSourceBinding(retry.References[i], retry.ProducerIncarnation);
if (end < retry.References.Count)
{
Timers.StartSingleTimer("source-binding-retry", retry with { Offset = end, Failed = failed }, TimeSpan.FromMilliseconds(1));
return;
}
if (failed)
{
var attempt = Math.Min(retry.Attempt + 1, 7);
var delayMs = Math.Min(30_000, 250 * (1 << attempt));
Timers.StartSingleTimer("source-binding-retry", retry with { Offset = 0, Failed = false, Attempt = attempt },
TimeSpan.FromMilliseconds(delayMs));
}
}
private async Task UnsubscribeAsync()
{
if (RetireAcquisitionHandle())
{
DetachDataSubscription();
return;
}
if (_driver is not ISubscribable subscribable || _subscriptionHandle is null)
{
DetachDataSubscription();
return;
}
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var handle = _subscriptionHandle; // non-null per the guard above; capture before the async lambda
await _invoker.ExecuteAsync(
DriverCapability.Subscribe,
_driverInstanceId,
async ct => await subscribable.UnsubscribeAsync(handle, ct),
cts.Token);
}
catch (Exception ex)
{
_log.Warning(ex, "DriverInstance {Id}: unsubscribe threw (continuing)", _driverInstanceId);
}
finally
{
DetachDataSubscription();
}
}
/// Tear down the data-change (per-tag AND batch) + native-alarm event handlers + null both handles.
/// Called on PostStop and on Connected → Reconnecting transitions so a stale handler doesn't push
/// data-change / alarm events to an actor that has lost its driver connection.
/// Not for the data Unsubscribe / re-subscribe path — that uses
/// instead.
private void DetachSubscription()
{
CancelSourceBindingRetry();
RetireAcquisitionHandle();
Volatile.Write(ref _activeAcquisition, null);
DetachDataSubscription();
DetachAlarmSource();
}
private bool RetireAcquisitionHandle()
{
var capacityReference = _activeCapacityReference;
var shared = _activeCapacity;
if (capacityReference is null || shared is null) return false;
_activeCapacityReference = null;
_activeCapacity = null;
var handle = _subscriptionHandle;
_subscriptionHandle = null;
Volatile.Write(ref _activeAcquisition, null);
if (handle is not null && _driver is ISubscribable subscribable)
_previousAcquisitionCleanup = CleanupAcquiredHandleAsync(subscribable, handle, capacityReference, shared);
else capacityReference.Dispose();
return true;
}
/// Tear down the data-change (per-tag AND batch) handlers + null the data handle, leaving the
/// native-alarm handler and handle alone.
/// The data Unsubscribe / re-subscribe path used to run the full ,
/// so every deploy that re-subscribed a Connected driver's DATA also unhooked OnAlarmEvent and
/// forgot the alarm handle — the alarm subscription still logged "established" but its events reached
/// nobody until a reconnect or respawn. The two subscriptions are independent at the driver; only a lost
/// connection ends both.
/// Both data-change fields are cleared unconditionally even though only one is ever attached — the
/// IDriver object outlives the actor when the host respawns a child around it, so a handler left on the
/// driver's event would keep Telling a dead actor.
private void DetachDataSubscription()
{
Volatile.Write(ref _activeAcquisition, null);
Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose();
if (_driver is ISubscribable subscribable && _dataChangeHandler is not null)
{
subscribable.OnDataChange -= _dataChangeHandler;
}
_dataChangeHandler = null;
if (_driver is IBatchSubscribable batchable && _batchChangeHandler is not null)
{
batchable.OnDataChangeBatch -= _batchChangeHandler;
}
_batchChangeHandler = null;
_subscriptionHandle = null;
}
/// Subscribe the driver's native alarm event (if it is an ),
/// marshaling each transition to the actor thread. Idempotent; mirrors the OnDataChange attach.
private void AttachAlarmSource()
{
if (_driver is not IAlarmSource src || _alarmEventHandler is not null) return;
var self = Self;
_alarmEventHandler = (_, e) => self.Tell(new NativeAlarmRaised(e));
src.OnAlarmEvent += _alarmEventHandler;
if (_driver is IAlarmInitialStateSignal signal)
{
_alarmInitialStateHandler = (_, e) => self.Tell(new NativeAlarmInitialState(e, Interlocked.Read(ref _connectionEpoch)));
signal.InitialAlarmStateDelivered += _alarmInitialStateHandler;
}
}
/// Subscribe the driver's (if it is one),
/// marshaling each raise to the actor thread. Idempotent; mirrors .
/// Attached once in PreStart rather than per-connect, because the interesting raises
/// (a Galaxy redeploy, a TwinCAT symbol-version bump) can happen while the driver is between
/// connects, and the event carries no connection affinity.
private void AttachRediscoverySource()
{
if (_driver is not IRediscoverable src || _rediscoveryHandler is not null) return;
var self = Self;
_rediscoveryHandler = (_, e) => self.Tell(new RediscoveryRaised(e));
src.OnRediscoveryNeeded += _rediscoveryHandler;
}
/// Symmetric teardown, called from PostStop. Load-bearing: the instance
/// can OUTLIVE this actor (the host respawns a child around the same driver object), so a missing
/// unsubscribe would accumulate one handler per respawn, each holding a dead Self.
private void DetachRediscoverySource()
{
if (_driver is IRediscoverable src && _rediscoveryHandler is not null)
src.OnRediscoveryNeeded -= _rediscoveryHandler;
_rediscoveryHandler = null;
}
///
/// Subscribe the driver's , if it is one,
/// marshalling each raise to the actor thread — actor state is never touched on the driver's thread. Attached
/// once in PreStart and detached in PostStop, like : the
/// instance can outlive this actor, so a per-connect attach would leak a handler (holding
/// a dead Self) per respawn.
///
private void AttachConnectionLossSource()
{
if (_driver is not IDriverConnectionLossSource src || _connectionLossHandler is not null) return;
var self = Self;
_connectionLossHandler = (_, e) => self.Tell(new ConnectionLossRaised(e));
src.ConnectionLost += _connectionLossHandler;
}
/// Symmetric teardown, called from PostStop — same leak argument as .
private void DetachConnectionLossSource()
{
if (_driver is IDriverConnectionLossSource src && _connectionLossHandler is not null)
src.ConnectionLost -= _connectionLossHandler;
_connectionLossHandler = null;
}
///
/// A connection loss reported while NOT Connected: a (re)initialise is already pending or running, so
/// there is nothing to tear down — and acting on it could tear down the connection that attempt is building.
///
private void IgnoreConnectionLoss(ConnectionLossRaised msg) =>
_log.Debug("DriverInstance {Id}: driver reported connection lost ({Reason}) while not connected — ignored",
_driverInstanceId, msg.Args.Reason);
///
/// Connected → Reconnecting on an observed disconnect — from the watchdog or a driver's definitive
/// .
///
private void HandleDisconnectObserved(string reason)
{
_log.Warning("DriverInstance {Id}: disconnect observed ({Reason}); reconnecting", _driverInstanceId, reason);
DetachSubscription();
FailQueuedWrites("driver not connected");
RecordFault();
Become(Reconnecting);
PublishHealthSnapshot();
}
/// Subscribe the driver's (if it is
/// one), marshaling each transition to the actor thread. Idempotent; mirrors
/// , including the PreStart-not-per-connect placement — a probe
/// loop can report a host down while the driver itself is between connects.
private void AttachHostStatusSource()
{
if (_driver is not IHostConnectivityProbe src || _hostStatusHandler is not null) return;
var self = Self;
_hostStatusHandler = (_, _) => self.Tell(new HostStatusRaised());
src.OnHostStatusChanged += _hostStatusHandler;
}
/// Symmetric teardown, called from PostStop — same leak argument as
/// .
private void DetachHostStatusSource()
{
if (_driver is IHostConnectivityProbe src && _hostStatusHandler is not null)
src.OnHostStatusChanged -= _hostStatusHandler;
_hostStatusHandler = null;
}
/// Current per-host connectivity, or null when the driver is not an
/// . Pulled fresh rather than cached: the driver owns the host set,
/// and a stale local copy would be a second source of truth to keep in sync.
/// GetHostStatuses() is called UNGUARDED (not through ) on purpose —
/// it is a pure in-memory snapshot with no I/O, which is exactly why
/// UnwrappedCapabilityCallAnalyzer exempts it. A driver that makes it do I/O breaks that
/// contract; the try/catch below keeps a misbehaving one from killing the health publish.
private IReadOnlyList? CurrentHostStatuses()
{
if (_driver is not IHostConnectivityProbe probe) return null;
try
{
return probe.GetHostStatuses();
}
catch (Exception ex)
{
_log.Warning(ex, "DriverInstance {Id}: GetHostStatuses threw during health publish; omitting host detail", _driverInstanceId);
return null;
}
}
/// What the driver skipped when it last built its tag table, or null when it is not an
/// . Pulled fresh for the same reason as
/// — the driver owns the answer, and a cached copy here would be a
/// second source of truth to keep in sync across every reinitialise.
/// Called UNGUARDED (not through ): the contract is a pure in-memory
/// snapshot with no I/O. The try/catch keeps a misbehaving implementation from taking down the health
/// publish — losing the skip detail is strictly better than losing the whole snapshot.
private SkippedTagReport? CurrentSkippedTags()
{
if (_driver is not ISkippedTagReporter reporter) return null;
try
{
return reporter.GetSkippedTags();
}
catch (Exception ex)
{
_log.Warning(ex, "DriverInstance {Id}: GetSkippedTags threw during health publish; omitting skip detail", _driverInstanceId);
return null;
}
}
/// Bounded driver diagnostics, or null when the driver is not an
/// implementation. Pulled fresh and called UNGUARDED for the same reasons as
/// ; a throwing implementation loses only the diagnostics.
private IReadOnlyDictionary? CurrentDiagnostics()
{
if (_driver is not IDriverDiagnostics diag) return null;
try
{
return DriverDiagnostics.Bound(diag.GetDiagnostics());
}
catch (Exception ex)
{
_log.Warning(ex, "DriverInstance {Id}: GetDiagnostics threw during health publish; omitting diagnostics", _driverInstanceId);
return null;
}
}
/// Value digest of the diagnostics bag for the publish fingerprint. Null in, null out. The bag is
/// already in ordinal key order (), so equal facts digest equally.
private static string? DiagnosticsDigest(IReadOnlyDictionary? d) =>
d is null ? null : string.Join('|', d.Select(kv => $"{kv.Key}={kv.Value}"));
/// Records the driver's rediscovery raise and re-publishes health so the signal reaches the
/// AdminUI promptly rather than waiting for the next 30 s heartbeat.
/// Advisory only. The served address space is deliberately NOT rebuilt: v3 authors raw tags
/// explicitly through the /raw browse-commit flow, so a runtime graft would create nodes no
/// operator approved and that no deployment artifact records. This prompts a human to re-browse.
private void HandleRediscoveryRaised(RediscoveryRaised msg)
{
_rediscoveryNeededUtc = DateTime.UtcNow;
_rediscoveryReason = msg.Args.Reason;
_log.Info(
"DriverInstance {Id}: driver reports its tag set may have changed ({Reason}) — surfaced for operator re-browse; the served address space is unchanged",
_driverInstanceId, msg.Args.Reason);
PublishHealthSnapshot();
}
/// Symmetric teardown — called from and PostStop so a stale
/// handler never pushes to a disconnected actor.
private void DetachAlarmSource()
{
if (_driver is IAlarmSource src && _alarmEventHandler is not null)
src.OnAlarmEvent -= _alarmEventHandler;
_alarmEventHandler = null;
if (_driver is IAlarmInitialStateSignal signal && _alarmInitialStateHandler is not null)
signal.InitialAlarmStateDelivered -= _alarmInitialStateHandler;
_alarmInitialStateHandler = null;
// Drop our handle so the next Connected entry re-subscribes; the desired alarm refs persist across
// reconnects. NOTE: this does NOT tear down the driver-side subscription. For a session-bound
// IAlarmSource the old subscription dies with the session (no accumulation). For a session-less feed
// (GalaxyDriver's always-on central monitor) it survives an in-place reconnect, so the re-subscribe
// is additive — but the driver now collapses to a single live handle on each SubscribeAlarmsAsync
// (GalaxyDriver.SubscribeAlarmsAsync clears the set before adding), so handles no longer accumulate
// across reconnects. The gate (Count > 0) and the one-shot fan-out are unchanged.
_alarmSubscriptionHandle = null;
_subscribedAlarmRefs = Array.Empty();
_alarmSubscribeFailures = 0;
_alarmRetrySkipTicks = 0;
}
/// Establish the native-alarm subscription that un-gates an driver's
/// feed — the driver suppresses until at least one alarm
/// subscription exists. Self-sends the async the Connected behaviour
/// handles. Idempotent: a no-op unless the driver is an , alarm refs are
/// desired, and no subscription is yet established.
private void SubscribeDesiredAlarms()
{
if (_driver is IAlarmSource && _desiredAlarmRefs.Count > 0 && AlarmSubscriptionIsStale())
Self.Tell(new SubscribeAlarms());
}
/// True when the desired alarm refs are not the ones the live handle was established with —
/// either because there is no handle yet, or because a deploy changed the set. The second case is the
/// one a bare "handle is null" check misses; see .
private bool AlarmSubscriptionIsStale() =>
_alarmSubscriptionHandle is null ||
!_subscribedAlarmRefs.SequenceEqual(_desiredAlarmRefs, StringComparer.Ordinal);
/// Calls the driver's (bounded) to register the
/// alarm subscription that un-gates its native feed, caching the returned handle. Re-checks the guard
/// (the desired set may have cleared, or another SubscribeAlarms may have already established a handle,
/// while this was queued). Failures are logged and retried on the next Connected entry or health-poll reconcile tick — the feed
/// stays gated until then.
private async Task HandleSubscribeAlarmsAsync(SubscribeAlarms _)
{
if (_driver is not IAlarmSource src || _desiredAlarmRefs.Count == 0 || !AlarmSubscriptionIsStale())
return;
var refs = _desiredAlarmRefs;
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
// A handle held against a DIFFERENT set must be released before re-subscribing, or a
// sourceNodeIds-filtering driver accumulates two overlapping subscriptions. Best-effort and
// deliberately non-fatal: the re-subscribe below is what actually matters, and a driver whose
// unsubscribe throws must not be left on the stale set because of it. Cleared FIRST so a throw
// cannot leave a handle that the staleness check would keep treating as live.
if (_alarmSubscriptionHandle is { } stale)
{
_alarmSubscriptionHandle = null;
_subscribedAlarmRefs = Array.Empty();
try
{
await _invoker.ExecuteAsync(
DriverCapability.AlarmSubscribe,
_driverInstanceId,
async ct => await src.UnsubscribeAlarmsAsync(stale, ct),
cts.Token);
}
catch (Exception ex)
{
_log.Warning(ex,
"DriverInstance {Id}: releasing the previous native-alarm subscription ({Diag}) threw; re-subscribing anyway",
_driverInstanceId, stale.DiagnosticId);
}
}
try
{
_alarmSubscriptionHandle = await _invoker.ExecuteAsync(
DriverCapability.AlarmSubscribe,
_driverInstanceId,
async ct => await src.SubscribeAlarmsAsync(refs, ct),
cts.Token);
_subscribedAlarmRefs = refs;
_log.Info("DriverInstance {Id}: native-alarm subscription established for {Count} alarm ref(s) ({Diag}){After}",
_driverInstanceId, refs.Count, _alarmSubscriptionHandle.DiagnosticId,
_alarmSubscribeFailures > 0 ? $" after {_alarmSubscribeFailures} failed attempt(s)" : "");
_alarmSubscribeFailures = 0;
_alarmRetrySkipTicks = 0;
}
catch (Exception ex)
{
_alarmSubscribeFailures++;
_alarmRetrySkipTicks = Math.Min((1 << Math.Min(_alarmSubscribeFailures - 1, 30)) - 1, MaxAlarmRetrySkipTicks);
// The stack once per failure streak; the retries that follow repeat the same cause, so they log
// just the message rather than a full trace every tick for the length of an outage.
if (_alarmSubscribeFailures == 1)
_log.Warning(ex, "DriverInstance {Id}: native-alarm subscription failed — feed stays gated until the periodic reconcile retries it",
_driverInstanceId);
else
_log.Warning("DriverInstance {Id}: native-alarm subscription retry {Attempt} failed ({Reason}) — next retry in {Ticks} health-poll tick(s)",
_driverInstanceId, _alarmSubscribeFailures, ex.Message, _alarmRetrySkipTicks + 1);
}
}
/// Records the host's desired subscription set without touching the live subscription.
/// The set is (re)applied by on the next Connected entry.
private void StoreDesiredSubscriptions(SetDesiredSubscriptions msg)
{
_desiredRefs = msg.FullReferences;
_desiredInterval = msg.PublishingInterval;
_desiredAlarmRefs = msg.AlarmReferences ?? Array.Empty();
}
private void StoreDisconnectedDesiredSubscriptions(SetDesiredSubscriptions msg)
{
if (msg.RequireAcquisition)
Sender.Tell(new AcquisitionDemandApplied(msg.DesiredRevision, msg.ProducerIncarnation, TimeSpan.Zero, false));
else StoreDesiredSubscriptions(msg);
}
/// Re-establish the desired subscription after (re)connecting. Self-sends the one-shot
/// the Connected behaviour already handles (which drops any prior handle
/// first), so values resume streaming after a reconnect or redeploy without host involvement.
private void ResubscribeDesired()
{
if (_desiredAcquisition is { } acquisition) Self.Tell(acquisition);
else if (_desiredRefs.Count > 0) Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
}
/// Forward a per-tag-only driver's data change to the parent for OPC UA publication, as a
/// single-item batch — so the parent sees ONE message shape whether or not the driver batches.
/// The driver's status code rides through UNCHANGED. This used to project it onto a
/// 3-state Good/Uncertain/Bad enum here, which the node manager then re-expanded to a bare
/// 0x80000000 — so no driver's sub-code ever reached a client, and the status constants each
/// driver maintains were diagnostic in logs only.
private void PublishSource(string reference, DataValueSnapshot? snapshot)
{
if (_sourcePublisher is null) return;
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceTicket ticket = default;
var found = false;
try
{
found = _sourceIncarnation is { } incarnation
? _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, incarnation, out ticket)
: _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, out ticket);
if (!found && snapshot is not null && _sourceIncarnation is { } current &&
_sourcePublisher.EnsureDriverBinding(_clusterId, _driverInstanceId, reference, current))
found = _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, current, out ticket);
if (!found) return;
if (snapshot is null) _sourcePublisher.Invalidate(ticket, "malformed driver callback");
else _sourcePublisher.TryPublish(ticket, snapshot);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (found) _sourcePublisher.Invalidate(ticket, "source callback failed");
_log.Warning(ex, "DriverInstance {Id}: source callback unavailable; legacy publication continues", _driverInstanceId);
}
}
// A malformed snapshot still crosses the mailbox in an incarnation-tagged envelope. The actor's
// existing supervision path handles it; the producer's callback thread must never throw for it.
private static DataValueSnapshot CopyLegacySnapshot(DataValueSnapshot? snapshot) => snapshot is null
? null!
: snapshot with { Value = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.CopyLegacy(snapshot.Value) };
private void OnDataChangeForward(DataChangeForward msg)
{
if (msg.ProducerIncarnation != _sourceIncarnation) return;
var ts = msg.Snapshot.SourceTimestampUtc ?? msg.Snapshot.ServerTimestampUtc ?? DateTime.MinValue;
Context.Parent.Tell(new AttributeValueBatchPublished(
_driverInstanceId,
new[] { new AttributeValueItem(msg.FullReference, msg.Snapshot.Value, msg.Snapshot.StatusCode, ts,
msg.Snapshot.SourceTimestampUtc, msg.Snapshot.ServerTimestampUtc) }));
}
/// Forward one batch-capable driver production burst to the parent as a single message.
/// Every item's status code and timestamp ride through exactly as
/// carries them for a per-tag driver (timestamps come from the
/// driver's snapshot, never from this actor's clock).
private void OnDataChangeBatchForward(DataChangeBatchForward msg)
{
if (msg.ProducerIncarnation != _sourceIncarnation) return;
var items = new AttributeValueItem[msg.Items.Count];
for (var i = 0; i < msg.Items.Count; i++)
{
var item = msg.Items[i];
var ts = item.Snapshot.SourceTimestampUtc ?? item.Snapshot.ServerTimestampUtc ?? DateTime.MinValue;
items[i] = new AttributeValueItem(item.FullReference, item.Snapshot.Value, item.Snapshot.StatusCode, ts,
item.Snapshot.SourceTimestampUtc, item.Snapshot.ServerTimestampUtc);
}
Context.Parent.Tell(new AttributeValueBatchPublished(_driverInstanceId, items));
}
private static bool IsGoodStatus(uint statusCode) => OpcUaStatus.IsGood(statusCode);
/// Resolve the resilience-pipeline host key for a single driver-side reference. Multi-host
/// drivers (e.g. Modbus across N PLCs) implement so one dead host
/// trips only its own breaker; single-host drivers fall back to the driver-instance id. Used for the
/// single-reference capability calls (write, alarm ack); bulk/whole-driver calls key on the instance
/// id directly.
private string ResolveHost(string reference) =>
_driver is IPerCallHostResolver resolver ? resolver.ResolveHost(reference) : _driverInstanceId;
/// Records a transition into a Faulted / error state for the 5-minute sliding counter.
private void RecordFault()
{
_faultTimestamps.Enqueue(DateTime.UtcNow);
}
/// Returns how many fault transitions occurred in the last 5 minutes.
private int ErrorCount5Min()
{
var cutoff = DateTime.UtcNow.AddMinutes(-5);
while (_faultTimestamps.Count > 0 && _faultTimestamps.Peek() < cutoff)
_faultTimestamps.Dequeue();
return _faultTimestamps.Count;
}
///
/// Polls and forwards the snapshot to the health publisher.
/// Called on every observable state change and by the periodic
/// so the AdminUI snapshot store is warmed up for newly-joined SignalR clients.
/// Deduplicates: if the resulting (state, lastSuccess, lastError, errorCount) tuple matches
/// the last publish, this call is a no-op. Stops flood-publishing identical Healthy snapshots
/// every 30s when nothing has changed. Newly-joined SignalR clients still get the current
/// snapshot via DriverStatusHub.JoinDriver which reads the store directly.
///
/// The health observed on this call, or null when threw.
/// Returned so the caller can reuse the same observation — the comms-loss watchdog rides this
/// call rather than polling the driver a second time and risking a different answer.
private DriverHealth? PublishHealthSnapshot()
{
DriverHealth? observed = null;
try
{
var health = _driver.GetHealth();
observed = health;
var errorCount = ErrorCount5Min();
var hostStatuses = CurrentHostStatuses();
var skippedTags = CurrentSkippedTags();
var diagnostics = CurrentDiagnostics();
// _rediscoveryNeededUtc is PART OF THE FINGERPRINT on purpose. A rediscovery raise on an
// otherwise-unchanged Healthy driver leaves (state, lastSuccess, lastError, errorCount)
// identical, so without it the dedup below would swallow the very publish that carries the
// signal and the operator would never see the prompt.
//
// The host-status digest is in the fingerprint for EXACTLY the same reason, and the failure
// mode is the more likely one of the two: a multi-device driver stays aggregate-Healthy when a
// single device drops, so every other fingerprint component is unchanged and the transition —
// the whole point of this channel — would be deduped away. It is a flattened STRING because a
// tuple holding IReadOnlyList compares by reference, which would never match and so would
// defeat the dedup in the opposite direction (re-publishing every 30 s heartbeat).
//
// The skip digest is in the fingerprint for the third instance of that same argument, and
// here it is the WHOLE point of the channel: a driver that skipped tags is by construction
// one whose state, error count and last-error are all unremarkable, so every other component
// is identical to a clean driver's and the publish that carries the signal is exactly the one
// dedup would swallow. Flattened to a STRING for the same reason as the host digest — the
// report holds an IReadOnlyList, which a tuple compares by reference.
//
// The diagnostics digest is the fourth instance: a diagnostic fact (S7's PDU size
// changing across a reconnect) moves none of the other components, so without it the publish
// that carries it is deduped away. Flattened to a STRING - the bag is a dictionary, which a
// tuple compares by reference.
var fingerprint = (health.State, health.LastSuccessfulRead, health.LastError, errorCount,
_rediscoveryNeededUtc, HostStatusDigest(hostStatuses), SkippedTagDigest(skippedTags),
DiagnosticsDigest(diagnostics));
if (_lastPublishedFingerprint is { } prev && prev.Equals(fingerprint))
return observed;
_lastPublishedFingerprint = fingerprint;
_healthPublisher.Publish(
_clusterId, _driverInstanceId, health, errorCount, _rediscoveryNeededUtc, _rediscoveryReason,
hostStatuses, skippedTags, diagnostics);
}
catch (Exception ex)
{
_log.Warning(ex, "DriverInstance {Id}: GetHealth threw during health publish; skipping", _driverInstanceId);
}
return observed;
}
/// Order-insensitive value digest of a host-status list for the publish fingerprint. Null in,
/// null out — so "driver is not a probe" and "probe reports no hosts" stay distinguishable rather than
/// both collapsing to the empty string.
/// Ordered by host name because a driver is free to return its hosts in any order (several build
/// the list from a Dictionary), and an order flip would otherwise read as a real transition and
/// re-publish forever.
private static string? HostStatusDigest(IReadOnlyList? statuses) =>
statuses is null
? null
: string.Join('|', statuses
.OrderBy(s => s.HostName, StringComparer.Ordinal)
.Select(s => $"{s.HostName}={s.State}@{s.LastChangedUtc:O}"));
/// Value digest of a skip report for the publish fingerprint. Null in, null out, so "driver
/// cannot report skips" and "driver reports none" stay distinguishable rather than both collapsing to
/// the same string.
/// The counts alone would be enough to catch a change in HOW MANY tags are skipped, but not a
/// change in WHICH — a redeploy that fixes one tag and breaks another leaves both counts identical,
/// and the operator would keep reading the stale sample. So the sample is in the digest too.
private static string? SkippedTagDigest(SkippedTagReport? report) =>
report is null
? null
: $"{report.AuthoredCount}/{report.SkippedCount}:" +
string.Join('|', report.Sample.Select(s => $"{s.RawPath}={s.Reason}"));
/// Fingerprint of the last call; null until first publish.
private (DriverState State, DateTime? LastSuccess, string? LastError, int ErrorCount,
DateTime? RediscoveryNeededUtc, string? HostStatusDigest, string? SkippedTagDigest,
string? DiagnosticsDigest)? _lastPublishedFingerprint;
///
protected override void PostStop()
{
_pendingAcquisition?.Abandon();
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
// entry; stopping did not, so an operator's Restart and a supervision respawn tore this child down
// silently and its value nodes went on serving their last value at Good across the gap. The fresh
// child's re-subscribe + initial push (03/S16) is what clears them again; on a deploy that REMOVES
// the driver the host has already rebuilt its ref index without it, so the Tell finds nothing.
//
// Gated on having actually reached Connected: a child that never connected leaves its nodes at
// BadWaitingForInitialData, which says something more precise than "communication lost", and
// overwriting it would claim an outage that never happened.
if (_connectedSinceUtc != default)
{
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false, ProducerIncarnation: _sourceIncarnation));
}
DetachSubscription();
FailQueuedWrites("driver stopped");
// MUST happen: the IDriver instance can outlive this actor (the host respawns a child around the
// same driver object), so a missing unsubscribe accumulates a handler per respawn holding a dead Self.
DetachRediscoverySource();
DetachHostStatusSource();
DetachConnectionLossSource();
// An attempt still inside the driver is cancelled before the shutdown below runs underneath it (on a
// restart the next incarnation re-initialises the same object). Best-effort: the task owns the CTS
// and may have disposed it already.
try { _initCts?.Cancel(); }
catch (ObjectDisposedException) { /* the attempt already finished */ }
// In-flight native-ack confirmations (lmxopcua#869) are abandoned, and each reports its ack unconfirmed so
// the host reverts it — this incarnation can no longer observe the upstream's confirmation.
_ackConfirmCts.Cancel();
// BOUNDED by ONE shared budget across shutdown + dispose. PostStop runs on a dispatcher thread and this
// blocks it, so an unbounded wait on a driver whose shutdown hangs against a dead socket / COM proxy pinned
// that thread for the whole wait, and a few such stops starved the dispatcher. A shutdown that overruns is
// abandoned, and the dispose gets whatever is left of the same budget (never a second full one).
var budget = Stopwatch.StartNew();
using (var cts = new CancellationTokenSource(_shutdownTimeout))
{
try { _driver.ShutdownAsync(cts.Token).WaitAsync(_shutdownTimeout).GetAwaiter().GetResult(); }
catch (TimeoutException)
{
_log.Warning("DriverInstance {Id}: ShutdownAsync did not complete within {Bound} on PostStop; abandoning it",
_driverInstanceId, _shutdownTimeout);
}
catch (Exception ex) { _log.Warning(ex, "DriverInstance {Id}: ShutdownAsync threw on PostStop", _driverInstanceId); }
}
// Dispose ONLY on a real stop. A supervision restart (PreRestart → this PostStop) re-uses the same driver
// object for the next incarnation, which the host re-initialises. Everything else that stops a child —
// deploy removal, operator Restart, respawn on a config change, host shutdown — is final, and the driver
// is never touched again: before this, nothing in the runtime ever disposed an IDriver, so a Calculation
// driver's compiled-script AssemblyLoadContexts and an OpcUaClient driver's LoggerFactory / gate / CTS
// leaked once per respawn (02/L1). Bounded like the shutdown, and runs even after a timed-out shutdown —
// leaking the object is strictly worse than disposing one whose shutdown is still wedged.
if (!_restarting)
{
var remaining = _shutdownTimeout - budget.Elapsed;
DisposeDriver(remaining > MinDisposeBudget ? remaining : MinDisposeBudget);
}
OtOpcUaTelemetry.DriverInstanceLifecycle.Add(1,
new KeyValuePair("event", "stop"),
new KeyValuePair("driver_type", _driver.DriverType));
}
/// Floor on the dispose's share of the PostStop budget once a timed-out shutdown has used it up —
/// enough for an idempotent dispose to run, not enough to double the stop's thread time.
private static readonly TimeSpan MinDisposeBudget = TimeSpan.FromMilliseconds(250);
/// Final teardown of the wrapped driver: preferred, else
/// , never both. A driver implementing neither needs nothing here. Runs even after
/// a timed-out shutdown, so a driver's dispose must be safe CONCURRENTLY with its own still-running
/// .
/// The remaining PostStop budget available to an async dispose.
private void DisposeDriver(TimeSpan bound)
{
try
{
switch (_driver)
{
case IAsyncDisposable asyncDisposable:
asyncDisposable.DisposeAsync().AsTask().WaitAsync(bound).GetAwaiter().GetResult();
break;
case IDisposable disposable:
disposable.Dispose();
break;
default:
return;
}
_log.Info("DriverInstance {Id}: disposed {Type} driver on stop", _driverInstanceId, _driver.DriverType);
OtOpcUaTelemetry.DriverInstanceLifecycle.Add(1,
new KeyValuePair("event", "dispose"),
new KeyValuePair("driver_type", _driver.DriverType));
}
catch (TimeoutException)
{
_log.Warning("DriverInstance {Id}: DisposeAsync did not complete within {Bound} on PostStop; abandoning it",
_driverInstanceId, bound);
}
catch (Exception ex)
{
_log.Warning(ex, "DriverInstance {Id}: disposing the driver threw on PostStop", _driverInstanceId);
}
}
}