f08ca7d9e3
- The Bad connectivity edge (and a Good edge with no Bad edge since the last Good one, or from a new child incarnation) sends MarkConditionsKnown(Known: false) for the driver's condition nodes, ahead of the quality annotation, so an alarm raised during an outage never reads known-inactive, Good after the reconnect. Stopping a child (a respawn) withdraws too. - DriverInstanceActor stamps a connection epoch (bumped on every Connected entry) on the initial-state signal and on ConnectivityChanged(Connected); a signal raised under an earlier connection is dropped by the child and the host. - G3 never discards a deferred withdrawal. - F5 'still unknown' follows the node manager: a native transition takes its ref out of Pending. - Re-arm F5 at the alarm-ref reindex for refs a deploy adds while connected (defensive: today such a deploy respawns the driver because its RawTags are folded into its config). - Nits: signals/edges from a retired or non-current child never (re)create a tracker; the injected clock replaces DateTime.UtcNow. - Primary demote/re-promote: checked, not a stale-known window — drivers and their condition writes run ungated on both pair members.
3182 lines
185 KiB
C#
3182 lines
185 KiB
C#
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() { }
|
||
}
|
||
|
||
/// <summary>Process-lifetime bound for physical subscription establishments and late cleanup.</summary>
|
||
public sealed class SubscriptionAcquisitionCapacity
|
||
{
|
||
private readonly object _gate = new();
|
||
private readonly Dictionary<(string Cluster, string Driver), TaskCompletionSource<bool>> _inFlight = new();
|
||
private readonly int _limit;
|
||
private long _ownerSerial;
|
||
private long _controlGeneration;
|
||
|
||
/// <summary>Creates a shared capacity with a fixed maximum number of in-flight drivers.</summary>
|
||
public SubscriptionAcquisitionCapacity(int limit)
|
||
{
|
||
if (limit <= 0) throw new ArgumentOutOfRangeException(nameof(limit));
|
||
_limit = limit;
|
||
}
|
||
|
||
/// <summary>Number of driver keys held by active subscriptions, establishments, or cleanup.</summary>
|
||
public int ReservedDriverCount { get { lock (_gate) return _inFlight.Count; } }
|
||
/// <summary>Configured maximum concurrent driver reservations.</summary>
|
||
public int MaxReservations => _limit;
|
||
/// <summary>Issues a process-lifetime serial for a new bridge owner.</summary>
|
||
public long NextOwnerSerial()
|
||
{
|
||
var serial = Interlocked.Increment(ref _ownerSerial);
|
||
return serial > 0 ? serial : throw new InvalidOperationException("Acquisition owner serial exhausted.");
|
||
}
|
||
/// <summary>Latest issued bridge owner serial.</summary>
|
||
public long CurrentOwnerSerial => Interlocked.Read(ref _ownerSerial);
|
||
/// <summary>Latest process-lifetime control generation.</summary>
|
||
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<bool>? 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<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
_inFlight.Add(key, completion);
|
||
return new Reservation(this, key, completion);
|
||
}
|
||
}
|
||
|
||
private sealed class Reservation(SubscriptionAcquisitionCapacity owner, (string Cluster, string Driver) key,
|
||
TaskCompletionSource<bool> 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);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Akka wrapper for a single <see cref="IDriver"/> instance. States:
|
||
///
|
||
/// <list type="bullet">
|
||
/// <item><c>Connecting</c> — calling <see cref="IDriver.InitializeAsync"/>.</item>
|
||
/// <item><c>Connected</c> — initialised; serving Read/Write/Subscribe requests.</item>
|
||
/// <item><c>Reconnecting</c> — disconnect observed; periodic retry of Initialize.</item>
|
||
/// <item><c>Failed</c> — terminal until parent restarts the actor.</item>
|
||
/// </list>
|
||
///
|
||
/// 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.
|
||
/// </summary>
|
||
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);
|
||
/// <summary>Sent to the parent (<see cref="DriverHostActor"/>) on every connectivity transition:
|
||
/// <c>Connected=true</c> on entering the Connected state, <c>false</c> 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.</summary>
|
||
public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected, long? ProducerIncarnation = null,
|
||
long? ConnectionEpoch = null);
|
||
|
||
/// <summary>
|
||
/// Sent to the parent from <see cref="PostRestart"/> so the host re-provisions THIS incarnation.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// A supervision restart recreates the actor object in place: the desired subscription sets are gone
|
||
/// (they are instance fields), and <c>PreRestart</c> has already run <see cref="PostStop"/> — which
|
||
/// called <see cref="IDriver.ShutdownAsync"/> on the driver object the Props closure re-uses. Nothing
|
||
/// else re-sends <see cref="InitializeRequested"/>: its only sender is
|
||
/// <c>DriverHostActor.SpawnChild</c>, and a restart does NOT respawn (the child's
|
||
/// <see cref="IActorRef"/> is unchanged, so the host is not otherwise notified that a new incarnation
|
||
/// exists at all). Without this the restarted child sits in <c>Connecting</c> forever around a
|
||
/// shut-down driver, with nothing subscribed — silently, since Akka logs the fault but the recovery
|
||
/// is invisible.
|
||
/// </remarks>
|
||
/// <param name="DriverInstanceId">The driver instance that was restarted.</param>
|
||
/// <param name="Reason">The type name of the exception that tripped supervision, for the host's log.</param>
|
||
public sealed record ReprovisionRequested(string DriverInstanceId, string Reason);
|
||
/// <summary>An operator write of <paramref name="Value"/> to the tag <paramref name="TagId"/>.</summary>
|
||
/// <param name="TagId">The tag's driver wire reference (RawPath).</param>
|
||
/// <param name="Value">The value to write.</param>
|
||
/// <param name="IssuedAt">When the asker issued the write, as a timestamp of the actor's write clock
|
||
/// (<see cref="TimeProvider.GetTimestamp"/>); null = when the actor receives it. <see cref="DriverHostActor"/>
|
||
/// 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).</param>
|
||
public sealed record WriteAttribute(string TagId, object Value, long? IssuedAt = null);
|
||
public sealed record WriteAttributeResult(bool Success, string? Reason);
|
||
internal sealed record WriteAttributeWithOutcome(WriteAdmissionTicket Ticket, WriteClaim Claim);
|
||
/// <summary>
|
||
/// Sent by <see cref="DriverHostActor"/> when an OPC UA client Acknowledges a NATIVE Part 9
|
||
/// condition (resolved from the condition NodeId to this driver via the host's alarm inverse map).
|
||
/// The actor forwards it to the driver's <see cref="IAlarmSource.AcknowledgeAsync"/>, carrying the
|
||
/// authored alarm full-reference (= the driver's <c>ConditionId</c>/AlarmFullReference) and the
|
||
/// authenticated principal. Mirrors <see cref="WriteAttribute"/>, but the ack is fire-and-forget:
|
||
/// the driver's <see cref="IAlarmSource.AcknowledgeAsync"/> 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.
|
||
/// </summary>
|
||
/// <param name="ConditionId">The authored alarm full-reference the driver correlates the ack on
|
||
/// (= the equipment tag's <c>FullName</c>/AlarmFullReference).</param>
|
||
/// <param name="Comment">Operator-supplied comment forwarded to the upstream alarm system; null when none.</param>
|
||
/// <param name="OperatorUser">The authenticated principal performing the acknowledge.</param>
|
||
/// <param name="ApiKeyId">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).</param>
|
||
/// <param name="ConditionNodeId">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 <see cref="AlarmAckFailed"/> so the host can revert
|
||
/// the locally-applied acknowledge (lmxopcua#760). Null ⇒ no report.</param>
|
||
/// <param name="AckSequence">The host projector's sequence for this acknowledge (lmxopcua#869), echoed on
|
||
/// <see cref="AlarmAckFailed"/> so only a failure of THIS ack reverts it; 0 ⇒ the ack changed nothing.</param>
|
||
public sealed record RouteAlarmAck(
|
||
string ConditionId, string? Comment, string OperatorUser, string? ApiKeyId = null, string? ConditionNodeId = null,
|
||
long AckSequence = 0);
|
||
|
||
/// <summary>
|
||
/// Reply to a <see cref="RouteAlarmAck"/> carrying a <see cref="RouteAlarmAck.ConditionNodeId"/> whose
|
||
/// acknowledge never reached the upstream alarm system (lmxopcua#760). Success sends nothing.
|
||
/// </summary>
|
||
/// <param name="ConditionNodeId">The OPC UA condition NodeId the client acknowledged.</param>
|
||
/// <param name="Reason">Why the acknowledge did not go through; never contains a secret.</param>
|
||
/// <param name="AckSequence">The failed acknowledge's <see cref="RouteAlarmAck.AckSequence"/> (lmxopcua#869).</param>
|
||
public sealed record AlarmAckFailed(string ConditionNodeId, string Reason, long AckSequence = 0);
|
||
public sealed record Subscribe(IReadOnlyList<string> FullReferences, TimeSpan PublishingInterval);
|
||
/// <summary>
|
||
/// Sets the set of references this driver should keep subscribed for the lifetime of the
|
||
/// current deployment. Unlike the one-shot <see cref="Subscribe"/>, the desired set is
|
||
/// retained and (re)established automatically every time the actor (re)enters
|
||
/// <c>Connected</c> — closing the F8b "re-subscribe across reconnects" gap and giving
|
||
/// <see cref="DriverHostActor"/> a single message to drive the SubscribeBulk pass after an
|
||
/// apply. Sending an empty set clears the desired subscription.
|
||
/// </summary>
|
||
/// <param name="AlarmReferences">
|
||
/// The native-alarm references (alarm-bearing equipment-tag FullNames = the driver's
|
||
/// <c>ConditionId</c>/AlarmFullReference) this driver should keep an alarm subscription open for.
|
||
/// An <see cref="IAlarmSource"/> driver suppresses <see cref="IAlarmSource.OnAlarmEvent"/> until at
|
||
/// least one alarm subscription exists, so the actor calls
|
||
/// <see cref="IAlarmSource.SubscribeAlarmsAsync"/> 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.
|
||
/// </param>
|
||
public sealed record SetDesiredSubscriptions(
|
||
IReadOnlyList<string> FullReferences,
|
||
TimeSpan PublishingInterval,
|
||
IReadOnlyList<string>? AlarmReferences = null,
|
||
long DesiredRevision = 0, long ProducerIncarnation = 0, bool RequireAcquisition = false);
|
||
/// <summary>Physical demand installation result, including the driver-acknowledged fence.</summary>
|
||
public sealed record AcquisitionDemandApplied(long DesiredRevision, long ProducerIncarnation,
|
||
TimeSpan NominalSamplingInterval, bool Succeeded, bool Busy = false, Task<bool>? 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;
|
||
/// <summary>
|
||
/// Sent by <see cref="DriverHostActor"/> when the AdminUI issues a Reconnect operation.
|
||
/// Pushes the actor out of <c>Connected</c> into <c>Reconnecting</c> 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.
|
||
/// </summary>
|
||
public sealed record ForceReconnect;
|
||
/// <summary>One value within an <see cref="AttributeValueBatchPublished"/>.
|
||
/// <para><paramref name="StatusCode"/> is the driver's full OPC UA status code including its sub-code
|
||
/// — not a severity bucket. Classify it with <see cref="OpcUaStatus.IsGood"/> and friends rather
|
||
/// than comparing it to <see cref="OpcUaStatus.Good"/>.</para>
|
||
/// <para>A struct deliberately: an <c>AttributeValueItem[]</c> 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
|
||
/// <see cref="IReadOnlyList{T}"/> does not box.</para></summary>
|
||
public readonly record struct AttributeValueItem(string FullReference, object? Value, uint StatusCode, DateTime TimestampUtc,
|
||
DateTime? SourceTimestampUtc = null, DateTime? ServerTimestampUtc = null);
|
||
/// <summary>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.</summary>
|
||
public sealed record AttributeValueBatchPublished(string DriverInstanceId, IReadOnlyList<AttributeValueItem> Items);
|
||
private sealed record DataChangeForward(string FullReference, DataValueSnapshot Snapshot, long? ProducerIncarnation);
|
||
/// <summary>Self-sent when a batch-capable driver (<see cref="IBatchSubscribable"/>) raises
|
||
/// <see cref="IBatchSubscribable.OnDataChangeBatch"/> — marshals the whole burst off the driver's
|
||
/// thread onto the actor thread in one hop. Parallels <see cref="DataChangeForward"/>.</summary>
|
||
private sealed record DataChangeBatchForward(IReadOnlyList<DataChangeItem> Items, long? ProducerIncarnation);
|
||
private sealed record RetrySourceBindings(IReadOnlyList<string> References, int Offset, bool Failed,
|
||
int Attempt, long Version, long ProducerIncarnation);
|
||
/// <summary>Published to the parent whenever the subscribed driver (an <see cref="IAlarmSource"/>) fires
|
||
/// <see cref="IAlarmSource.OnAlarmEvent"/>. The parent (<see cref="DriverHostActor"/>) projects + routes it
|
||
/// to the materialised Part 9 condition. Parallels <see cref="AttributeValueBatchPublished"/>.</summary>
|
||
public sealed record AttributeAlarmPublished(string DriverInstanceId, AlarmEventArgs Args);
|
||
private sealed record NativeAlarmRaised(AlarmEventArgs Args);
|
||
/// <summary>A1 (plan §5.1 F2): published to the parent when the driver raises
|
||
/// <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/>. It travels the SAME self-Tell → parent path as
|
||
/// <see cref="AttributeAlarmPublished"/>, so it reaches <see cref="DriverHostActor"/> after every alarm event the
|
||
/// driver raised before it.</summary>
|
||
/// <remarks>A1 review S2: <paramref name="ConnectionEpoch"/> is the connection (Connected entry) the driver raised
|
||
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge.</remarks>
|
||
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args,
|
||
long? ConnectionEpoch = null);
|
||
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch);
|
||
/// <summary>Self-sent on Connected entry / when alarm refs are (re)pushed, to establish the native-alarm
|
||
/// subscription that un-gates an <see cref="IAlarmSource"/> driver's feed. Handled async so the
|
||
/// <see cref="IAlarmSource.SubscribeAlarmsAsync"/> call is bounded + off the synchronous handlers.</summary>
|
||
private sealed record SubscribeAlarms;
|
||
/// <summary>Self-sent when the wrapped driver raises <see cref="IRediscoverable.OnRediscoveryNeeded"/> —
|
||
/// 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.</summary>
|
||
private sealed record RediscoveryRaised(RediscoveryEventArgs Args);
|
||
/// <summary>Self-sent when the wrapped driver raises <see cref="IHostConnectivityProbe.OnHostStatusChanged"/>
|
||
/// — 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
|
||
/// <see cref="IHostConnectivityProbe.GetHostStatuses"/>, 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 <see cref="RediscoveryRaised"/> — a probe tick can land while the
|
||
/// driver is between connects.</summary>
|
||
private sealed record HostStatusRaised;
|
||
/// <summary>Self-sent when the wrapped driver raises <see cref="IDriverConnectionLossSource.ConnectionLost"/>
|
||
/// — 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.</summary>
|
||
private sealed record ConnectionLossRaised(DriverConnectionLossEventArgs Args);
|
||
|
||
public sealed class RetryConnect
|
||
{
|
||
public static readonly RetryConnect Instance = new();
|
||
private RetryConnect() { }
|
||
}
|
||
|
||
/// <summary>Interval between periodic health-poll heartbeats sent to the snapshot store.</summary>
|
||
public static readonly TimeSpan HealthPollInterval = TimeSpan.FromSeconds(30);
|
||
|
||
/// <summary>
|
||
/// 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 <see cref="HealthPollInterval"/> tick, so the effective detection granularity is
|
||
/// 30 s and the worst-case detection latency is this value plus one tick.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// 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 <see cref="HealthPollInterval"/> and
|
||
/// <see cref="DefaultReconnectInterval"/>. Unlike the periodic drift-detector removed earlier,
|
||
/// this generates <b>no</b> outbound traffic on a healthy system: the watchdog is a local
|
||
/// read of <see cref="IDriver.GetHealth"/>, and it only reaches the network once a driver has
|
||
/// already stopped reading successfully.
|
||
/// </remarks>
|
||
public static readonly TimeSpan DefaultCommsLossTimeout = TimeSpan.FromSeconds(90);
|
||
|
||
/// <summary>
|
||
/// Bound on the driver's <see cref="IDriver.ShutdownAsync"/> (and its dispose) when the child stops or
|
||
/// restarts, and on the teardown that precedes every reconnect attempt. <c>PostStop</c> 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 <c>CoordinatedShutdown</c> and the host's own restart cascade. A shutdown that overruns is
|
||
/// abandoned (logged), never awaited further.
|
||
/// </summary>
|
||
public static readonly TimeSpan DefaultShutdownTimeout = TimeSpan.FromSeconds(5);
|
||
|
||
/// <summary>
|
||
/// Default cap on the writes this actor runs against its driver at once. Writes run OFF the mailbox
|
||
/// (a <c>ReceiveAsync</c> 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.
|
||
/// </summary>
|
||
public const int DefaultMaxWritesInFlight = 4;
|
||
|
||
/// <summary>
|
||
/// How long a queued write may wait for a slot before it is failed <c>BadTimeout</c> instead of being
|
||
/// written, when no explicit budget is given: <see cref="DriverWriteBounds.QueueBudget"/> 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 (<see cref="DriverWriteBounds.HostAsk"/>), so a write started inside the budget is always answered
|
||
/// before the host reports it failed.
|
||
/// </summary>
|
||
public static readonly TimeSpan DefaultQueuedWriteBudget = DriverWriteBounds.Default.QueueBudget;
|
||
|
||
/// <summary>
|
||
/// Pessimistic bound on one <see cref="IDriver.InitializeAsync"/> 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).
|
||
/// </summary>
|
||
public static readonly TimeSpan DefaultInitializeTimeout = TimeSpan.FromSeconds(30);
|
||
|
||
/// <summary>
|
||
/// Bound on one write round-trip. The write's cancellation token is cancelled when it elapses (the write
|
||
/// answers <c>"write timeout"</c>); a driver whose <see cref="IWritable.WriteAsync"/> ignores its token is
|
||
/// abandoned <see cref="WriteAbandonGrace"/> later (the write answers <c>BadTimeout</c> 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.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// <see cref="DriverWriteBounds.DefaultTimeout"/>. The host's write Ask is DERIVED from the same value
|
||
/// (<see cref="DriverWriteBounds.HostAsk"/>, 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.
|
||
/// </remarks>
|
||
public static readonly TimeSpan DefaultWriteTimeout = DriverWriteBounds.DefaultTimeout;
|
||
|
||
/// <summary>
|
||
/// How long after a write's token is cancelled a write that has not returned is abandoned as
|
||
/// token-ignoring; see <see cref="DriverWriteBounds.AbandonGrace"/>.
|
||
/// </summary>
|
||
/// <param name="writeTimeout">The write timeout in force.</param>
|
||
/// <returns>The grace between cancelling the write's token and abandoning the write.</returns>
|
||
internal static TimeSpan WriteAbandonGrace(TimeSpan writeTimeout) => DriverWriteBounds.AbandonGraceFor(writeTimeout);
|
||
|
||
/// <summary>Self-sent by a write task once it has replied, releasing its slot and its tag.</summary>
|
||
/// <param name="TagId">The tag the write held.</param>
|
||
/// <param name="Incarnation">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.</param>
|
||
private sealed record WriteCompleted(string TagId, int Incarnation);
|
||
|
||
private readonly IDriver _driver;
|
||
|
||
/// <summary>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
|
||
/// <see cref="NullDriverCapabilityInvoker"/> (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 <see cref="IDriverCapabilityInvokerFactory"/> and injects it at
|
||
/// spawn. Consumed through the <see cref="IDriverCapabilityInvoker"/> abstraction because Runtime
|
||
/// is deliberately Polly-free (it does not reference <c>ZB.MOM.WW.OtOpcUa.Core</c>).</summary>
|
||
private readonly IDriverCapabilityInvoker _invoker;
|
||
private readonly string _driverInstanceId;
|
||
private readonly string _clusterId;
|
||
private readonly IDriverHealthPublisher _healthPublisher;
|
||
private readonly TimeSpan _reconnectInterval;
|
||
|
||
private readonly TimeSpan _healthPollInterval;
|
||
|
||
/// <summary>Comms-loss watchdog threshold; <see cref="TimeSpan.Zero"/> or negative disables it.</summary>
|
||
private readonly TimeSpan _commsLossTimeout;
|
||
|
||
/// <summary>Bound on the driver shutdown / dispose; see <see cref="DefaultShutdownTimeout"/>.</summary>
|
||
private readonly TimeSpan _shutdownTimeout;
|
||
|
||
/// <summary>Cap on concurrent writes; see <see cref="DefaultMaxWritesInFlight"/>.</summary>
|
||
private readonly int _maxWritesInFlight;
|
||
|
||
/// <summary>Writes currently inside the driver. Actor-thread only (incremented on launch, decremented on
|
||
/// the self-sent <see cref="WriteCompleted"/>).</summary>
|
||
private int _writesInFlight;
|
||
|
||
/// <summary>Writes waiting for a slot (or for their tag), in arrival order, stamped with arrival time.
|
||
/// Failed fast on every exit from <c>Connected</c>, so a queued write never reaches a driver that is
|
||
/// reconnecting; failed <c>BadTimeout</c> once older than <see cref="_queuedWriteBudget"/> since issued.</summary>
|
||
private readonly LinkedList<(WriteAttribute Write, IActorRef ReplyTo, long IssuedAt, long Sequence)> _pendingWrites = new();
|
||
private readonly LinkedList<(WriteAttributeWithOutcome Write, IActorRef ReplyTo, long Sequence)> _pendingRichWrites = new();
|
||
private long _queuedWriteSequence;
|
||
private readonly IWriteDispatchGate? _writeDispatchGate;
|
||
private readonly LateWriteObserver? _lateWriteObserver;
|
||
private readonly WriteRouteState? _writeRouteState;
|
||
private string? _writeIncarnation;
|
||
|
||
/// <summary>Tags with a write currently inside the driver. A second write to the same tag waits in the
|
||
/// queue behind it — two concurrent writes v1, v2 to one tag could otherwise land as v1.</summary>
|
||
private readonly HashSet<string> _tagsInFlight = new(StringComparer.Ordinal);
|
||
|
||
/// <summary>See <see cref="DefaultQueuedWriteBudget"/>.</summary>
|
||
private readonly TimeSpan _queuedWriteBudget;
|
||
|
||
/// <summary>See <see cref="DefaultInitializeTimeout"/>.</summary>
|
||
private readonly TimeSpan _initializeTimeout;
|
||
|
||
/// <summary>See <see cref="DefaultWriteTimeout"/>.</summary>
|
||
private readonly TimeSpan _writeTimeout;
|
||
|
||
/// <summary>The clock the write bounds run on — <see cref="TimeProvider.System"/> outside tests.</summary>
|
||
private readonly TimeProvider _writeClock;
|
||
|
||
/// <summary>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).</summary>
|
||
private readonly int _incarnation;
|
||
|
||
/// <summary>
|
||
/// Set by <see cref="PreRestart"/> so the <see cref="PostStop"/> it triggers skips the dispose. A
|
||
/// supervision restart recreates the actor object around the SAME <see cref="IDriver"/> (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.
|
||
/// </summary>
|
||
private bool _restarting;
|
||
|
||
/// <summary>When the actor last entered <c>Connected</c>. 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.</summary>
|
||
private DateTime _connectedSinceUtc;
|
||
|
||
private readonly ILoggingAdapter _log = Context.GetLogger();
|
||
private string? _currentConfigJson;
|
||
|
||
/// <summary>Monotonic token tagging each <see cref="InitializeAsync"/> 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.</summary>
|
||
private int _initGeneration;
|
||
|
||
/// <summary>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.</summary>
|
||
private static int s_initGenerationSource;
|
||
|
||
/// <summary>
|
||
/// True while an <see cref="InitializeAsync"/> attempt is running (set when it is launched, cleared by its
|
||
/// piped <see cref="InitializeSucceeded"/>/<see cref="InitializeFailed"/>). The <c>Reconnecting</c> 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.
|
||
/// </summary>
|
||
private bool _initInFlight;
|
||
|
||
/// <summary>Cancellation for the in-flight attempt, so <see cref="PostStop"/> can cancel it before the
|
||
/// shutdown rather than let it race the teardown on a restart.</summary>
|
||
private CancellationTokenSource? _initCts;
|
||
|
||
/// <summary>Cancelled by <see cref="PostStop"/> to abandon in-flight native-ack confirmations (lmxopcua#869);
|
||
/// never disposed — detached confirmation tasks may still hold its token.</summary>
|
||
private readonly CancellationTokenSource _ackConfirmCts = new();
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
private readonly Queue<DateTime> _faultTimestamps = new();
|
||
|
||
/// <summary>Active subscription handle (null when not subscribed). Tracks the current live
|
||
/// subscription; the actor auto-(re)subscribes on (re)connect and on each <see cref="Subscribe"/>
|
||
/// message via <see cref="ResubscribeDesired"/> / <see cref="HandleSubscribeAsync"/>, so callers
|
||
/// do not need to re-send subscription requests after a reconnect.</summary>
|
||
private ISubscriptionHandle? _subscriptionHandle;
|
||
private EventHandler<DataChangeEventArgs>? _dataChangeHandler;
|
||
/// <summary>The batch data-change handler, attached INSTEAD of <see cref="_dataChangeHandler"/> when the
|
||
/// driver is an <see cref="IBatchSubscribable"/>. Exactly one of the two is ever non-null.</summary>
|
||
private EventHandler<DataChangeBatchEventArgs>? _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<bool>? _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<AlarmEventArgs>? _alarmEventHandler;
|
||
// A1 (plan §5.1 G5): attached and detached WITH the alarm handler, so the signal obeys exactly the gate
|
||
// OnAlarmEvent obeys.
|
||
private EventHandler<AlarmInitialStateEventArgs>? _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<RediscoveryEventArgs>? _rediscoveryHandler;
|
||
private EventHandler<HostStatusChangedEventArgs>? _hostStatusHandler;
|
||
private EventHandler<DriverConnectionLossEventArgs>? _connectionLossHandler;
|
||
|
||
/// <summary>When the driver last raised <see cref="IRediscoverable.OnRediscoveryNeeded"/>, 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.
|
||
/// <para>Deliberately <b>sticky</b> — 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.</para></summary>
|
||
private DateTime? _rediscoveryNeededUtc;
|
||
private string? _rediscoveryReason;
|
||
|
||
/// <summary>The references the host wants kept subscribed (set by <see cref="SetDesiredSubscriptions"/>).
|
||
/// Re-applied on every entry into <c>Connected</c> so values resume after a reconnect or redeploy.</summary>
|
||
private IReadOnlyList<string> _desiredRefs = Array.Empty<string>();
|
||
private TimeSpan _desiredInterval = TimeSpan.FromSeconds(1);
|
||
|
||
/// <summary>The native-alarm references the host wants kept subscribed (set by
|
||
/// <see cref="SetDesiredSubscriptions"/>). Re-applied on every <c>Connected</c> entry so the alarm
|
||
/// feed is re-un-gated after a reconnect/redeploy.</summary>
|
||
private IReadOnlyList<string> _desiredAlarmRefs = Array.Empty<string>();
|
||
|
||
/// <summary>The active native-alarm subscription handle for an <see cref="IAlarmSource"/> driver, or
|
||
/// null when none is established. Reset on <see cref="DetachAlarmSource"/> so the next Connected entry
|
||
/// re-subscribes against the freshly re-initialised driver; the null check makes the subscribe
|
||
/// idempotent across repeated <see cref="SetDesiredSubscriptions"/> pushes.</summary>
|
||
private IAlarmSubscriptionHandle? _alarmSubscriptionHandle;
|
||
|
||
/// <summary>The alarm references the live <see cref="_alarmSubscriptionHandle"/> was actually established
|
||
/// with, so a CHANGED desired set can be told apart from a repeat of the same one.
|
||
/// <para>Without this the subscription latched: both <see cref="SubscribeDesiredAlarms"/> and
|
||
/// <see cref="HandleSubscribeAlarmsAsync"/> 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 <c>sourceNodeIds</c> (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.</para></summary>
|
||
private IReadOnlyList<string> _subscribedAlarmRefs = Array.Empty<string>();
|
||
|
||
/// <summary>Consecutive <see cref="HandleSubscribeAlarmsAsync"/> failures; reset on success and on
|
||
/// <see cref="DetachAlarmSource"/> (a new connection starts a new streak).</summary>
|
||
private int _alarmSubscribeFailures;
|
||
|
||
/// <summary>Health-poll ticks the alarm reconcile still skips before its next retry (backoff).</summary>
|
||
private int _alarmRetrySkipTicks;
|
||
|
||
/// <summary>Backoff cap: at the production 30 s tick a failing alarm subscribe is retried at least
|
||
/// every 4 minutes.</summary>
|
||
private const int MaxAlarmRetrySkipTicks = 7;
|
||
|
||
/// <summary>
|
||
/// Gets or sets the timer scheduler for scheduling reconnection attempts.
|
||
/// </summary>
|
||
public ITimerScheduler Timers { get; set; } = null!;
|
||
|
||
/// <summary>
|
||
/// Creates a Props object for instantiating a <see cref="DriverInstanceActor"/>.
|
||
/// </summary>
|
||
/// <param name="driver">The driver instance to wrap.</param>
|
||
/// <param name="reconnectInterval">Optional interval for reconnection attempts; defaults to 10 seconds.</param>
|
||
/// <param name="startStubbed">If true, the actor starts in stub mode for testing or unavailable platforms.</param>
|
||
/// <param name="healthPublisher">Optional health publisher; defaults to <see cref="NullDriverHealthPublisher"/> so tests and
|
||
/// stub paths don't need to provide one.</param>
|
||
/// <param name="clusterId">Optional cluster identifier forwarded in <see cref="DriverHealthChanged"/> messages;
|
||
/// defaults to an empty string when not provided (e.g. in unit tests).</param>
|
||
/// <param name="invoker">Optional Phase 6.1 resilience invoker wrapping this driver's capability
|
||
/// calls; defaults to <see cref="NullDriverCapabilityInvoker"/> (pass-through) when not supplied.</param>
|
||
/// <param name="healthPollInterval">Optional period of the health-poll heartbeat, which also drives the
|
||
/// subscription reconcile (<see cref="ReconcileSubscription"/>); defaults to
|
||
/// <see cref="HealthPollInterval"/>. Exists so a test can drive the reconcile without waiting 30 s.</param>
|
||
/// <param name="commsLossTimeout">Optional comms-loss watchdog threshold; defaults to
|
||
/// <see cref="DefaultCommsLossTimeout"/>. <see cref="TimeSpan.Zero"/> disables the watchdog — used by
|
||
/// tests that need a Connected driver to stay Connected while reporting non-Healthy.</param>
|
||
/// <param name="shutdownTimeout">Optional bound on the driver's shutdown / dispose on stop and on the
|
||
/// pre-reconnect teardown; defaults to <see cref="DefaultShutdownTimeout"/>. Exists so a test can prove a
|
||
/// hung shutdown is abandoned without waiting 5 s.</param>
|
||
/// <param name="maxWritesInFlight">Optional cap on concurrent writes against the driver; defaults to
|
||
/// <see cref="DefaultMaxWritesInFlight"/>. Writes beyond it queue in arrival order.</param>
|
||
/// <param name="queuedWriteBudget">Optional bound on how long a queued write may wait before it is failed
|
||
/// <c>BadTimeout</c>; defaults to <see cref="DriverWriteBounds.QueueBudget"/> of the write timeout in force.</param>
|
||
/// <param name="initializeTimeout">Optional pessimistic bound on one initialise attempt; defaults to
|
||
/// <see cref="DefaultInitializeTimeout"/>.</param>
|
||
/// <param name="writeTimeout">Optional bound on one write round-trip (its token is cancelled when it elapses;
|
||
/// a token-ignoring write is abandoned <see cref="WriteAbandonGrace"/> later); defaults to
|
||
/// <see cref="DefaultWriteTimeout"/>.</param>
|
||
/// <param name="writeClock">Optional clock for the write bounds; defaults to <see cref="TimeProvider.System"/>.
|
||
/// Exists so a test can step past a bound without waiting for it.</param>
|
||
/// <returns>A <see cref="Akka.Actor.Props"/> instance configured to create the wrapped <see cref="DriverInstanceActor"/>.</returns>
|
||
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<DriverInstanceActor> create) : IIndirectActorProducer
|
||
{
|
||
public Type ActorType => typeof(DriverInstanceActor);
|
||
public ActorBase Produce() => create();
|
||
public void Release(ActorBase actor) { }
|
||
}
|
||
|
||
/// <summary>
|
||
/// Returns true when the driver should boot in DEV-STUB mode based on host platform and
|
||
/// configured roles. Only the legacy v1 in-process <c>"Galaxy"</c> type stays Windows-only:
|
||
/// 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 <c>"GalaxyMxGateway"</c> driver talks gRPC to an external mxaccessgw process,
|
||
/// so it runs on any platform .NET 10 supports — Linux containers included. Not stubbed.
|
||
/// </summary>
|
||
/// <param name="driverType">The type identifier of the driver.</param>
|
||
/// <param name="roles">Operational roles configured for this instance.</param>
|
||
/// <returns>True if the driver should start in DEV-STUB mode; otherwise false.</returns>
|
||
public static bool ShouldStub(string driverType, IEnumerable<string> 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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Initializes a new instance of the <see cref="DriverInstanceActor"/> class.
|
||
/// </summary>
|
||
/// <param name="driver">The driver instance to wrap and manage.</param>
|
||
/// <param name="reconnectInterval">Interval between reconnection attempts.</param>
|
||
/// <param name="startStubbed">If true, start in stub mode for testing or unavailable platforms.</param>
|
||
/// <param name="healthPublisher">Sink for health-change notifications; must not be null.</param>
|
||
/// <param name="clusterId">Cluster identifier forwarded in health snapshots.</param>
|
||
/// <param name="invoker">Phase 6.1 resilience invoker wrapping this driver's capability calls;
|
||
/// defaults to <see cref="NullDriverCapabilityInvoker"/> (pass-through) when null.</param>
|
||
/// <param name="healthPollInterval">Period of the health-poll heartbeat, which also drives the
|
||
/// subscription reconcile; defaults to <see cref="HealthPollInterval"/> when null.</param>
|
||
/// <param name="commsLossTimeout">Comms-loss watchdog threshold; defaults to
|
||
/// <see cref="DefaultCommsLossTimeout"/> when null, and is disabled when zero or negative.</param>
|
||
/// <param name="shutdownTimeout">Bound on the driver's shutdown / dispose; defaults to
|
||
/// <see cref="DefaultShutdownTimeout"/> when null.</param>
|
||
/// <param name="maxWritesInFlight">Cap on concurrent writes; defaults to
|
||
/// <see cref="DefaultMaxWritesInFlight"/> when null or non-positive.</param>
|
||
/// <param name="queuedWriteBudget">Bound on a queued write's wait; defaults to
|
||
/// <see cref="DriverWriteBounds.QueueBudget"/> of the write timeout when null or non-positive.</param>
|
||
/// <param name="initializeTimeout">Pessimistic bound on one initialise attempt; defaults to
|
||
/// <see cref="DefaultInitializeTimeout"/> when null or non-positive.</param>
|
||
/// <param name="writeTimeout">Bound on one write round-trip; defaults to
|
||
/// <see cref="DefaultWriteTimeout"/> when null or non-positive.</param>
|
||
/// <param name="writeClock">Clock for the write bounds; defaults to <see cref="TimeProvider.System"/>.</param>
|
||
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<string, object?>("event", startStubbed ? "spawn_stub" : "spawn"),
|
||
new KeyValuePair<string, object?>("driver_type", driver.DriverType));
|
||
if (startStubbed)
|
||
{
|
||
Context.GetLogger().Info("[DEV-STUB] driver={Name} type={Type}",
|
||
_driverInstanceId, driver.DriverType);
|
||
Become(Stubbed);
|
||
}
|
||
else
|
||
{
|
||
Become(Connecting);
|
||
}
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
protected override void PreStart()
|
||
{
|
||
if (_writeRouteState is not null) _writeIncarnation = _writeRouteState.BeginDriverIncarnation(_driverInstanceId);
|
||
if (_sourcePublisher is not null && _sourceIncarnation is { } previous &&
|
||
!_sourcePublisher.IsDriverIncarnationActive(_driverInstanceId, previous))
|
||
_sourceIncarnation = _sourcePublisher.RegisterDriverIncarnation(_driverInstanceId);
|
||
// 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.
|
||
/// <inheritdoc />
|
||
protected override void PostRestart(Exception reason)
|
||
{
|
||
base.PostRestart(reason);
|
||
Context.Parent.Tell(new ReprovisionRequested(_driverInstanceId, reason.GetType().Name));
|
||
}
|
||
|
||
/// <summary>
|
||
/// Flags the restart before the base implementation runs <see cref="PostStop"/>, so that PostStop
|
||
/// shuts the driver down (the host re-initialises it on <see cref="ReprovisionRequested"/>) but does
|
||
/// NOT dispose it — see <see cref="_restarting"/>.
|
||
/// </summary>
|
||
/// <inheritdoc />
|
||
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<InitializeRequested>(_ => { /* no-op */ });
|
||
Receive<WriteAttribute>(_ => Sender.Tell(new WriteAttributeResult(true, "stubbed")));
|
||
Receive<WriteAttributeWithOutcome>(msg => RejectRich(msg, Sender, "driver is stubbed"));
|
||
// Stubbed drivers have no upstream alarm system — swallow the ack (it's fire-and-forget, no reply).
|
||
Receive<RouteAlarmAck>(_ => { /* stubbed drivers have no alarm backend */ });
|
||
Receive<DisconnectObserved>(_ => { /* stubbed drivers don't disconnect */ });
|
||
Receive<ConnectionLossRaised>(IgnoreConnectionLoss);
|
||
Receive<ForceReconnect>(_ => { /* stubbed drivers don't reconnect */ });
|
||
Receive<SetDesiredSubscriptions>(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<RediscoveryRaised>(HandleRediscoveryRaised);
|
||
Receive<HostStatusRaised>(_ => PublishHealthSnapshot());
|
||
Receive<HealthPollTick>(_ => PublishHealthSnapshot());
|
||
}
|
||
|
||
private void Connecting()
|
||
{
|
||
Receive<InitializeRequested>(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<WriteAttribute>(_ =>
|
||
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
|
||
Receive<WriteAttributeWithOutcome>(msg => RejectRich(msg, Sender, "driver not connected"));
|
||
// A write launched while Connected can finish after the transition out of it; its slot still frees.
|
||
Receive<WriteCompleted>(OnWriteCompleted);
|
||
// An ack arriving while still connecting can't reach the upstream alarm system; drop it and report it
|
||
// failed so the host reverts the locally-committed acknowledge (lmxopcua#760).
|
||
Receive<RouteAlarmAck>(msg =>
|
||
{
|
||
_log.Debug("DriverInstance {Id}: alarm ack arrived during connect — dropped (driver not connected)", _driverInstanceId);
|
||
ReportAckFailed(Sender, msg, "the driver is not connected");
|
||
});
|
||
Receive<InitializeSucceeded>(msg =>
|
||
{
|
||
if (msg.Generation != _initGeneration) return;
|
||
CompleteInitAttempt();
|
||
_log.Info("DriverInstance {Id}: connected", _driverInstanceId);
|
||
Become(Connected);
|
||
PublishHealthSnapshot();
|
||
ResubscribeDesired();
|
||
AttachAlarmSource();
|
||
SubscribeDesiredAlarms();
|
||
});
|
||
Receive<InitializeFailed>(msg =>
|
||
{
|
||
if (msg.Generation != _initGeneration) return;
|
||
CompleteInitAttempt();
|
||
_log.Warning("DriverInstance {Id}: initialize failed: {Reason}", _driverInstanceId, msg.Reason);
|
||
RecordFault();
|
||
Become(Reconnecting);
|
||
PublishHealthSnapshot();
|
||
});
|
||
Receive<SetDesiredSubscriptions>(StoreDisconnectedDesiredSubscriptions);
|
||
Receive<ForceReconnect>(_ => { /* already connecting — no-op */ });
|
||
Receive<ConnectionLossRaised>(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<SubscriptionEstablished>(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<SubscriptionFailed>(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<NativeAlarmRaised>(_ =>
|
||
_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<NativeAlarmInitialState>(_ =>
|
||
_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<SubscribeAlarms>(_ => { });
|
||
Receive<RediscoveryRaised>(HandleRediscoveryRaised);
|
||
Receive<HostStatusRaised>(_ => PublishHealthSnapshot());
|
||
Receive<HealthPollTick>(_ => 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<DisconnectObserved>(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<ConnectionLossRaised>(msg => HandleDisconnectObserved($"driver reported connection lost: {msg.Args.Reason}"));
|
||
Receive<ForceReconnect>(_ =>
|
||
{
|
||
_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<WriteAttribute>(msg => StartOrQueueWrite(msg, Sender));
|
||
Receive<WriteAttributeWithOutcome>(msg => StartOrQueueRichWrite(msg, Sender));
|
||
Receive<WriteCompleted>(OnWriteCompleted);
|
||
ReceiveAsync<RouteAlarmAck>(HandleAcknowledgeAsync);
|
||
ReceiveAsync<Subscribe>(HandleSubscribeAsync);
|
||
ReceiveAsync<Unsubscribe>(_ => { CancelSourceBindingRetry(); return UnsubscribeAsync(); });
|
||
Receive<RetrySourceBindings>(RetrySourceBindingBatch);
|
||
ReceiveAsync<SetDesiredSubscriptions>(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<ResumeDeferredLegacy>(_ =>
|
||
{
|
||
if (_deferredLegacyDemand is not { } desired) return;
|
||
_deferredLegacyDemand = null;
|
||
Self.Tell(desired);
|
||
});
|
||
ReceiveAsync<SubscribeAlarms>(HandleSubscribeAlarmsAsync);
|
||
Receive<DataChangeForward>(OnDataChangeForward);
|
||
Receive<DataChangeBatchForward>(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<NativeAlarmRaised>(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<NativeAlarmInitialState>(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<SubscriptionEstablished>(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<SubscriptionFailed>(msg =>
|
||
_log.Debug("DriverInstance {Id}: resubscribe reported failure: {Reason}", _driverInstanceId, msg.Reason));
|
||
Receive<RediscoveryRaised>(HandleRediscoveryRaised);
|
||
Receive<HostStatusRaised>(_ => PublishHealthSnapshot());
|
||
Receive<HealthPollTick>(_ =>
|
||
{
|
||
// 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();
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// The comms-loss watchdog. Declares a Connected driver disconnected once it has gone
|
||
/// <see cref="_commsLossTimeout"/> without a single successful read <b>while also</b> reporting
|
||
/// itself non-Healthy, by self-sending <see cref="DisconnectObserved"/>.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// <para>
|
||
/// <b>Why this exists.</b> <see cref="DisconnectObserved"/> had no production sender at all. The only
|
||
/// ways into <c>Reconnecting</c> were a failed <em>initial</em> 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
|
||
/// <see cref="ConnectivityChanged"/>, so both were wired to a signal that never fired.
|
||
/// This is also <c>OpcUaClientDriver</c>'s only recovery path for a lost upstream
|
||
/// session (its in-driver SDK reconnect handler was deleted).
|
||
/// </para>
|
||
/// <para>
|
||
/// <b>Why the trip condition is a conjunction, and NOT simply "non-Healthy for N polls".</b>
|
||
/// <see cref="DriverState.Degraded"/> means <em>connected but some data is bad</em> — the enum says
|
||
/// so. Several drivers publish health per-tag inside their read loop (<c>ModbusDriver.ReadAsync</c>
|
||
/// 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.
|
||
/// </para>
|
||
/// <para>
|
||
/// <see cref="DriverHealth.LastSuccessfulRead"/> is the honest liveness evidence: every driver
|
||
/// advances it on any successful read and <em>preserves</em> 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.
|
||
/// </para>
|
||
/// <para>
|
||
/// <b>Drivers this cannot fire for, by construction.</b> <c>CalculationDriver</c> 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.
|
||
/// </para>
|
||
/// <para>
|
||
/// <b>The grace is per CONNECTION (03/S17).</b> The silence baseline is
|
||
/// <c>max(LastSuccessfulRead, _connectedSinceUtc)</c>, not <c>LastSuccessfulRead ?? _connectedSinceUtc</c>.
|
||
/// Because <c>LastSuccessfulRead</c> is <em>preserved</em> 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 <c>??</c> 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
|
||
/// <c>_connectedSinceUtc</c> on every Connected entry was for. Note this <b>paces</b> the cycle, it
|
||
/// does not end it: a permanently half-broken device still reconnects once per threshold, and a
|
||
/// driver that stops reading <i>within</i> a stable connection still trips on schedule (its read
|
||
/// stamp is the later term, exactly as before).
|
||
/// </para>
|
||
/// </remarks>
|
||
/// <param name="health">The health observed on this tick, or null when <see cref="IDriver.GetHealth"/>
|
||
/// threw — a failed observation is not evidence of comms loss, so it never advances the watchdog.</param>
|
||
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}"));
|
||
}
|
||
|
||
/// <summary>
|
||
/// Periodic desired-vs-actual subscription reconcile, riding the existing <c>health-poll</c>
|
||
/// tick. While Connected, a driver that has a desired subscription set but no live handle is
|
||
/// re-subscribed.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// <para>
|
||
/// The desired set is otherwise only (re)applied on a <b>Connected transition</b>
|
||
/// (<see cref="ResubscribeDesired"/>) or on a deploy's <see cref="SetDesiredSubscriptions"/>.
|
||
/// Nothing re-asserted it for a subscription that was lost while the driver <i>stayed</i>
|
||
/// Connected — a failed subscribe whose retry never came, or a handle dropped down an error
|
||
/// path. That is the hole this closes.
|
||
/// </para>
|
||
/// <para>
|
||
/// <b>This is a state-machine consistency check, not a probe.</b> It can only see that this
|
||
/// actor holds no handle; it cannot detect a handle that is present but dead server-side,
|
||
/// because <c>ISubscriptionHandle</c> is opaque (a <c>DiagnosticId</c> string and nothing
|
||
/// else). Detecting that needs a liveness member on <c>ISubscribable</c> implemented across
|
||
/// all eight drivers, each with different subscription mechanics — deliberately deferred
|
||
/// until a real occurrence shows the handle outliving the subscription.
|
||
/// </para>
|
||
/// <para>
|
||
/// Gated on <see cref="ISubscribable"/>: a driver that cannot subscribe at all may still have
|
||
/// been handed a desired set, and re-telling <c>Subscribe</c> to it every tick would fail
|
||
/// every tick, forever.
|
||
/// </para>
|
||
/// <para>
|
||
/// A redundant <c>Subscribe</c> is possible but harmless: a tick sitting in the mailbox ahead
|
||
/// of an already-queued <c>Subscribe</c> observes the same "no handle" state and tells a
|
||
/// second one. <see cref="HandleSubscribeAsync"/> is a <c>ReceiveAsync</c> (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.
|
||
/// </para>
|
||
/// </remarks>
|
||
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));
|
||
}
|
||
|
||
/// <summary>
|
||
/// The native-alarm half of <see cref="ReconcileSubscription"/>. 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 <c>OnAlarmEvent</c> handler
|
||
/// (idempotent attach) and a subscription matching the desired set (<see cref="SubscribeDesiredAlarms"/>
|
||
/// is a no-op while the live handle already matches). Gated on <see cref="IAlarmSource"/> + a
|
||
/// non-empty desired set, so it costs nothing on a driver with no alarm tags.
|
||
/// <para>A persistently failing subscribe backs off: after the n-th consecutive failure the reconcile
|
||
/// skips 2^(n-1) − 1 ticks, capped at <see cref="MaxAlarmRetrySkipTicks"/>, 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.</para>
|
||
/// </summary>
|
||
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<RetryConnect>(_ => 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<WriteAttribute>(_ =>
|
||
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
|
||
Receive<WriteAttributeWithOutcome>(msg => RejectRich(msg, Sender, "driver not connected"));
|
||
Receive<WriteCompleted>(OnWriteCompleted);
|
||
// An ack arriving while reconnecting can't reach the upstream alarm system; drop it and report it
|
||
// failed so the host reverts the locally-committed acknowledge (lmxopcua#760).
|
||
Receive<RouteAlarmAck>(msg =>
|
||
{
|
||
_log.Debug("DriverInstance {Id}: alarm ack arrived during reconnect — dropped (driver not connected)", _driverInstanceId);
|
||
ReportAckFailed(Sender, msg, "the driver is not connected");
|
||
});
|
||
Receive<InitializeSucceeded>(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<InitializeFailed>(msg =>
|
||
{
|
||
if (msg.Generation == _initGeneration) CompleteInitAttempt();
|
||
});
|
||
Receive<SetDesiredSubscriptions>(StoreDisconnectedDesiredSubscriptions);
|
||
Receive<ForceReconnect>(_ => { /* already reconnecting — no-op */ });
|
||
Receive<ConnectionLossRaised>(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<DisconnectObserved>(_ => { /* 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<SubscriptionEstablished>(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<SubscriptionFailed>(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<NativeAlarmRaised>(_ =>
|
||
_log.Debug("DriverInstance {Id}: native alarm arrived during reconnect — dropped (feed re-delivers)", _driverInstanceId));
|
||
Receive<NativeAlarmInitialState>(_ =>
|
||
_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<SubscribeAlarms>(_ => { });
|
||
Receive<RediscoveryRaised>(HandleRediscoveryRaised);
|
||
Receive<HostStatusRaised>(_ => PublishHealthSnapshot());
|
||
Receive<HealthPollTick>(_ => PublishHealthSnapshot());
|
||
Timers.StartPeriodicTimer("retry-connect", RetryConnect.Instance, _reconnectInterval);
|
||
}
|
||
|
||
/// <param name="driverConfigJson">The config blob to initialise the driver with.</param>
|
||
/// <param name="teardownFirst">
|
||
/// When true, <see cref="IDriver.ShutdownAsync"/> is awaited before <see cref="IDriver.InitializeAsync"/>
|
||
/// — the sequence every driver's own <c>ReinitializeAsync</c> uses. Set on the <c>Reconnecting</c>
|
||
/// retry path, because several drivers <em>overwrite</em> their transport field in
|
||
/// <c>InitializeAsync</c> without disposing the previous one: <c>ModbusDriver</c> assigns
|
||
/// <c>_transport = _transportFactory(...)</c> and <c>MqttDriver</c> assigns <c>_connection</c>, both
|
||
/// over an <see cref="IAsyncDisposable"/>. 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.
|
||
/// </param>
|
||
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();
|
||
}
|
||
});
|
||
}
|
||
|
||
/// <summary>Releases the single-flight gate once the in-flight attempt's result has been honoured.</summary>
|
||
private void CompleteInitAttempt()
|
||
{
|
||
_initInFlight = false;
|
||
_initCts = null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Launches a write against the driver off the mailbox, or queues it when
|
||
/// <see cref="_maxWritesInFlight"/> 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
|
||
/// (<see cref="RunWriteAsync"/>) replies to the captured sender from the thread pool and then
|
||
/// self-sends <see cref="WriteCompleted"/> to free its slot.
|
||
/// </summary>
|
||
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<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
var cancellation = new CancellationTokenSource(timeout, clock);
|
||
// This task represents the entire physical invocation, including synchronous work before a driver
|
||
// returns its task. Its permit and payload live until that invocation really exits.
|
||
reservation.Observe(physical.Task, msg.Claim, new WriteLifetime(msg.Ticket, cancellation));
|
||
var attempt = Task.Run(async () =>
|
||
{
|
||
try
|
||
{
|
||
return await invoker.ExecuteWriteAsync(hostKey, false, ct =>
|
||
{
|
||
WriteRequest[] request;
|
||
try { request = [new WriteRequest(msg.Ticket.Proof.DriverReference, DriverValue(msg.Ticket.Value))]; }
|
||
catch
|
||
{
|
||
var noCall = msg.Claim.Complete(RichRejected) ? RichRejected : msg.Claim.CurrentOutcome ?? RichUnknown;
|
||
if (!msg.Claim.IsDispatched) physical.TrySetResult(noCall);
|
||
return ValueTask.FromResult(noCall);
|
||
}
|
||
var rejection = gate.TryCommit(msg.Ticket, msg.Claim);
|
||
if (rejection is not null)
|
||
{
|
||
msg.Claim.Complete(rejection);
|
||
physical.TrySetResult(rejection);
|
||
return ValueTask.FromResult(rejection);
|
||
}
|
||
// The commit above is the linearization point. No await or external callback occurs
|
||
// between that commit and the invocation below; preemption after commit is post-dispatch.
|
||
try
|
||
{
|
||
if (driver is IWriteOutcomeCapability rich)
|
||
_ = ObserveRichDriver(rich.WriteWithOutcomesAsync(request, ct), physical);
|
||
else
|
||
_ = ObserveLegacyDriver(((IWritable)driver).WriteAsync(request, ct), physical);
|
||
}
|
||
catch { physical.TrySetResult(RichUnknown); }
|
||
return new ValueTask<DataWriteOutcome>(physical.Task);
|
||
}, cancellation.Token).ConfigureAwait(false);
|
||
}
|
||
catch
|
||
{
|
||
var outcome = msg.Claim.Complete(RichRejected) ? RichRejected : RichUnknown;
|
||
if (outcome == RichRejected) physical.TrySetResult(outcome);
|
||
else msg.Claim.Complete(outcome);
|
||
return outcome;
|
||
}
|
||
});
|
||
try
|
||
{
|
||
var outcome = await attempt.WaitAsync(timeout + WriteAbandonGrace(timeout), clock).ConfigureAwait(false);
|
||
replyTo.Tell(outcome);
|
||
}
|
||
catch
|
||
{
|
||
var outcome = msg.Claim.Complete(RichRejected) ? RichRejected : RichUnknown;
|
||
if (outcome == RichRejected) physical.TrySetResult(outcome);
|
||
else msg.Claim.Complete(outcome);
|
||
replyTo.Tell(outcome);
|
||
}
|
||
finally { self.Tell(new WriteCompleted(msg.Ticket.Proof.DriverReference, incarnation)); }
|
||
}
|
||
|
||
private static async Task ObserveRichDriver(Task<IReadOnlyList<DataWriteOutcome>> task,
|
||
TaskCompletionSource<DataWriteOutcome> physical)
|
||
{
|
||
try
|
||
{
|
||
var result = await task.ConfigureAwait(false);
|
||
var outcome = result is { Count: 1 } ? result[0] : RichUnknown;
|
||
if (outcome.State == DataWriteState.RejectedBeforeDispatch || outcome.State == DataWriteState.Unspecified) outcome = RichUnknown;
|
||
physical.TrySetResult(outcome);
|
||
}
|
||
catch { physical.TrySetResult(RichUnknown); }
|
||
}
|
||
|
||
private static async Task ObserveLegacyDriver(Task<IReadOnlyList<WriteResult>> task,
|
||
TaskCompletionSource<DataWriteOutcome> physical)
|
||
{
|
||
try
|
||
{
|
||
var result = await task.ConfigureAwait(false);
|
||
physical.TrySetResult(result is { Count: 1 } && IsGoodStatus(result[0].StatusCode)
|
||
? new(DataWriteState.AcceptedUnconfirmed, result[0].StatusCode, null) : RichUnknown);
|
||
}
|
||
catch { physical.TrySetResult(RichUnknown); }
|
||
}
|
||
|
||
private static object? DriverValue(DataValue value) => value.Kind switch
|
||
{
|
||
DataValueKind.Null => null,
|
||
DataValueKind.Bytes => value.GetBytes().ToArray(),
|
||
DataValueKind.Array => ToDriverArray(value),
|
||
_ => value.GetScalar(),
|
||
};
|
||
|
||
private static Array ToDriverArray(DataValue value)
|
||
{
|
||
var elements = value.GetArray();
|
||
var type = value.ArrayElementKind switch
|
||
{
|
||
DataValueKind.Boolean => typeof(bool), DataValueKind.Int8 => typeof(sbyte), DataValueKind.Int16 => typeof(short),
|
||
DataValueKind.Int32 => typeof(int), DataValueKind.Int64 => typeof(long), DataValueKind.UInt8 => typeof(byte),
|
||
DataValueKind.UInt16 => typeof(ushort), DataValueKind.UInt32 => typeof(uint), DataValueKind.UInt64 => typeof(ulong),
|
||
DataValueKind.Float => typeof(float), DataValueKind.Double => typeof(double), DataValueKind.String => typeof(string),
|
||
DataValueKind.Timestamp => typeof(DateTimeOffset), DataValueKind.Guid => typeof(Guid),
|
||
_ => throw new ArgumentException("Unsupported array element kind."),
|
||
};
|
||
var dimensions = value.Dimensions!.ToArray();
|
||
var result = Array.CreateInstance(type, dimensions);
|
||
var index = new int[dimensions.Length];
|
||
foreach (var element in elements)
|
||
{
|
||
result.SetValue(element, index);
|
||
for (var d = index.Length - 1; d >= 0; d--)
|
||
{
|
||
if (++index[d] < dimensions[d]) break;
|
||
index[d] = 0;
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
private void LaunchWrite(IWritable writable, WriteAttribute msg, IActorRef replyTo)
|
||
{
|
||
_writesInFlight++;
|
||
_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<WriteResult> 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));
|
||
}
|
||
}
|
||
|
||
/// <summary>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.</summary>
|
||
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;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Fails a write that has waited longer than <see cref="_queuedWriteBudget"/> 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 (<see cref="DriverWriteBounds.HostAsk"/>), 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.
|
||
/// </summary>
|
||
/// <returns>True when the write was expired (and answered).</returns>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Replies to every queued write with <paramref name="reason"/>; called on each exit from
|
||
/// <c>Connected</c>. In-flight writes are left to finish — they already hold the device and reply with its
|
||
/// real outcome.</summary>
|
||
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);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Forwards an inbound native-condition acknowledge (routed by <see cref="DriverHostActor"/> from a
|
||
/// resolved condition NodeId) to the driver's <see cref="IAlarmSource.AcknowledgeAsync"/>. The driver
|
||
/// correlates on <see cref="AlarmAcknowledgeRequest.ConditionId"/> (= the authored alarm
|
||
/// full-reference); <see cref="AlarmAcknowledgeRequest.SourceNodeId"/> 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
|
||
/// <see cref="AlarmAckFailed"/> so the host reverts the condition to unacknowledged (lmxopcua#760) —
|
||
/// otherwise the node showed Acknowledged for an alarm the upstream system never acknowledged.
|
||
/// </summary>
|
||
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})");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
internal static readonly TimeSpan AckConfirmationCeiling = TimeSpan.FromMinutes(3);
|
||
|
||
/// <summary>
|
||
/// Awaits <see cref="IAlarmAcknowledgeConfirmation.ConfirmAcknowledgedAsync"/> off the actor context and, when
|
||
/// the upstream does not confirm, reports <see cref="AlarmAckFailed"/> so the host reverts the condition to
|
||
/// unacknowledged — the same report an <see cref="IAlarmSource.AcknowledgeAsync"/> failure makes. Reads no actor
|
||
/// state: everything it needs is captured by the caller on the actor thread.
|
||
/// </summary>
|
||
private static async Task RunAckConfirmationAsync(
|
||
IAlarmAcknowledgeConfirmation confirmer, IReadOnlyList<AlarmAcknowledgeRequest> 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})");
|
||
}
|
||
}
|
||
|
||
/// <summary>Tells <paramref name="replyTo"/> an <see cref="AlarmAckFailed"/> when the ack names a condition
|
||
/// NodeId (lmxopcua#760); a no-op for an ack routed without one.</summary>
|
||
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<StagedEvent> _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<DataChangeItem> 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<DataChangeItem> 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<AcquisitionSubscriptionResult> _completion =
|
||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
private readonly TaskCompletionSource<bool> _finished = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
private AcquisitionSubscriptionResult? _result;
|
||
private bool _abandoned, _settled;
|
||
internal Task<AcquisitionSubscriptionResult> Completion => _completion.Task;
|
||
internal Task<bool> 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<AcquisitionBatch> callback) => _ = ObserveAsync(Task.Run(() =>
|
||
source.SubscribeAcquisitionAsync(request, callback, _stop.Token)));
|
||
|
||
private async Task ObserveAsync(Task<AcquisitionSubscriptionResult> 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<AcquisitionDemandApplied> 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<string>(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<bool> 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();
|
||
}
|
||
}
|
||
|
||
/// <summary>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.
|
||
/// <para>Not for the data Unsubscribe / re-subscribe path — that uses <see cref="DetachDataSubscription"/>
|
||
/// instead.</para></summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Tear down the data-change (per-tag AND batch) handlers + null the data handle, leaving the
|
||
/// native-alarm handler and handle alone.
|
||
/// <para>The data Unsubscribe / re-subscribe path used to run the full <see cref="DetachSubscription"/>,
|
||
/// so every deploy that re-subscribed a Connected driver's DATA also unhooked <c>OnAlarmEvent</c> 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.</para>
|
||
/// <para>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.</para></summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Subscribe the driver's native alarm event (if it is an <see cref="IAlarmSource"/>),
|
||
/// marshaling each transition to the actor thread. Idempotent; mirrors the OnDataChange attach.</summary>
|
||
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;
|
||
}
|
||
}
|
||
|
||
/// <summary>Subscribe the driver's <see cref="IRediscoverable.OnRediscoveryNeeded"/> (if it is one),
|
||
/// marshaling each raise to the actor thread. Idempotent; mirrors <see cref="AttachAlarmSource"/>.
|
||
/// <para>Attached once in <c>PreStart</c> 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.</para></summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Symmetric teardown, called from PostStop. Load-bearing: the <see cref="IDriver"/> 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 <c>Self</c>.</summary>
|
||
private void DetachRediscoverySource()
|
||
{
|
||
if (_driver is IRediscoverable src && _rediscoveryHandler is not null)
|
||
src.OnRediscoveryNeeded -= _rediscoveryHandler;
|
||
_rediscoveryHandler = null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Subscribe the driver's <see cref="IDriverConnectionLossSource.ConnectionLost"/>, if it is one,
|
||
/// marshalling each raise to the actor thread — actor state is never touched on the driver's thread. Attached
|
||
/// once in <c>PreStart</c> and detached in <c>PostStop</c>, like <see cref="AttachRediscoverySource"/>: the
|
||
/// <see cref="IDriver"/> instance can outlive this actor, so a per-connect attach would leak a handler (holding
|
||
/// a dead <c>Self</c>) per respawn.
|
||
/// </summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Symmetric teardown, called from PostStop — same leak argument as <see cref="DetachRediscoverySource"/>.</summary>
|
||
private void DetachConnectionLossSource()
|
||
{
|
||
if (_driver is IDriverConnectionLossSource src && _connectionLossHandler is not null)
|
||
src.ConnectionLost -= _connectionLossHandler;
|
||
_connectionLossHandler = null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
private void IgnoreConnectionLoss(ConnectionLossRaised msg) =>
|
||
_log.Debug("DriverInstance {Id}: driver reported connection lost ({Reason}) while not connected — ignored",
|
||
_driverInstanceId, msg.Args.Reason);
|
||
|
||
/// <summary>
|
||
/// Connected → Reconnecting on an observed disconnect — from the watchdog or a driver's definitive
|
||
/// <see cref="IDriverConnectionLossSource.ConnectionLost"/>.
|
||
/// </summary>
|
||
private void HandleDisconnectObserved(string reason)
|
||
{
|
||
_log.Warning("DriverInstance {Id}: disconnect observed ({Reason}); reconnecting", _driverInstanceId, reason);
|
||
DetachSubscription();
|
||
FailQueuedWrites("driver not connected");
|
||
RecordFault();
|
||
Become(Reconnecting);
|
||
PublishHealthSnapshot();
|
||
}
|
||
|
||
/// <summary>Subscribe the driver's <see cref="IHostConnectivityProbe.OnHostStatusChanged"/> (if it is
|
||
/// one), marshaling each transition to the actor thread. Idempotent; mirrors
|
||
/// <see cref="AttachRediscoverySource"/>, including the PreStart-not-per-connect placement — a probe
|
||
/// loop can report a host down while the driver itself is between connects.</summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Symmetric teardown, called from PostStop — same leak argument as
|
||
/// <see cref="DetachRediscoverySource"/>.</summary>
|
||
private void DetachHostStatusSource()
|
||
{
|
||
if (_driver is IHostConnectivityProbe src && _hostStatusHandler is not null)
|
||
src.OnHostStatusChanged -= _hostStatusHandler;
|
||
_hostStatusHandler = null;
|
||
}
|
||
|
||
/// <summary>Current per-host connectivity, or null when the driver is not an
|
||
/// <see cref="IHostConnectivityProbe"/>. 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.
|
||
/// <para><c>GetHostStatuses()</c> is called UNGUARDED (not through <see cref="_invoker"/>) on purpose —
|
||
/// it is a pure in-memory snapshot with no I/O, which is exactly why
|
||
/// <c>UnwrappedCapabilityCallAnalyzer</c> 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.</para></summary>
|
||
private IReadOnlyList<HostConnectivityStatus>? 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;
|
||
}
|
||
}
|
||
|
||
/// <summary>What the driver skipped when it last built its tag table, or null when it is not an
|
||
/// <see cref="ISkippedTagReporter"/>. Pulled fresh for the same reason as
|
||
/// <see cref="CurrentHostStatuses"/> — the driver owns the answer, and a cached copy here would be a
|
||
/// second source of truth to keep in sync across every reinitialise.
|
||
/// <para>Called UNGUARDED (not through <see cref="_invoker"/>): 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.</para></summary>
|
||
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;
|
||
}
|
||
}
|
||
|
||
/// <summary>Bounded driver diagnostics, or null when the driver is not an <see cref="IDriverDiagnostics"/>
|
||
/// implementation. Pulled fresh and called UNGUARDED for the same reasons as
|
||
/// <see cref="CurrentSkippedTags"/>; a throwing implementation loses only the diagnostics.</summary>
|
||
private IReadOnlyDictionary<string, string>? 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;
|
||
}
|
||
}
|
||
|
||
/// <summary>Value digest of the diagnostics bag for the publish fingerprint. Null in, null out. The bag is
|
||
/// already in ordinal key order (<see cref="DriverDiagnostics.Bound"/>), so equal facts digest equally.</summary>
|
||
private static string? DiagnosticsDigest(IReadOnlyDictionary<string, string>? d) =>
|
||
d is null ? null : string.Join('|', d.Select(kv => $"{kv.Key}={kv.Value}"));
|
||
|
||
/// <summary>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.
|
||
/// <para><b>Advisory only.</b> The served address space is deliberately NOT rebuilt: v3 authors raw tags
|
||
/// explicitly through the <c>/raw</c> 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.</para></summary>
|
||
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();
|
||
}
|
||
|
||
/// <summary>Symmetric teardown — called from <see cref="DetachSubscription"/> and PostStop so a stale
|
||
/// handler never pushes to a disconnected actor.</summary>
|
||
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<string>();
|
||
_alarmSubscribeFailures = 0;
|
||
_alarmRetrySkipTicks = 0;
|
||
}
|
||
|
||
/// <summary>Establish the native-alarm subscription that un-gates an <see cref="IAlarmSource"/> driver's
|
||
/// feed — the driver suppresses <see cref="IAlarmSource.OnAlarmEvent"/> until at least one alarm
|
||
/// subscription exists. Self-sends the async <see cref="SubscribeAlarms"/> the Connected behaviour
|
||
/// handles. Idempotent: a no-op unless the driver is an <see cref="IAlarmSource"/>, alarm refs are
|
||
/// desired, and no subscription is yet established.</summary>
|
||
private void SubscribeDesiredAlarms()
|
||
{
|
||
if (_driver is IAlarmSource && _desiredAlarmRefs.Count > 0 && AlarmSubscriptionIsStale())
|
||
Self.Tell(new SubscribeAlarms());
|
||
}
|
||
|
||
/// <summary>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 <see cref="_subscribedAlarmRefs"/>.</summary>
|
||
private bool AlarmSubscriptionIsStale() =>
|
||
_alarmSubscriptionHandle is null ||
|
||
!_subscribedAlarmRefs.SequenceEqual(_desiredAlarmRefs, StringComparer.Ordinal);
|
||
|
||
/// <summary>Calls the driver's <see cref="IAlarmSource.SubscribeAlarmsAsync"/> (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.</summary>
|
||
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<string>();
|
||
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);
|
||
}
|
||
}
|
||
|
||
|
||
/// <summary>Records the host's desired subscription set without touching the live subscription.
|
||
/// The set is (re)applied by <see cref="ResubscribeDesired"/> on the next <c>Connected</c> entry.</summary>
|
||
private void StoreDesiredSubscriptions(SetDesiredSubscriptions msg)
|
||
{
|
||
_desiredRefs = msg.FullReferences;
|
||
_desiredInterval = msg.PublishingInterval;
|
||
_desiredAlarmRefs = msg.AlarmReferences ?? Array.Empty<string>();
|
||
}
|
||
|
||
private void StoreDisconnectedDesiredSubscriptions(SetDesiredSubscriptions msg)
|
||
{
|
||
if (msg.RequireAcquisition)
|
||
Sender.Tell(new AcquisitionDemandApplied(msg.DesiredRevision, msg.ProducerIncarnation, TimeSpan.Zero, false));
|
||
else StoreDesiredSubscriptions(msg);
|
||
}
|
||
|
||
/// <summary>Re-establish the desired subscription after (re)connecting. Self-sends the one-shot
|
||
/// <see cref="Subscribe"/> the Connected behaviour already handles (which drops any prior handle
|
||
/// first), so values resume streaming after a reconnect or redeploy without host involvement.</summary>
|
||
private void ResubscribeDesired()
|
||
{
|
||
if (_desiredAcquisition is { } acquisition) Self.Tell(acquisition);
|
||
else if (_desiredRefs.Count > 0) Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
|
||
}
|
||
|
||
/// <summary>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.
|
||
/// <para>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
|
||
/// <c>0x80000000</c> — so no driver's sub-code ever reached a client, and the status constants each
|
||
/// driver maintains were diagnostic in logs only.</para></summary>
|
||
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) }));
|
||
}
|
||
|
||
/// <summary>Forward one batch-capable driver production burst to the parent as a single message.
|
||
/// <para>Every item's status code and timestamp ride through exactly as
|
||
/// <see cref="OnDataChangeForward"/> carries them for a per-tag driver (timestamps come from the
|
||
/// driver's snapshot, never from this actor's clock).</para></summary>
|
||
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);
|
||
|
||
/// <summary>Resolve the resilience-pipeline host key for a single driver-side reference. Multi-host
|
||
/// drivers (e.g. Modbus across N PLCs) implement <see cref="IPerCallHostResolver"/> 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.</summary>
|
||
private string ResolveHost(string reference) =>
|
||
_driver is IPerCallHostResolver resolver ? resolver.ResolveHost(reference) : _driverInstanceId;
|
||
|
||
/// <summary>Records a transition into a Faulted / error state for the 5-minute sliding counter.</summary>
|
||
private void RecordFault()
|
||
{
|
||
_faultTimestamps.Enqueue(DateTime.UtcNow);
|
||
}
|
||
|
||
/// <summary>Returns how many fault transitions occurred in the last 5 minutes.</summary>
|
||
private int ErrorCount5Min()
|
||
{
|
||
var cutoff = DateTime.UtcNow.AddMinutes(-5);
|
||
while (_faultTimestamps.Count > 0 && _faultTimestamps.Peek() < cutoff)
|
||
_faultTimestamps.Dequeue();
|
||
return _faultTimestamps.Count;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Polls <see cref="IDriver.GetHealth"/> and forwards the snapshot to the health publisher.
|
||
/// Called on every observable state change and by the periodic <see cref="HealthPollTick"/>
|
||
/// 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 <c>DriverStatusHub.JoinDriver</c> which reads the store directly.
|
||
/// </summary>
|
||
/// <returns>The health observed on this call, or null when <see cref="IDriver.GetHealth"/> 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.</returns>
|
||
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;
|
||
}
|
||
|
||
/// <summary>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.
|
||
/// <para>Ordered by host name because a driver is free to return its hosts in any order (several build
|
||
/// the list from a <c>Dictionary</c>), and an order flip would otherwise read as a real transition and
|
||
/// re-publish forever.</para></summary>
|
||
private static string? HostStatusDigest(IReadOnlyList<HostConnectivityStatus>? statuses) =>
|
||
statuses is null
|
||
? null
|
||
: string.Join('|', statuses
|
||
.OrderBy(s => s.HostName, StringComparer.Ordinal)
|
||
.Select(s => $"{s.HostName}={s.State}@{s.LastChangedUtc:O}"));
|
||
|
||
/// <summary>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.
|
||
/// <para>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.</para></summary>
|
||
private static string? SkippedTagDigest(SkippedTagReport? report) =>
|
||
report is null
|
||
? null
|
||
: $"{report.AuthoredCount}/{report.SkippedCount}:" +
|
||
string.Join('|', report.Sample.Select(s => $"{s.RawPath}={s.Reason}"));
|
||
|
||
/// <summary>Fingerprint of the last <see cref="PublishHealthSnapshot"/> call; null until first publish.</summary>
|
||
private (DriverState State, DateTime? LastSuccess, string? LastError, int ErrorCount,
|
||
DateTime? RediscoveryNeededUtc, string? HostStatusDigest, string? SkippedTagDigest,
|
||
string? DiagnosticsDigest)? _lastPublishedFingerprint;
|
||
|
||
/// <inheritdoc />
|
||
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<string, object?>("event", "stop"),
|
||
new KeyValuePair<string, object?>("driver_type", _driver.DriverType));
|
||
}
|
||
|
||
/// <summary>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.</summary>
|
||
private static readonly TimeSpan MinDisposeBudget = TimeSpan.FromMilliseconds(250);
|
||
|
||
/// <summary>Final teardown of the wrapped driver: <see cref="IAsyncDisposable"/> preferred, else
|
||
/// <see cref="IDisposable"/>, 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
|
||
/// <see cref="IDriver.ShutdownAsync"/>.</summary>
|
||
/// <param name="bound">The remaining PostStop budget available to an async dispose.</param>
|
||
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<string, object?>("event", "dispose"),
|
||
new KeyValuePair<string, object?>("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);
|
||
}
|
||
}
|
||
}
|