Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs
T
Joseph Doherty f0c6cf9640
v2-ci / unit-tests (push) Has been cancelled
fix(security): running drivers refuse out-of-namespace credential refs at resolve time (#834)
The #815 warn-only compatibility window is over. A running Galaxy driver
(InitializeAsync, every gateway ReopenAsync, the ack fallback password) and a
running OpcUaClient driver (session open) now refuse an out-of-namespace
credential reference with the same CredentialReferenceException that save,
deploy (CredentialReferenceOutOfScope), Test Connect and browse already raise,
before any store / environment / file read and before any endpoint is dialled.
The one existing scope check (CredentialReferences.Parse/ResolveAsync) is now
the only path; nothing new was added.

Removed:
- LegacyCredentialReferenceTracker (Core.Abstractions), its rate-limited WARN
  and the credential-compat:<field> diagnostics entry.
- The per-driver Legacy* resolve methods and every `legacy` parameter
  (GalaxySecretRef, GalaxyAckCredentialResolver, OpcUaUserIdentityFactory,
  OpcUaUserCertificatePaths, OpcUaClientSecretResolution).
- IDriverDiagnostics on GalaxyDriver / OpcUaClientDriver (it only carried the
  tracker's entries).
- The tracker also kept a pre-#836 absolute UserCertificatePath loading on a
  running OpcUaClient driver; that is refused now too.

Preflight / banner decision: KEPT, as a hard error. The Running source
(driver-health credential-compat entries) and CredentialReferenceBannerModel
are gone with the tracker, but the ConfigDb scan still tells an operator
something no other surface does: a Deployed finding is now a driver that is
not connecting, a Draft finding is a deploy the gate will refuse - named
before anyone deploys, e.g. after restoring an old ConfigDb backup or
importing a pre-#815 config. It also carries the #835 cross-instance and
#836/#850 path checks. CredentialReferencePreflightService now logs one Error
per finding (was Warning) with no warn-only wording, and the /raw banner is
alert-danger.

DEV and QA ConfigDbs hold no Galaxy/OpcUaClient driver (checked 2026-11-13);
no production install exists.

Tests: GalaxyDriverLegacyCredentialTests replaced by
GalaxyDriverCredentialScopeTests; new OpcUaClientDriverCredentialScopeTests;
tracker tests in OpcUaClientSecretResolutionTests /
OpcUaClientUserCertificatePathTests deleted; AdminUI preflight tests drop the
Running/banner-model cases and assert Error level. Against the old code the
new refusal tests fail (Galaxy 5/6, OpcUaClient 4/5; the two positive controls
pass on both).

docs/security.md: the migration table now says running drivers refuse; the
warn-only section is replaced by "The compatibility window is over".

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-13 02:06:43 -05:00

3084 lines
169 KiB
C#

using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.MxGateway.Client;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Health;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy;
/// <summary>
/// In-process .NET 10 Galaxy driver — the only Galaxy backend since PR 7.2 retired
/// the legacy <c>Galaxy.Host</c> / <c>Galaxy.Proxy</c> / <c>Galaxy.Shared</c>
/// projects and the <c>OtOpcUaGalaxyHost</c> Windows service. Implements the full
/// capability surface: <see cref="ITagDiscovery"/>, <see cref="IReadable"/>,
/// <see cref="IWritable"/>, <see cref="ISubscribable"/>, <see cref="IRediscoverable"/>,
/// <see cref="IHostConnectivityProbe"/>, and <see cref="IAlarmSource"/>. Galaxy
/// access flows through the in-process driver over gRPC to the separately
/// installed <c>mxaccessgw</c> gateway (sibling repo), which owns the MXAccess
/// COM apartment server-side.
/// </summary>
/// <remarks>
/// <para>
/// Registered as a Tier A in-process driver alongside Modbus / S7 / etc. via
/// <see cref="GalaxyDriverFactoryExtensions"/> under driver-type name
/// "GalaxyMxGateway".
/// </para>
/// <para>
/// Tests inject capability seams (<see cref="IGalaxyHierarchySource"/>,
/// <see cref="IGalaxyDataReader"/>, <see cref="IGalaxyDataWriter"/>,
/// <see cref="IGalaxySubscriber"/>, <see cref="IGalaxyAlarmAcknowledger"/>,
/// <see cref="IGalaxyAlarmFeed"/>) via the internal ctor so capability flow
/// can be exercised without a real gw round-trip.
/// </para>
/// </remarks>
public sealed class GalaxyDriver
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable
{
/// <summary>Authored tags this driver could not dial — a TagConfig with no usable
/// <c>attributeRef</c> has no MXAccess address to bind.</summary>
private readonly SkippedTagLedger _skippedTags = new();
/// <inheritdoc />
public SkippedTagReport? GetSkippedTags() => _skippedTags.Snapshot();
private readonly string _driverInstanceId;
private readonly GalaxyDriverOptions _options;
private readonly ILogger<GalaxyDriver> _logger;
// Resolves the Gateway.ApiKeySecretRef secret: arm through the shared encrypted store.
// Injected via ctor (the production factory pulls it from DI). The internal test ctor
// defaults it to a null-object resolver so the 45 seam-injecting test call sites keep
// compiling; those tests never use a secret: ref (they inject seams or use env/file/literal).
private readonly ISecretResolver _secretResolver;
// PR 4.1 — IGalaxyHierarchySource is the test seam for browse. When null, the driver
// lazily builds a GatewayGalaxyHierarchySource around a GalaxyRepositoryClient on
// first DiscoverAsync. Tests inject a fake source via the internal ctor to exercise
// GalaxyDiscoverer's translation logic without a real gRPC channel.
private IGalaxyHierarchySource? _hierarchySource;
private GalaxyRepositoryClient? _ownedRepositoryClient;
// IGalaxyDataReader is the test seam for IReadable. Production ReadAsync calls
// ReadViaSubscribeOnceAsync (SubscribeBulk + first-event wait + Unsubscribe) through
// the live GalaxyMxSession built by InitializeAsync; no legacy-host backend exists.
// When a test injects a reader via the internal ctor, that injected reader is used
// instead so capability flow can be exercised without a real gRPC round-trip.
private IGalaxyDataReader? _dataReader;
// PR 4.3 — IGalaxyDataWriter is the test seam for IWritable. Production wraps
// GalaxyMxSession via GatewayGalaxyDataWriter (Write / WriteSecured routing). The
// per-tag SecurityClassification map is populated during ITagDiscovery and consumed
// here at write time.
private IGalaxyDataWriter? _dataWriter;
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, SecurityClassification>
_securityByFullRef = new(StringComparer.OrdinalIgnoreCase);
// v3 RawPath keying. The server hands every read/write/subscribe reference as a RawPath; MXAccess
// dials the Galaxy attributeRef (tag_name.AttributeName). These two tables — built once in the ctor
// from options.RawTags (each entry's TagConfig carries the camelCase "attributeRef" key) — bridge the
// two identity domains at the driver boundary:
// _attributeRefByRawPath : RawPath -> attributeRef (forward dial: read/write/subscribe/ack)
// _rawTagByAttributeRef : attributeRef -> RawTagEntry (reverse + WriteIdempotent: discovery,
// OnDataChange, alarm ConditionId)
// Both fall back to identity on a miss, so the live-browse discovery path (no authored tags) and any
// synthetic alarm sub-ref (attributeRef.InAlarm, never an authored RawPath) dial straight through
// unchanged — reproducing pre-v3 behaviour exactly.
private readonly Dictionary<string, string> _attributeRefByRawPath;
private readonly Dictionary<string, RawTagEntry> _rawTagByAttributeRef;
// lmxopcua#895: the gateway alarm feed names an alarm by its provider-qualified reference
// ("Galaxy!<Area>.<tag_name>.<Attribute>"), but a tag authored through the AdminUI Galaxy picker carries
// the plain attributeRef ("<tag_name>.<Attribute>"). When a transition resolves through its
// SourceObjectReference instead of the full reference, the full reference is remembered here per RawPath
// so an acknowledge of that condition dials the reference the gateway's AcknowledgeAlarm accepts (it
// refuses a non-provider reference) and the #869 confirmation watch matches the feed's transitions.
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, string> _alarmFullRefByRawPath =
new(StringComparer.OrdinalIgnoreCase);
// lmxopcua#895 review: a tag hand-authored with the provider-qualified form ("Galaxy!<Area>.<tag>.<Attr>")
// indexed by its area-free "<tag>.<Attr>", so its alarms still resolve after Galaxy moves the object to
// another area (the feed's full reference then names the new area and no longer matches the authored one).
// Built once with the raw-tag tables; read-only afterwards.
private readonly Dictionary<string, RawTagEntry> _rawTagByAreaFreeRef;
// PR 4.4 — subscription lifecycle. The pump consumes the gw event stream and fans
// out OnDataChange events to every registered driver subscription via the registry's
// reverse map. The subscriber is the test seam — production uses
// GatewayGalaxySubscriber over a connected GalaxyMxSession.
private IGalaxySubscriber? _subscriber;
private readonly SubscriptionRegistry _subscriptions = new();
// #862: subscriptions a reconnect left without advises because Reconnect.ReplayOnSessionLost=false.
// Their tags were published BadNoCommunication and the driver reports Degraded while any of them is
// still registered. Cleared by UnsubscribeAsync (the host re-subscribes on every deploy / re-init) and
// by the runtime teardown; GetHealth also prunes ids the registry no longer holds, so an unsubscribe
// racing the replay can never pin Degraded.
private readonly System.Collections.Concurrent.ConcurrentDictionary<long, byte> _strandedSubscriptions = new();
private EventPump? _eventPump;
private readonly Lock _pumpLock = new();
/// <summary>
/// Re-entry gate for the replay-gap re-snapshot (0 = idle, 1 = running). Interlocked
/// rather than a lock because the setter runs on the event pump's read loop and must
/// never block it.
/// </summary>
private int _resnapshotInFlight;
// IAlarmSource implementation. Production-side acks route through
// GatewayGalaxyAlarmAcknowledger which calls the session-less
// MxGatewayClient.AcknowledgeAlarmAsync RPC; alarm transitions arrive on the
// gateway's session-less StreamAlarms feed via GatewayGalaxyAlarmFeed. Tests inject
// IGalaxyAlarmAcknowledger + IGalaxyAlarmFeed via the internal ctor to exercise the
// wiring without a running gateway. This driver bridges the feed's OnAlarmTransition
// onto IAlarmSource.OnAlarmEvent.
private IGalaxyAlarmAcknowledger? _alarmAcknowledger;
// lmxopcua#749: resolves the Galaxy account each acknowledge authenticates as (API key identity →
// fallback account → refused). Built in the ctor — it needs only options + the secret resolver.
private readonly IGalaxyAckCredentialResolver _ackCredentialResolver;
// lmxopcua#765: the cached key → has-Galaxy-identity set the synchronous ack pre-check reads (no I/O).
// Null = no directory wired, so a keyed session is never pre-refused (the pre-#765 behaviour).
private readonly IGalaxyAckIdentityDirectory? _ackIdentityDirectory;
// lmxopcua#869: confirms acks the gateway SENT but could not confirm, against Galaxy's own acknowledged
// transition on the alarm feed (bounded by AlarmAck.ConfirmTimeoutMs). Built in the ctor.
private readonly GalaxyAckConfirmationTracker _ackConfirmations;
/// <summary>The ack confirmation window in force (lmxopcua#869) — tests.</summary>
internal TimeSpan AckConfirmationWindow => _ackConfirmations.Window;
/// <summary>Acks still awaiting (or exempt from) confirmation (lmxopcua#869) — tests.</summary>
internal int PendingAckConfirmations => _ackConfirmations.PendingCount;
private IGalaxyAlarmFeed? _alarmFeed;
private readonly Lock _alarmHandlersLock = new();
private readonly Lock _alarmFeedLock = new();
private bool _alarmFeedWired;
// List preserves insertion order so OnAlarmFeedTransition always picks the
// earliest-registered handle — a deterministic choice that doesn't vary as
// handles are added/removed (HashSet.First() is unstable).
private readonly List<GalaxyAlarmSubscriptionHandle> _alarmSubscriptions = new();
// Production runtime owned by InitializeAsync (BuildProductionRuntimeAsync). The
// driver builds these when it opens a real gw session; tests bypass them by
// injecting seams via the internal ctor, which leaves both fields null and skips
// BuildProductionRuntimeAsync entirely.
private GalaxyMxSession? _ownedMxSession;
private MxGatewayClient? _ownedMxClient;
// PR 4.5 — reconnect supervisor. Reflects in DriverState.Degraded while not Healthy.
private ReconnectSupervisor? _supervisor;
// PR 4.6 — IRediscoverable plumbing.
private DeployWatcher? _deployWatcher;
// PR 4.7 — IHostConnectivityProbe plumbing. The aggregator owns the merged
// transport+per-platform view; the forwarder is fed from the supervisor on
// transport state transitions; the probe watcher subscribes ScanState attributes
// for every discovered platform and pushes value changes to the aggregator.
private readonly HostStatusAggregator _hostStatuses = new();
private HostConnectivityForwarder? _transportForwarder;
private PerPlatformProbeWatcher? _probeWatcher;
// Injected deploy-watch seam (tests). Null in production, where StartDeployWatcherAsync builds a
// GatewayGalaxyDeployWatchSource over the owned GalaxyRepositoryClient.
private readonly IGalaxyDeployWatchSource? _deployWatchSource;
// Platform set for the ScanState probe watcher. Injected seam (tests) or, on the production
// path, a platform-only DiscoverHierarchy query over the owned repository client. Seeded at
// InitializeAsync and re-seeded on every deploy-watcher rediscovery: the runtime never calls
// DiscoverAsync on a live driver (only the /raw picker's throwaway does), so SyncPlatformsAsync
// from DiscoverAsync alone left the production watcher with no platforms, ever.
private readonly IGalaxyPlatformSource? _platformSource;
private IGalaxyPlatformSource? _ownedPlatformSource;
// Probe-seed requests (init + every rediscovery) not yet served. The first request starts the
// background worker; later ones only bump the count, and the worker loops until it has served
// every request it saw — so a request that lands while a pass is mid-fetch (a deploy, or the
// next runtime's init after a teardown) still gets a pass that starts after it.
private int _reseedRequests;
private volatile string _seedReason = "initialize";
// Cancels the in-flight background seed of the CURRENT runtime. Created by InitializeAsync,
// cancelled (never disposed — it has no timer or wait handle, and the worker may still read its
// token) by the teardown.
private CancellationTokenSource? _seedCts;
// Serialises "is this registration still for the live runtime?" against the teardown's registry
// Clear, so a subscribe / re-subscribe whose SubscribeBulk straddled a teardown either lands
// before the Clear (and is wiped by it) or sees the bumped generation and backs out.
private readonly Lock _registryGate = new();
// Bumped by every runtime teardown. Background work started under one runtime (the replay-gap
// re-snapshot, a rediscovery re-seed) re-checks it before touching the registry / watcher, so a
// late Rebind cannot resurrect handles into a registry the teardown already cleared.
private int _runtimeGeneration;
/// <summary>
/// Upper bound on the gateway <c>CloseSession</c> round-trip during a teardown. The SDK's
/// default close runs under the 30 s call timeout, which against a blackholed gateway parks
/// <c>ShutdownAsync</c> — and the host's <c>PostStop</c> — for the whole of it. Internal so
/// tests can shrink it.
/// </summary>
internal TimeSpan SessionCloseDeadline { get; set; } = TimeSpan.FromSeconds(5);
// True while the seams (_subscriber / _dataWriter / _hierarchySource / _alarmFeed /
// _alarmAcknowledger) were built by BuildProductionRuntimeAsync and are therefore ours to dispose
// and null on ShutdownAsync — the host's comms-loss recovery is ShutdownAsync → InitializeAsync on
// this SAME object, and InitializeAsync rebuilds only when the seams are null. Injected seams
// belong to the injector: ShutdownAsync stops every loop it started on top of them but leaves the
// seams in place, so a seam-driven test can cycle the lifecycle the way the watchdog does.
private bool _ownsRuntime;
// Serialises InitializeAsync / ShutdownAsync / DisposeAsync so a late watchdog re-init can never
// interleave with a teardown and resurrect half of the runtime it is tearing down.
private readonly SemaphoreSlim _lifecycleGate = new(1, 1);
// Set for the duration of a runtime teardown so the pump's stream-fault / replay-gap callbacks and
// the supervisor's replay cannot start a fresh pump underneath it.
private volatile bool _runtimeStopping;
private DriverHealth _health = new(DriverState.Unknown, null, null);
private bool _disposed;
/// <summary>
/// Test seam — forwarded to <see cref="GalaxyMxSession.OpenAndRegisterOverrideForTests"/> on the
/// session <see cref="BuildProductionRuntimeAsync"/> creates, so the owned-runtime lifecycle
/// (client + session construction, teardown, rebuild) can be exercised without a gateway. The
/// gRPC channels it builds are real but lazy: nothing dials until a call is made.
/// </summary>
internal Func<CancellationToken, Task>? SessionOpenOverrideForTests { get; set; }
/// <summary>Test seam: the owned gateway client, null when no production runtime is live.</summary>
internal MxGatewayClient? OwnedMxClientForTests => _ownedMxClient;
/// <summary>Test seam: the owned MX session, null when no production runtime is live.</summary>
internal GalaxyMxSession? OwnedMxSessionForTests => _ownedMxSession;
/// <summary>Test seam: the owned repository client, null until the deploy watcher or discovery built it.</summary>
internal GalaxyRepositoryClient? OwnedRepositoryClientForTests => _ownedRepositoryClient;
/// <summary>Test seam: the live reconnect supervisor, null outside a production runtime.</summary>
internal ReconnectSupervisor? SupervisorForTests => _supervisor;
/// <summary>Test seam: the live per-platform probe watcher, null until InitializeAsync.</summary>
internal PerPlatformProbeWatcher? ProbeWatcherForTests => _probeWatcher;
/// <summary>Test seam: the live deploy watcher, null until InitializeAsync starts one.</summary>
internal DeployWatcher? DeployWatcherForTests => _deployWatcher;
/// <summary>Test seam: true while an <see cref="EventPump"/> is running.</summary>
internal bool HasEventPumpForTests { get { lock (_pumpLock) return _eventPump is not null; } }
/// <summary>Test seam — the current pump instance (identity only), to observe a restart.</summary>
internal object? EventPumpInstanceForTests { get { lock (_pumpLock) return _eventPump; } }
/// <summary>Test seam: the number of driver subscriptions the registry still tracks.</summary>
internal int TrackedSubscriptionCountForTests => _subscriptions.TrackedSubscriptionCount;
/// <summary>Test seam — the registry's parked early-event count (#859).</summary>
internal int ParkedEarlyEventCountForTests => _subscriptions.ParkedEventCount;
/// <summary>Test seam — the driver's subscription registry (#859/#861 window + session tests).</summary>
internal SubscriptionRegistry SubscriptionsForTests => _subscriptions;
/// <summary>
/// Server-pushed data-change notification. Fires from the
/// <see cref="EventPump"/>'s background loop; handlers should be cheap (or queue
/// onto another thread) to avoid blocking the gw event stream.
/// </summary>
public event EventHandler<DataChangeEventArgs>? OnDataChange;
/// <summary>Fires when the gateway signals a deploy-time change (PR 4.6 DeployWatcher).</summary>
public event EventHandler<RediscoveryEventArgs>? OnRediscoveryNeeded;
/// <summary>Fires when a host transitions Running ↔ Stopped (PR 4.7 HostStatusAggregator).</summary>
public event EventHandler<HostStatusChangedEventArgs>? OnHostStatusChanged;
/// <summary>Raised when the gateway reports an alarm event for a subscribed Galaxy attribute.</summary>
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
/// <summary>Initializes a new instance of the <see cref="GalaxyDriver"/> class.</summary>
/// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
/// <param name="options">The Galaxy driver configuration options.</param>
/// <param name="secretResolver">Resolves the <c>secret:</c> arm of <c>Gateway.ApiKeySecretRef</c>.</param>
/// <param name="logger">Optional logger instance for diagnostics.</param>
/// <param name="ackIdentityDirectory">
/// Optional cached set of API keys with a Galaxy ack identity (lmxopcua#765), consulted by the synchronous
/// ack pre-check. Null = keyed sessions are never pre-refused.
/// </param>
public GalaxyDriver(
string driverInstanceId,
GalaxyDriverOptions options,
ISecretResolver secretResolver,
ILogger<GalaxyDriver>? logger = null,
IGalaxyAckIdentityDirectory? ackIdentityDirectory = null)
: this(driverInstanceId, options,
hierarchySource: null, dataReader: null, dataWriter: null, subscriber: null,
alarmAcknowledger: null, alarmFeed: null, logger,
secretResolver: secretResolver ?? throw new ArgumentNullException(nameof(secretResolver)),
ackIdentityDirectory: ackIdentityDirectory)
{
}
/// <summary>
/// Test-visible ctor — inject custom seams so <see cref="DiscoverAsync"/>,
/// <see cref="ReadAsync"/>, <see cref="WriteAsync"/>, and
/// <see cref="SubscribeAsync"/> can be exercised against canned data without
/// building real gRPC channels.
/// </summary>
/// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
/// <param name="options">The Galaxy driver configuration options.</param>
/// <param name="hierarchySource">Optional custom hierarchy source for testing.</param>
/// <param name="dataReader">Optional custom data reader for testing.</param>
/// <param name="dataWriter">Optional custom data writer for testing.</param>
/// <param name="subscriber">Optional custom subscriber for testing.</param>
/// <param name="alarmAcknowledger">Optional custom alarm acknowledger for testing.</param>
/// <param name="alarmFeed">Optional custom alarm feed for testing.</param>
/// <param name="logger">Optional logger instance for diagnostics.</param>
/// <param name="secretResolver">
/// Optional secret resolver for the <c>secret:</c> API-key arm. Defaults to a
/// null-object resolver (returns null for every name) so seam-injecting tests that
/// don't exercise a <c>secret:</c> ref need not supply one.
/// </param>
/// <param name="deployWatchSource">
/// Optional deploy-event stream seam. When supplied, <see cref="InitializeAsync"/> starts the
/// <see cref="DeployWatcher"/> over it (production builds one over the owned repository client).
/// </param>
/// <param name="platformSource">
/// Optional platform-set seam for the ScanState probe watcher. When supplied,
/// <see cref="InitializeAsync"/> seeds the watcher from it and every rediscovery re-seeds
/// (production builds a <see cref="GatewayGalaxyPlatformSource"/> over the owned repository client).
/// </param>
/// <param name="ackCredentialResolver">
/// Optional ack-credential seam (lmxopcua#749). Defaults to <see cref="GalaxyAckCredentialResolver"/>
/// over <see cref="GalaxyDriverOptions.AlarmAck"/> and <paramref name="secretResolver"/>.
/// </param>
/// <param name="ackIdentityDirectory">Optional cached key → Galaxy-identity set (lmxopcua#765).</param>
internal GalaxyDriver(
string driverInstanceId,
GalaxyDriverOptions options,
IGalaxyHierarchySource? hierarchySource,
IGalaxyDataReader? dataReader = null,
IGalaxyDataWriter? dataWriter = null,
IGalaxySubscriber? subscriber = null,
IGalaxyAlarmAcknowledger? alarmAcknowledger = null,
IGalaxyAlarmFeed? alarmFeed = null,
ILogger<GalaxyDriver>? logger = null,
ISecretResolver? secretResolver = null,
IGalaxyDeployWatchSource? deployWatchSource = null,
IGalaxyPlatformSource? platformSource = null,
IGalaxyAckCredentialResolver? ackCredentialResolver = null,
IGalaxyAckIdentityDirectory? ackIdentityDirectory = null)
{
_ackIdentityDirectory = ackIdentityDirectory;
_deployWatchSource = deployWatchSource;
_platformSource = platformSource;
_driverInstanceId = !string.IsNullOrWhiteSpace(driverInstanceId)
? driverInstanceId
: throw new ArgumentException("Driver instance id required.", nameof(driverInstanceId));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? NullLogger<GalaxyDriver>.Instance;
_secretResolver = secretResolver ?? NullSecretResolver.Instance;
_hierarchySource = hierarchySource;
_dataReader = dataReader;
_dataWriter = dataWriter;
_subscriber = subscriber;
_alarmAcknowledger = alarmAcknowledger;
_alarmFeed = alarmFeed;
_ackCredentialResolver = ackCredentialResolver
?? new GalaxyAckCredentialResolver(_driverInstanceId, _options.AlarmAck, _secretResolver, _logger);
_ackConfirmations = new GalaxyAckConfirmationTracker(
_options.AlarmAck?.ConfirmTimeout ?? GalaxyAckConfirmationTracker.DefaultWindow, _logger, _driverInstanceId);
// Build the v3 RawPath ⇄ attributeRef tables from the authored raw tags. Empty when no tags
// are authored (live-browse path), leaving every translation an identity no-op.
(_attributeRefByRawPath, _rawTagByAttributeRef) = BuildRawTagTables(_options.RawTags, _logger, _skippedTags);
_rawTagByAreaFreeRef = BuildAreaFreeAlarmIndex(_rawTagByAttributeRef, _logger);
// Forward the aggregator's transitions through IHostConnectivityProbe.
_hostStatuses.OnHostStatusChanged += (_, args) => OnHostStatusChanged?.Invoke(this, args);
}
/// <summary>
/// Build the RawPath → attributeRef and attributeRef → <see cref="RawTagEntry"/> tables from the
/// authored raw tags. Each entry's <see cref="RawTagEntry.TagConfig"/> carries the Galaxy dialled
/// address under the camelCase key <c>attributeRef</c>. Entries whose blob has no usable
/// <c>attributeRef</c> are skipped (they can't be dialled). On a duplicate attributeRef (two
/// authored RawPaths pointing at the same Galaxy attribute) the first entry wins the reverse map —
/// the value fan-out / alarm ConditionId then surfaces under that first RawPath; the forward map
/// still dials both. Case-insensitive to match the driver's reference handling.
/// </summary>
private static (Dictionary<string, string> Forward, Dictionary<string, RawTagEntry> Reverse)
BuildRawTagTables(IReadOnlyList<RawTagEntry> rawTags, ILogger logger, SkippedTagLedger skipped)
{
var forward = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var reverse = new Dictionary<string, RawTagEntry>(StringComparer.OrdinalIgnoreCase);
skipped.BeginRebuild(rawTags.Count);
foreach (var entry in rawTags)
{
if (string.IsNullOrEmpty(entry.RawPath))
{
// Counted, though there is no path to name it by: an artifact carrying such an entry
// is malformed, and reporting "N authored, N-1 bound" with nothing accounting for the
// difference is exactly the silence the skipped-tag count exists to prevent.
skipped.Skip("", "entry has no RawPath");
continue;
}
var attributeRef = TryReadAttributeRef(entry.TagConfig);
if (string.IsNullOrEmpty(attributeRef))
{
skipped.Skip(entry.RawPath, "TagConfig has no 'attributeRef' — cannot dial MXAccess");
logger.LogWarning(
"GalaxyDriver raw tag {RawPath} has no 'attributeRef' in its TagConfig — skipped (cannot dial MXAccess).",
entry.RawPath);
continue;
}
forward[entry.RawPath] = attributeRef;
if (!reverse.TryAdd(attributeRef, entry)) // first-wins on a shared attributeRef
{
// The loser is still dialled (forward map) but its value fan-out / alarm ConditionId surface
// under the winner's RawPath, so its own node never updates -- say so (archreview 06/S-13).
var winner = reverse[attributeRef].RawPath;
skipped.Skip(entry.RawPath,
$"duplicate attributeRef '{attributeRef}' — value fan-out surfaces under '{winner}'");
logger.LogWarning(
"GalaxyDriver raw tag {RawPath} shares attributeRef {AttributeRef} with {Winner} — its values and alarms surface under the winner only.",
entry.RawPath, attributeRef, winner);
}
}
skipped.Commit();
return (forward, reverse);
}
/// <summary>
/// Read the Galaxy dialled address from a tag's <c>TagConfig</c> JSON — the camelCase
/// <c>attributeRef</c> key (v3 rename of the pre-v3 PascalCase <c>FullName</c>). Case-insensitive
/// on the property name for authoring tolerance; returns null on an absent/blank/non-string value
/// or unparseable blob (the entry is then skipped, never dialled).
/// </summary>
private static string? TryReadAttributeRef(string tagConfigJson) => GalaxyAttributeRef.TryRead(tagConfigJson);
/// <summary>RawPath → Galaxy attributeRef for MXAccess dialling; identity on a miss.</summary>
private string ToAttributeRef(string rawPath) =>
_attributeRefByRawPath.GetValueOrDefault(rawPath, rawPath);
/// <summary>Galaxy attributeRef → RawPath (the server-facing identity); identity on a miss.</summary>
private string ToRawPath(string attributeRef) =>
_rawTagByAttributeRef.TryGetValue(attributeRef, out var e) ? e.RawPath : attributeRef;
/// <summary>
/// Resolves the RawPath an alarm-feed transition belongs to (lmxopcua#895). The authored attributeRef
/// is matched against, in order: the transition's full reference (a tag authored with the
/// provider-qualified <c>Galaxy!Area.tag.Attr</c> form), its <c>SourceObjectReference</c>
/// (<c>tag.Attr</c> — the form the AdminUI Galaxy picker authors), the full reference with its
/// <c>Provider!Area.</c> prefix stripped (the subtag provider sends only the object as its source), and the
/// full reference after its <c>Provider!</c> (an empty area). Those area-free names are then tried against
/// the hand-authored <c>Galaxy!Area.tag.Attr</c> refs by their own area-free part, so a re-areaed object
/// still resolves. Identity on a miss, as before. A match through any fallback records the full reference
/// for <see cref="ToAlarmAckReference"/> (latest wins, so a re-area is picked up on the next transition).
/// </summary>
/// <param name="alarmFullReference">The feed's provider-qualified alarm reference.</param>
/// <param name="sourceObjectReference">The feed's source reference (<c>tag.Attr</c>), may be empty.</param>
/// <returns>The authored RawPath, or <paramref name="alarmFullReference"/> when no authored tag matches.</returns>
internal string ResolveAlarmRawPath(string alarmFullReference, string? sourceObjectReference)
{
if (string.IsNullOrEmpty(alarmFullReference)) return alarmFullReference;
if (_rawTagByAttributeRef.TryGetValue(alarmFullReference, out var direct)) return direct.RawPath;
// The feed's area-free name for the alarm. The alarmmgr provider sends it as SourceObjectReference; the
// subtag fallback sends only the object there, so it is also derived from the full reference — with the
// area segment stripped, or (a reference composed with an empty area, "Galaxy!tag.Attr") everything
// after the '!'.
var stripped = StripProviderAndArea(alarmFullReference);
var afterBang = AfterProvider(alarmFullReference);
string?[] candidates = [sourceObjectReference, stripped, afterBang];
// Picker form first (attributeRef = tag.Attr), then a hand-authored Galaxy!<OldArea>.tag.Attr whose object
// Galaxy has since moved to another area.
foreach (var table in (Dictionary<string, RawTagEntry>[])[_rawTagByAttributeRef, _rawTagByAreaFreeRef])
{
foreach (var candidate in candidates)
{
if (string.IsNullOrEmpty(candidate) || !table.TryGetValue(candidate, out var entry)) continue;
_alarmFullRefByRawPath[entry.RawPath] = alarmFullReference;
return entry.RawPath;
}
}
return alarmFullReference;
}
/// <summary>
/// Index the provider-qualified authored attributeRefs (<c>Galaxy!Area.tag.Attr</c>) by their area-free
/// <c>tag.Attr</c> (lmxopcua#895 review). First wins on a shared key; an area-free key that is also authored
/// as a plain attributeRef is left to the plain entry. Both overlaps are logged, since the losing tag's
/// alarms then surface under another RawPath.
/// </summary>
private static Dictionary<string, RawTagEntry> BuildAreaFreeAlarmIndex(
Dictionary<string, RawTagEntry> rawTagByAttributeRef, ILogger logger)
{
var index = new Dictionary<string, RawTagEntry>(StringComparer.OrdinalIgnoreCase);
foreach (var (attributeRef, entry) in rawTagByAttributeRef)
{
var areaFree = StripProviderAndArea(attributeRef);
if (areaFree is null) continue;
if (rawTagByAttributeRef.TryGetValue(areaFree, out var plain))
{
logger.LogWarning(
"GalaxyDriver raw tags {RawPath} ({AttributeRef}) and {PlainRawPath} ({AreaFreeRef}) name the same Galaxy alarm — its transitions surface under {RawPath} while the area matches, otherwise under {PlainRawPath}.",
entry.RawPath, attributeRef, plain.RawPath, areaFree, entry.RawPath, plain.RawPath);
continue;
}
if (!index.TryAdd(areaFree, entry))
{
logger.LogWarning(
"GalaxyDriver raw tags {RawPath} ({AttributeRef}) and {Winner} name the same Galaxy alarm {AreaFreeRef} in different areas — a transition from any other area surfaces under {Winner} only.",
entry.RawPath, attributeRef, index[areaFree].RawPath, areaFree, index[areaFree].RawPath);
}
}
return index;
}
/// <summary>
/// The reference an acknowledge of the condition <paramref name="rawPath"/> dials: the provider-qualified
/// reference the alarm feed reported for it when one was learned (lmxopcua#895), otherwise the authored
/// attributeRef (identity on a miss).
/// </summary>
/// <param name="rawPath">The condition's RawPath (its ConditionId).</param>
/// <returns>The gateway alarm reference to acknowledge.</returns>
internal string ToAlarmAckReference(string rawPath) =>
_alarmFullRefByRawPath.TryGetValue(rawPath, out var full) ? full : ToAttributeRef(rawPath);
/// <summary><c>Galaxy!Area.tag.Attr</c> → <c>tag.Attr</c>; null when the reference has no <c>!</c> provider
/// prefix or nothing follows the area segment.</summary>
private static string? StripProviderAndArea(string alarmFullReference)
{
var bang = alarmFullReference.IndexOf('!');
if (bang < 0) return null;
var dot = alarmFullReference.IndexOf('.', bang + 1);
return dot < 0 || dot == alarmFullReference.Length - 1 ? null : alarmFullReference[(dot + 1)..];
}
/// <summary><c>Galaxy!tag.Attr</c> → <c>tag.Attr</c>; null without a <c>!</c> or with nothing after it.</summary>
private static string? AfterProvider(string alarmFullReference)
{
var bang = alarmFullReference.IndexOf('!');
return bang < 0 || bang == alarmFullReference.Length - 1 ? null : alarmFullReference[(bang + 1)..];
}
/// <inheritdoc />
public string DriverInstanceId => _driverInstanceId;
/// <inheritdoc />
public string DriverType => GalaxyDriverFactoryExtensions.DriverTypeName;
/// <summary>Test-visible options snapshot.</summary>
internal GalaxyDriverOptions Options => _options;
/// <summary>
/// Test-visible entry into <see cref="ReplayAsync"/>. The supervisor's
/// <see cref="ReconnectSupervisor.ReportTransportFailure"/> drives this on a
/// background task in production; tests prefer to invoke it directly so the
/// <see cref="GalaxyReconnectOptions.ReplayOnSessionLost"/> branch can be
/// asserted deterministically.
/// </summary>
/// <param name="cancellationToken">Cancellation token for the replay operation.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
internal Task InvokeReplayForTestAsync(CancellationToken cancellationToken) =>
ReplayAsync(cancellationToken);
// InitializeAsync takes a config document, and the IDriver contract is that a driver serves the
// one it is handed (the runtime's own mid-connect adoption path was deleted). The driver cannot
// hot-swap its options (they shape the gw session; see ReinitializeAsync), so a non-equivalent
// config with a real body is REFUSED here too rather than silently ignored - the driver would
// otherwise connect on its old endpoint while the deploy reported the change applied. A "{}" /
// empty document is the unit-test lifecycle shape and keeps the constructor options.
/// <inheritdoc />
public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (HasConfigBody(driverConfigJson)) RefuseNonEquivalentConfig(driverConfigJson);
await _lifecycleGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
// Tests inject seams via the internal ctor; production InitializeAsync builds
// the gateway client + session + per-capability runtime components from
// GalaxyDriverOptions. When seams are pre-injected we leave them alone (the
// test exercises the wired surface without a real gw round-trip). After a
// ShutdownAsync the production seams are null again, so the watchdog's
// Shutdown → Initialize genuinely rebuilds the runtime on this same object.
if (_subscriber is null && _dataWriter is null && _hierarchySource is null)
{
await BuildProductionRuntimeAsync(cancellationToken).ConfigureAwait(false);
}
else
{
_logger.LogDebug(
"GalaxyDriver {InstanceId} initializing with pre-injected seams — production runtime build skipped",
_driverInstanceId);
// The per-platform probe watcher needs only a subscriber, so it runs on the seam path
// too — that is what lets the ScanState wiring be exercised without a gateway.
if (_subscriber is not null) _probeWatcher ??= BuildProbeWatcher(_subscriber);
}
await StartDeployWatcherAsync(cancellationToken).ConfigureAwait(false);
// The platform seed is a gateway DiscoverHierarchy round-trip, which can spend the whole of
// a cold gateway cache's first-load wait — longer than Galaxy's Tier-A Initialize budget. It
// runs in the background: InitializeAsync neither waits on it nor fails because of it.
await PrepareProbeSeedAsync(cancellationToken).ConfigureAwait(false);
// #865: the seed's probe advises start the event pump themselves (BuildProbeWatcher's
// pre-subscribe hook) — a driver with no authored tags never Reads/Subscribes, and the pump
// used to start only there, so every initial ScanState value went to no stream.
RequestProbeSeed("initialize");
_logger.LogInformation(
"GalaxyDriver {InstanceId} initialized — endpoint={Endpoint} clientName={ClientName}",
_driverInstanceId, _options.Gateway.Endpoint, _options.MxAccess.ClientName);
_health = new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null);
}
finally
{
_lifecycleGate.Release();
}
}
/// <summary>
/// Under the lifecycle gate, before the first seed request of a runtime: resolve the platform
/// source (production builds it over the owned repository client — no network here) and arm
/// the runtime's seed cancellation. Resolving here, not in the worker, keeps the background
/// pass from creating a repository client after a teardown released it. A failure is a
/// Warning: the value path does not depend on the probe set.
/// </summary>
private async Task PrepareProbeSeedAsync(CancellationToken cancellationToken)
{
if (_probeWatcher is null) return;
_seedCts ??= new CancellationTokenSource();
if (_platformSource is not null || !_ownsRuntime || _ownedPlatformSource is not null) return;
try
{
_ownedRepositoryClient ??= GalaxyRepositoryClient.Create(
await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false));
_ownedPlatformSource =
new GatewayGalaxyPlatformSource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize);
}
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} could not build the platform query — per-platform host status stays unseeded until the next rediscovery.",
_driverInstanceId);
}
}
/// <summary>
/// Ask for a background probe seed (init and every deploy-watcher rediscovery). Requests
/// coalesce onto one worker; each worker pass serves the runtime that is live when the pass
/// STARTS, and a pass whose fetch completes after a teardown is discarded — so a request made
/// under a new runtime always gets a pass of its own.
/// </summary>
private void RequestProbeSeed(string reason)
{
if (_runtimeStopping || _probeWatcher is null) return;
_seedReason = reason;
if (Interlocked.Increment(ref _reseedRequests) != 1) return; // the running worker will serve it
_ = Task.Run(async () =>
{
int served;
do
{
served = Volatile.Read(ref _reseedRequests);
var generation = Volatile.Read(ref _runtimeGeneration);
var seedCts = Volatile.Read(ref _seedCts);
if (!_runtimeStopping && seedCts is not null)
{
await SeedProbePlatformsAsync(_seedReason, generation, seedCts.Token).ConfigureAwait(false);
}
}
while (Interlocked.Add(ref _reseedRequests, -served) != 0);
});
}
/// <summary>
/// One seed pass: fetch the platform / engine set and hand it to the probe watcher of the
/// runtime identified by <paramref name="generation"/>. Never throws — a failed or cancelled
/// fetch logs and leaves the watcher as it was (the next rediscovery retries), and a result
/// that lands after that runtime was torn down is discarded.
/// </summary>
private async Task SeedProbePlatformsAsync(string reason, int generation, CancellationToken cancellationToken)
{
var watcher = _probeWatcher;
var source = _platformSource ?? _ownedPlatformSource;
if (watcher is null || source is null) return;
try
{
var platforms = await source.GetPlatformTagNamesAsync(cancellationToken).ConfigureAwait(false);
if (Volatile.Read(ref _runtimeGeneration) != generation || _runtimeStopping
|| !ReferenceEquals(watcher, _probeWatcher))
{
_logger.LogDebug(
"GalaxyDriver {InstanceId} discarded a platform seed ({Reason}) — its runtime was torn down.",
_driverInstanceId, reason);
return;
}
await watcher.SyncPlatformsAsync(platforms, cancellationToken).ConfigureAwait(false);
_logger.LogInformation(
"GalaxyDriver {InstanceId} probe watcher seeded with {Count} platform(s) ({Reason}).",
_driverInstanceId, platforms.Count, reason);
}
catch (Exception ex) when (cancellationToken.IsCancellationRequested
|| Volatile.Read(ref _runtimeGeneration) != generation)
{
_logger.LogDebug(ex, "GalaxyDriver {InstanceId} platform seed ({Reason}) abandoned by a teardown.",
_driverInstanceId, reason);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} platform seed failed ({Reason}) — per-platform host status stays as it was until the next rediscovery.",
_driverInstanceId, reason);
}
}
/// <summary>Deploy-watcher rediscovery: a redeploy may add or remove platforms / engines.</summary>
private void ReseedProbePlatformsOnRediscovery() => RequestProbeSeed("rediscovery");
/// <summary>
/// Register <paramref name="bindings"/> only while <paramref name="generation"/> is still the
/// live runtime. Atomic with the teardown's registry Clear (both under <see cref="_registryGate"/>).
/// </summary>
private RegisterOutcome TryRegisterForGeneration(
long subscriptionId, IReadOnlyList<TagBinding> bindings, int generation, int session)
{
lock (_registryGate)
{
if (Volatile.Read(ref _runtimeGeneration) != generation) return RegisterOutcome.TornDown;
// #861: the reply may have straddled a reconnect — its handles then belong to the dead
// session and collide with the new session's numbers. Checked atomically with
// StartNewSession inside the registry.
return _subscriptions.TryRegister(subscriptionId, bindings, session)
? RegisterOutcome.Registered
: RegisterOutcome.SessionChanged;
}
}
private enum RegisterOutcome { Registered, TornDown, SessionChanged }
/// <summary>
/// UnsubscribeBulk for <paramref name="itemHandles"/>, then purge any event parked for them
/// (#859 I-3 interim — a trailing event must not be promoted onto a reused handle number).
/// </summary>
private async Task UnsubscribeAndPurgeAsync(
IGalaxySubscriber subscriber, IReadOnlyList<int> itemHandles, CancellationToken cancellationToken)
{
// Captured BEFORE the RPC (#859 I-B): a slow or failed unsubscribe can finish after a reconnect,
// when these numbers may be the NEW session's — the purge is then a no-op instead of deleting
// their parked initial values.
var session = _subscriptions.CurrentSession;
try
{
await subscriber.UnsubscribeBulkAsync(itemHandles, cancellationToken).ConfigureAwait(false);
}
finally
{
_subscriptions.PurgeParked(itemHandles, session);
}
}
private void ClearRegistry()
{
lock (_registryGate)
{
_subscriptions.Clear();
_strandedSubscriptions.Clear();
// A new session too: a late PurgeParked from a call the teardown orphaned (captured the old
// session) must never reach the next runtime's parked values.
_subscriptions.StartNewSession();
}
}
/// <summary>
/// Best-effort release of the live handles a SubscribeBulk produced for a call that then lost
/// its runtime — the subscriber may already be dead, so a failure is logged and swallowed.
/// </summary>
private async Task ReleaseOrphanedHandlesAsync(IGalaxySubscriber subscriber, IReadOnlyList<TagBinding> bindings)
{
var live = bindings.Where(b => b.ItemHandle > 0).Select(b => b.ItemHandle).ToArray();
if (live.Length == 0) return;
try { await UnsubscribeAndPurgeAsync(subscriber, live, CancellationToken.None).ConfigureAwait(false); }
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} could not release {Count} handle(s) orphaned by a teardown.",
_driverInstanceId, live.Length);
}
}
private static InvalidOperationException TornDownDuringSubscribe() => new(
"GalaxyDriver runtime was torn down while the subscribe was in flight — retry after the next InitializeAsync.");
// The watcher publishes its probe handles into the driver's registry (reserved id) so the
// EventPump's fan-out reaches OnPumpDataChange for ScanState events — without that every
// probe event was dropped before it got anywhere near the watcher.
// #865: the watcher also starts the pump before every probe SubscribeBulk — the initial ScanState
// value only reaches a stream that is already attached (the gateway does not replay a fresh one).
private PerPlatformProbeWatcher BuildProbeWatcher(IGalaxySubscriber subscriber) =>
new(subscriber, _hostStatuses, _subscriptions, _logger,
bufferedUpdateIntervalMs: _options.MxAccess.PublishingIntervalMs,
ensureEventStream: EnsureProbeEventStreamAsync);
/// <summary>
/// Build the production gw client + session + per-capability runtime components
/// from <c>_options</c>. Sets up the reconnect supervisor's reopen / replay
/// callbacks so a transport drop replays every active subscription on the
/// restored session.
/// </summary>
private async Task BuildProductionRuntimeAsync(CancellationToken cancellationToken)
{
try
{
await BuildProductionRuntimeCoreAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
// A failed connect must not leave a half-built runtime behind: the watchdog retries
// InitializeAsync every 10 s, and the seam check above would see the orphaned client +
// session as "already built" — or, worse, rebuild on top of them. Release what was
// created, and land the failed state before AND after the teardown (IDriver remark).
_health = new DriverHealth(DriverState.Faulted, _health.LastSuccessfulRead, ex.Message);
await TeardownRuntimeAsync(final: false, CancellationToken.None).ConfigureAwait(false);
_health = new DriverHealth(DriverState.Faulted, _health.LastSuccessfulRead, ex.Message);
throw;
}
}
private async Task BuildProductionRuntimeCoreAsync(CancellationToken cancellationToken)
{
// A pump that slipped in between a teardown and this rebuild (a late SubscribeAsync) is bound
// to the dead subscriber; it must never be reused as this runtime's pump.
EventPump? stale;
lock (_pumpLock) { stale = _eventPump; _eventPump = null; }
if (stale is not null)
{
stale.OnDataChange -= OnPumpDataChange;
try { await stale.DisposeAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "Stale EventPump dispose failed before runtime rebuild"); }
}
// Unconditionally: whatever the registry holds names handles of a session this rebuild replaces.
ClearRegistry();
_ownsRuntime = true;
var clientOptions = await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false);
_ownedMxClient = MxGatewayClient.Create(clientOptions);
_ownedMxSession = new GalaxyMxSession(_options.MxAccess, _logger)
{
OpenAndRegisterOverrideForTests = SessionOpenOverrideForTests,
};
await _ownedMxSession.ConnectAsync(clientOptions, cancellationToken).ConfigureAwait(false);
// PR 6.1 — wrap the gw-facing seams in tracing decorators so every Subscribe /
// Unsubscribe / Write / StreamEvents call emits a span on the
// "ZB.MOM.WW.OtOpcUa.Driver.Galaxy" ActivitySource. The host process's tracing
// listener (OTLP exporter, dotnet-trace, etc.) consumes these without the driver
// taking a dependency on the OpenTelemetry packages.
_subscriber = new TracedGalaxySubscriber(
new GatewayGalaxySubscriber(_ownedMxSession, _logger), _options.MxAccess.ClientName);
_dataWriter = new TracedGalaxyDataWriter(
// The writer always AddItems its own handle — a subscription's handle is plain-advised,
// and MXAccess both refuses a no-login write through it (SECURITY_ERROR 1008) and refuses
// upgrading its advise mode (E_INVALIDARG), so the former borrow-from-registry
// optimization could never commit a write. The advise limit is per handle, not per
// attribute: the writer's own supervisory-advised handle coexists with the subscription's.
new GatewayGalaxyDataWriter(
_ownedMxSession, _options.MxAccess.WriteUserId, _logger),
_options.MxAccess.ClientName);
_supervisor = new ReconnectSupervisor(
reopen: ReopenAsync,
replay: ReplayAsync,
options: new ReconnectOptions(
InitialBackoffOverride: TimeSpan.FromMilliseconds(_options.Reconnect.InitialBackoffMs),
MaxBackoffOverride: TimeSpan.FromMilliseconds(_options.Reconnect.MaxBackoffMs)),
logger: _logger);
_transportForwarder = new HostConnectivityForwarder(_options.MxAccess.ClientName, _hostStatuses, _logger);
_transportForwarder.SetTransport(HostState.Running); // initial state — we just connected
_supervisor.StateChanged += OnSupervisorStateChanged;
_probeWatcher = BuildProbeWatcher(_subscriber);
// Wire the alarm acknowledger + feed to the live gateway client. Both are
// session-less — the gateway serves alarms from an always-on central monitor —
// so they hang off the owned MxGatewayClient, not the worker session.
_alarmAcknowledger ??= new GatewayGalaxyAlarmAcknowledger(_ownedMxClient, _logger);
_alarmFeed ??= new GatewayGalaxyAlarmFeed(
_ownedMxClient.StreamAlarmsAsync, _logger, _options.MxAccess.ClientName);
}
/// <summary>
/// Stop every background loop and release every gateway resource this driver holds — the
/// teardown half shared by <see cref="ShutdownAsync"/> (<paramref name="final"/> = false:
/// a later <see cref="InitializeAsync"/> rebuilds) and <see cref="DisposeAsync"/>
/// (<paramref name="final"/> = true). Before this existed, <c>ShutdownAsync</c> was a
/// no-op and everything below outlived the driver on every respawn, removal and
/// <c>/raw</c> browse: the gateway accumulated live MX sessions and advised items, and
/// this process accumulated channels and stream loops.
/// </summary>
/// <remarks>
/// Ordering matters:
/// <list type="number">
/// <item>The supervisor goes first and is awaited, so no recovery loop can reopen the
/// session or start a pump while the rest is being released.</item>
/// <item>The probe watcher unsubscribes while the session is still open (its handles
/// die with the session anyway, but a clean release keeps the gateway's advise
/// count honest).</item>
/// <item>Streams (pump, alarm feed, deploy watcher) are cancelled and awaited.</item>
/// <item>The session closes (gateway <c>CloseSession</c>), then both owned channels.</item>
/// </list>
/// Every step is best-effort: one failing release never prevents the next.
/// </remarks>
private async Task TeardownRuntimeAsync(bool final, CancellationToken cancellationToken)
{
_runtimeStopping = true;
Interlocked.Increment(ref _runtimeGeneration);
Interlocked.Exchange(ref _seedCts, null)?.Cancel(); // a seed in flight belongs to this runtime
try
{
var supervisor = _supervisor;
_supervisor = null;
if (supervisor is not null)
{
supervisor.StateChanged -= OnSupervisorStateChanged;
try { await supervisor.StopAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "ReconnectSupervisor stop failed"); }
}
var deployWatcher = _deployWatcher;
_deployWatcher = null;
if (deployWatcher is not null)
{
deployWatcher.OnRediscoveryNeeded -= OnDeployWatcherRediscoveryNeeded;
try { await deployWatcher.StopAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "DeployWatcher stop failed"); }
}
var probeWatcher = _probeWatcher;
_probeWatcher = null;
if (probeWatcher is not null)
{
try { await probeWatcher.StopAsync(cancellationToken).ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "ProbeWatcher stop failed"); }
}
try { _transportForwarder?.Dispose(); } catch (Exception ex) { _logger.LogWarning(ex, "Transport forwarder dispose failed"); }
_transportForwarder = null;
EventPump? pump;
lock (_pumpLock) { pump = _eventPump; _eventPump = null; }
if (pump is not null)
{
pump.OnDataChange -= OnPumpDataChange;
try { await pump.DisposeAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "EventPump dispose failed"); }
}
// Every item handle the registry knows died with the pump's session; the host
// re-subscribes (fresh ids) once the next InitializeAsync reports Connected.
ClearRegistry();
// The alarm feed: owned → disposed and nulled so InitializeAsync builds a fresh one;
// injected → detached (the injector owns its lifetime) unless this is the final dispose.
IGalaxyAlarmFeed? alarmFeed;
bool releaseFeed;
lock (_alarmFeedLock)
{
alarmFeed = _alarmFeed;
releaseFeed = alarmFeed is not null && (_ownsRuntime || final);
if (alarmFeed is not null && _alarmFeedWired)
{
alarmFeed.OnAlarmTransition -= OnAlarmFeedTransition;
_alarmFeedWired = false;
}
if (releaseFeed) _alarmFeed = null;
}
if (releaseFeed)
{
try { await alarmFeed!.DisposeAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "Alarm feed dispose failed"); }
}
if (_ownedMxSession is not null)
{
var session = _ownedMxSession;
_ownedMxSession = null;
// Bounded close: the caller's token plus SessionCloseDeadline, so a blackholed gateway
// cannot park this (and the host's PostStop) for the SDK's 30 s call timeout.
using var closeCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
closeCts.CancelAfter(SessionCloseDeadline);
try { await session.CloseAsync(closeCts.Token).ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "MxSession close failed"); }
try { await session.DisposeAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "MxSession dispose failed"); }
}
if (_ownedMxClient is not null)
{
try { await _ownedMxClient.DisposeAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "MxClient dispose failed"); }
_ownedMxClient = null;
}
if (_ownedRepositoryClient is not null)
{
try { await _ownedRepositoryClient.DisposeAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "RepositoryClient dispose failed"); }
_ownedRepositoryClient = null;
}
if (_ownsRuntime || final)
{
// Null the seams so the next InitializeAsync rebuilds (production) — injected seams
// are only dropped on the final dispose.
_subscriber = null;
_dataWriter = null;
_hierarchySource = null;
_alarmAcknowledger = null;
_ownedPlatformSource = null;
_ownsRuntime = false;
}
}
finally
{
_runtimeStopping = false;
}
}
/// <summary>
/// Reopen callback for <see cref="ReconnectSupervisor"/>: recreate the gw session. After a
/// gateway restart the existing session handle is faulted / stale but non-null, so a plain
/// <c>ConnectAsync</c> would no-op and the supervisor would loop forever replaying against a
/// dead session. <see cref="GalaxyMxSession.RecreateAsync"/> disposes the stale session +
/// owned client and rebuilds, so a never-connected session still opens fresh.
/// </summary>
private async Task ReopenAsync(CancellationToken cancellationToken)
{
if (_ownedMxSession is null && RecreateOverrideForTests is null) return;
// #859 I-C: fence the registry around the swap itself, not later in ReplayAsync — a
// SubscribeBulk issued between RecreateAsync and the replay goes to the NEW gateway session.
// BEFORE: from here on nothing registered so far counts as live, so an UnsubscribeAsync during
// reopen/backoff never sends an old number (which the new session may reuse).
_subscriptions.StartNewSession();
if (RecreateOverrideForTests is { } recreate)
{
await recreate(cancellationToken).ConfigureAwait(false);
}
else
{
var clientOptions = await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false);
await _ownedMxSession!.RecreateAsync(clientOptions, cancellationToken).ConfigureAwait(false);
}
// AFTER: a subscribe that captured the session between the two bumps may have dialled the old
// (dead) session, so it is refused and re-issued; one that captures it from here on dials the
// recreated session (GatewayGalaxySubscriber reads GalaxyMxSession.Session at call time), so
// it registers normally and the replay leaves it alone instead of re-subscribing it.
Volatile.Write(ref _sessionOpenedByReopen, _subscriptions.StartNewSession());
// The recreated session invalidates every prior gw item handle; drop the writer's handle/advise
// caches so the next write re-AddItems + re-AdviseSupervisory against the fresh session.
_dataWriter?.InvalidateHandleCaches();
}
/// <summary>
/// The registry session <see cref="ReopenAsync"/> opened for the recreated gateway session, or -1.
/// <see cref="ReplayAsync"/> starts a new session itself only when no reopen did (the injected-
/// subscriber path, and tests); a second bump after a reopen would fence subscribes that already
/// registered against the recreated session.
/// </summary>
private int _sessionOpenedByReopen = -1;
/// <summary>Test seam — replaces the gateway session swap inside <see cref="ReopenAsync"/>.</summary>
internal Func<CancellationToken, Task>? RecreateOverrideForTests { get; set; }
/// <summary>Test-visible entry into <see cref="ReopenAsync"/>.</summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
internal Task InvokeReopenForTestAsync(CancellationToken cancellationToken) => ReopenAsync(cancellationToken);
/// <summary>
/// Replay callback. Walks every active subscription, re-issues SubscribeBulk for
/// its tag list, and <see cref="SubscriptionRegistry.Rebind">rebinds</see> the
/// registry with the fresh item handles the gateway returned — the pre-reconnect
/// handles are dead once the session reopened. The faulted <see cref="EventPump"/>
/// is recreated first so the replayed subscriptions have a live StreamEvents
/// consumer; without that restart the replayed tags are subscribed on the gw but
/// never reach <c>OnDataChange</c>. PR 6.x can swap this for
/// the gw's batched <c>ReplaySubscriptionsCommand</c> once it ships.
/// </summary>
private async Task ReplayAsync(CancellationToken cancellationToken)
{
// A teardown cancels the supervisor's cycle between reopen and replay; a replay that ran on
// anyway would start a fresh pump underneath the shutdown.
cancellationToken.ThrowIfCancellationRequested();
if (_subscriber is null) return;
// The session was recreated: every item handle the registry holds is dead and its number
// may be reused by the new session (#859 I-1 / #861). Invalidate the reverse map (the
// subscriptions stay; the per-iteration Rebind below re-binds each one, and new-session
// events park meanwhile instead of resolving to the old owner of a reused number), discard
// held events, and fence any subscribe whose reply straddled the reconnect. ReopenAsync
// already did this around the session swap; only when no reopen ran (injected subscriber,
// tests) is it done here — FIRST, before the pump restart and even with nothing to replay.
if (Interlocked.Exchange(ref _sessionOpenedByReopen, -1) != _subscriptions.CurrentSession)
{
_subscriptions.StartNewSession();
}
// The stream-fault that triggered this recovery left the old pump's RunAsync loop
// exited and its channel completed; EventPump.Start() is a no-op on a non-null but
// completed loop. Recreate the pump BEFORE anything can return early (#859 P-1): with no
// subscriptions to replay the dead pump used to stay in _eventPump, so every later
// Subscribe/Read reused it and was silently deaf while health stayed Healthy.
RestartEventPumpForReplay();
// #865: every re-advise below pushes its initial value once, to whatever stream is attached.
EventPump? replayPump;
lock (_pumpLock) replayPump = _eventPump;
if (replayPump is not null)
{
await AwaitCurrentEventStreamAsync(cancellationToken).ConfigureAwait(false);
// A replay whose fresh pump already died must FAIL, so the supervisor backs off and stays
// Degraded — succeeding would go Healthy with a dead stream, and the next advise's re-report
// would start a new cycle at attempt 1 (no backoff): a tight reconnect loop.
lock (_pumpLock) replayPump = _eventPump;
if (replayPump is { HasEnded: true })
{
// A teardown cancelling this replay can end the pump too: that is a clean cancellation.
cancellationToken.ThrowIfCancellationRequested();
// The synchronous case; a stream that ends a round trip later reports a transport failure
// while Replaying, which the supervisor itself turns into a failed attempt.
throw new InvalidOperationException(
"The Galaxy event stream ended during the reconnect replay — retrying after backoff.");
}
}
// Only subscriptions still holding the previous session's handles: one registered after the
// reopen is already live on the recreated session (re-subscribing it would double-advise).
// The probe entry is excluded: ONE registry entry holds every probe handle and any probe publish
// on the new session re-stamps it, so its session says nothing about which platforms are stale.
// The probe watcher tracks the session per handle and is driven separately below.
var session = _subscriptions.CurrentSession;
var entries = _subscriptions.SnapshotEntriesNotIn(session)
.Where(e => e.SubscriptionId != SubscriptionRegistry.ProbeSubscriptionId)
.ToArray();
var probeWatcher = _probeWatcher;
if (entries.Length == 0 && probeWatcher is null) return;
// Honor ReplayOnSessionLost. When operators opt out (false) the per-tag SubscribeBulk fan-out
// is skipped, and the recreated gateway session carries NONE of the old advises — those
// subscriptions stay deaf (their handles are dead and no longer resolve) until re-subscribed.
// #862: deaf must not look healthy. Every tag of every stranded subscription is published
// BadNoCommunication and the driver reports Degraded until the stranded subscriptions are gone.
if (!_options.Reconnect.ReplayOnSessionLost)
{
if (entries.Length > 0) MarkSubscriptionsStranded(entries);
return;
}
var generation = Volatile.Read(ref _runtimeGeneration);
var tagCount = entries.Length == 0
? 0
: await ResubscribeAllAsync(entries, generation, cancellationToken).ConfigureAwait(false);
// Probes on EVERY reconnect, whatever the registry entry's session: re-subscribes exactly the
// platforms whose handles predate the current session (a platform a seed already advised on the
// new session is left alone — no double advise), and republishes the fenced bindings.
if (probeWatcher is not null
&& Volatile.Read(ref _runtimeGeneration) == generation
&& _subscriptions.CurrentSession == session)
{
tagCount += await probeWatcher.ResubscribeStaleAsync(cancellationToken).ConfigureAwait(false);
}
_logger.LogInformation(
"GalaxyDriver {InstanceId} replay completed — {SubCount} subscriptions, {TagCount} tags re-subscribed",
_driverInstanceId, entries.Length, tagCount);
}
/// <summary>
/// #862 — a reconnect with <see cref="GalaxyReconnectOptions.ReplayOnSessionLost"/> = false left
/// <paramref name="entries"/> without advises on the recreated gateway session. Records them as
/// stranded (so <see cref="GetHealth"/> reports Degraded) and publishes every one of their tags
/// <c>BadNoCommunication</c> — the quality contract's comms-loss status — so no node keeps serving
/// its last value as Good. The value is null: the driver keeps no value cache, and a Bad sample's
/// value is not client-observable anyway (the SDK nulls it on read); the node is restated by the
/// initial value MXAccess delivers when the tag is next advised (a re-subscribe).
/// Published straight to <see cref="OnDataChange"/>, never through the pump path: that would
/// stamp <c>LastSuccessfulRead</c> for data that never arrived.
/// </summary>
/// <param name="entries">The subscriptions the reconnect stranded.</param>
private void MarkSubscriptionsStranded(
IReadOnlyList<(long SubscriptionId, IReadOnlyList<TagBinding> Bindings)> entries)
{
var tagCount = 0;
foreach (var (subscriptionId, _) in entries) _strandedSubscriptions[subscriptionId] = 0;
_logger.LogWarning(
"GalaxyDriver {InstanceId} reconnect replay skipped — Reconnect.ReplayOnSessionLost=false; {SubCount} subscription(s) " +
"receive no further data until they are re-subscribed (the recreated gateway session has none of their advises). " +
"Their tags are published BadNoCommunication and the driver reports Degraded until then.",
_driverInstanceId, entries.Count);
var now = DateTime.UtcNow;
var snapshot = new DataValueSnapshot(
Value: null, StatusCode: StatusCodeMap.BadNoCommunication, SourceTimestampUtc: now, ServerTimestampUtc: now);
foreach (var (subscriptionId, bindings) in entries)
{
// Unsubscribed while the reconnect ran: the host no longer holds this handle.
if (!_subscriptions.Contains(subscriptionId)) continue;
var handle = new GalaxySubscriptionHandle(subscriptionId);
foreach (var binding in bindings)
{
tagCount++;
try
{
OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, ToRawPath(binding.FullReference), snapshot));
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} OnDataChange handler threw publishing a stranded tag {FullRef} — continuing.",
_driverInstanceId, binding.FullReference);
}
}
}
_logger.LogDebug(
"GalaxyDriver {InstanceId} published BadNoCommunication for {TagCount} stranded tag(s).", _driverInstanceId, tagCount);
}
/// <summary>
/// #862 — the number of subscriptions a reconnect stranded (replay disabled) that are still registered.
/// Prunes ids the registry no longer holds.
/// </summary>
/// <returns>The live stranded-subscription count.</returns>
private int CountStrandedSubscriptions()
{
if (_strandedSubscriptions.IsEmpty) return 0;
var count = 0;
foreach (var id in _strandedSubscriptions.Keys)
{
if (_subscriptions.Contains(id)) count++;
else _strandedSubscriptions.TryRemove(id, out _);
}
return count;
}
/// <summary>Test seam — the live stranded-subscription count (#862).</summary>
internal int StrandedSubscriptionCountForTests => CountStrandedSubscriptions();
/// <summary>
/// Re-issues <c>SubscribeBulk</c> for every tracked subscription and rebinds the registry
/// with the item handles the gateway returned. Shared by the reconnect replay path and
/// the replay-gap re-snapshot — the difference between them is the event pump, which
/// replay must recreate (its loop died with the stream) and a gap must NOT touch (the
/// stream carrying the sentinel is still healthy and still delivering).
/// </summary>
/// <param name="entries">The subscriptions to re-issue.</param>
/// <param name="generation">
/// The runtime generation this re-subscribe belongs to. Re-checked before every
/// <see cref="SubscriptionRegistry.Rebind"/>: a teardown bumps it and clears the registry,
/// and a Rebind landing after that would resurrect dead handles into the next runtime.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The number of tag references re-subscribed.</returns>
private async Task<int> ResubscribeAllAsync(
IReadOnlyList<(long SubscriptionId, IReadOnlyList<TagBinding> Bindings)> entries,
int generation,
CancellationToken cancellationToken)
{
var tagCount = 0;
// M-b: the session this pass belongs to, read ONCE. Any later change fences the rest of the
// pass (the new session's own replay takes over).
var session = _subscriptions.CurrentSession;
foreach (var (subscriptionId, oldBindings) in entries)
{
if (Volatile.Read(ref _runtimeGeneration) != generation)
{
_logger.LogDebug("GalaxyDriver {InstanceId} re-subscribe abandoned — runtime was torn down.", _driverInstanceId);
return tagCount;
}
if (_subscriptions.CurrentSession != session) return tagCount; // a newer session's replay owns the rest
if (subscriptionId == SubscriptionRegistry.ProbeSubscriptionId && _probeWatcher is { } probeWatcher)
{
// The probe watcher owns its handles: it re-subscribes its platforms, records the
// fresh handles and rebinds the reserved registry entry itself, so ScanState host
// status keeps updating after a reconnect (it used to go permanently deaf).
tagCount += await probeWatcher.ResubscribeAsync(cancellationToken).ConfigureAwait(false);
continue;
}
var refs = oldBindings
.Select(b => b.FullReference)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
if (refs.Length == 0) continue;
// #859: the re-issued handles' initial values (the whole point of a re-snapshot) can
// overtake this SubscribeBulk reply; park them until the Rebind below promotes them.
// Scoped to this one iteration (the using is disposed at the end of the loop body): a
// window held across all N round-trips would park every unrelated unknown-handle event
// for the whole replay and could exhaust the bound before the genuine early values.
using var earlyEventWindow = _subscriptions.BeginPendingSubscribe();
var results = await _subscriber!
.SubscribeBulkAsync(refs, _options.MxAccess.PublishingIntervalMs, cancellationToken)
.ConfigureAwait(false);
var byAddress = BuildResultIndex(results);
var newBindings = new List<TagBinding>(refs.Length);
foreach (var fullRef in refs)
{
var itemHandle = byAddress.TryGetValue(fullRef, out var match) && match.WasSuccessful
? match.ItemHandle
: 0;
newBindings.Add(new TagBinding(fullRef, itemHandle));
}
// Rebind so the EventPump fan-out reverse map points at the post-reconnect
// handles; otherwise events on the new handles miss every subscription. Not after a
// teardown: the fresh handles belong to a subscriber that is already being released.
SubscriptionRegistry.BindOutcome outcome;
lock (_registryGate)
{
if (Volatile.Read(ref _runtimeGeneration) != generation) return tagCount;
outcome = _subscriptions.TryRebind(subscriptionId, newBindings, session);
}
if (outcome == SubscriptionRegistry.BindOutcome.SessionChanged)
{
// #861: another reconnect during the pass makes these handles dead too; the newer
// session's own replay re-subscribes everything, so stop here.
_logger.LogDebug(
"GalaxyDriver {InstanceId} re-subscribe abandoned — the gateway session changed again.",
_driverInstanceId);
return tagCount;
}
if (outcome == SubscriptionRegistry.BindOutcome.UnknownId)
{
// M-a: the subscription (or a subscribe-once read) was removed while its SubscribeBulk
// was in flight. Nothing will ever unsubscribe what was just advised — release it now.
var orphaned = newBindings.Where(b => b.ItemHandle > 0).Select(b => b.ItemHandle).ToArray();
if (orphaned.Length > 0)
{
try
{
await UnsubscribeAndPurgeAsync(_subscriber!, orphaned, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} could not release {Count} handle(s) re-subscribed for a subscription removed during the pass.",
_driverInstanceId, orphaned.Length);
}
}
continue;
}
tagCount += refs.Length;
}
return tagCount;
}
/// <summary>
/// Index a SubscribeBulk result list by tag address (OrdinalIgnoreCase) so the
/// subscribe / replay correlation loops are O(1) per reference rather than a
/// linear scan. Last-write-wins on a duplicate address (the gw shouldn't emit one).
/// </summary>
private static Dictionary<string, SubscribeResult> BuildResultIndex(IReadOnlyList<SubscribeResult> results)
{
var index = new Dictionary<string, SubscribeResult>(results.Count, StringComparer.OrdinalIgnoreCase);
foreach (var result in results)
{
if (!string.IsNullOrEmpty(result.TagAddress)) index[result.TagAddress] = result;
}
return index;
}
/// <summary>
/// Dispose the faulted <see cref="EventPump"/> and create a fresh one bound to the
/// same subscriber / registry, started immediately. Invoked from the reconnect
/// replay path. No-op when no pump was ever started (no active subscriptions).
/// </summary>
private void RestartEventPumpForReplay()
{
EventPump? old;
lock (_pumpLock)
{
old = _eventPump;
if (old is null) return; // pump never started — nothing to restart
// #865: a pump first started after the reopen's fence (no pump existed before the reconnect)
// already streams the recreated session, and advises registered under it may be waiting for
// their initial values on it — keep it, unless its loop has ended (a dead pump is always replaced,
// #859 P-1: a stream fault during Replaying is not re-reported by the supervisor).
if (old.Session == _subscriptions.CurrentSession && !old.HasEnded) return;
_eventPump = null;
// #865: until the replacement exists, AwaitCurrentEventStreamAsync must not start one of its
// own — two streams would race for the gateway's single-subscriber slot while the old one detaches.
_pumpRestarting = true;
}
try
{
// Detach + dispose the faulted pump outside the lock so a slow shutdown doesn't
// block a concurrent EnsureEventPumpStarted; the old loop already exited on fault.
old.OnDataChange -= OnPumpDataChange;
try { old.DisposeAsync().AsTask().GetAwaiter().GetResult(); }
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} faulted EventPump dispose failed during replay — continuing.",
_driverInstanceId);
}
// EnsureEventPumpStarted creates + starts a fresh pump under the lock. Skip the
// recreate if the driver is being disposed or its runtime torn down — the teardown
// already released the pump and a fresh one here would leak past it.
if (_disposed || _runtimeStopping) return;
EnsureEventPumpStarted();
}
finally
{
lock (_pumpLock) _pumpRestarting = false;
}
}
/// <summary>True while <see cref="RestartEventPumpForReplay"/> is between dropping the old pump and starting its replacement.</summary>
private bool _pumpRestarting;
private void OnSupervisorStateChanged(object? sender, StateTransition transition)
{
// Reflect supervisor state in DriverHealth + transport forwarder.
_health = transition.Next switch
{
ReconnectSupervisor.State.Healthy => new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null),
_ => new DriverHealth(DriverState.Degraded, _health.LastSuccessfulRead, transition.Cause),
};
if (_transportForwarder is not null)
{
var hostState = transition.Next == ReconnectSupervisor.State.Healthy
? HostState.Running
: HostState.Stopped;
_transportForwarder.SetTransport(hostState);
}
}
// Internal: the ONE client-options build InitializeAsync, ReopenAsync (every gateway reconnect) and the
// repository/alarm clients share — the lmxopcua#834 tests drive it directly to prove a reconnect refuses an
// out-of-namespace reference exactly like the first init.
internal async Task<MxGatewayClientOptions> BuildClientOptionsAsync(
GalaxyGatewayOptions gw, CancellationToken cancellationToken)
{
// Resolve the API-key ref BEFORE the object initializer — the secret: arm is
// async and you can't await inside an initializer. Pass the logger so the
// literal-arm cleartext fallback surfaces a startup warning rather than
// silently shipping the key. The resolver lives in Driver.Galaxy.Contracts
// (GalaxySecretRef) so the runtime driver and the AdminUI browser share one
// implementation; the secret: arm resolves through the shared ISecretResolver.
var apiKey = await GalaxySecretRef
.ResolveApiKeyAsync(gw.ApiKeySecretRef, _secretResolver, _logger, cancellationToken)
.ConfigureAwait(false);
return new MxGatewayClientOptions
{
Endpoint = new Uri(gw.Endpoint, UriKind.Absolute),
ApiKey = apiKey,
UseTls = gw.UseTls,
CaCertificatePath = gw.CaCertificatePath,
ConnectTimeout = TimeSpan.FromSeconds(gw.ConnectTimeoutSeconds),
DefaultCallTimeout = TimeSpan.FromSeconds(gw.DefaultCallTimeoutSeconds),
StreamTimeout = gw.StreamTimeoutSeconds > 0 ? TimeSpan.FromSeconds(gw.StreamTimeoutSeconds) : null,
};
}
private async Task StartDeployWatcherAsync(CancellationToken cancellationToken)
{
if (!_options.Repository.WatchDeployEvents) return;
var source = _deployWatchSource;
if (source is null)
{
// Seam mode without an injected watch source has no gateway to watch. (Production
// always owns its runtime here.) The old guard returned whenever BOTH the repository
// client and the hierarchy source were null — which on a production runtime instance
// is every first InitializeAsync, since discovery runs on the /raw picker's throwaway
// instance, not here — so the watcher never started and the re-browse chip never
// fired for a live driver.
if (!_ownsRuntime) return;
// Reuse the lazily-built repository client (DiscoverAsync constructs it on demand).
// Build under a null-check (not an overwrite) so if BuildDefaultHierarchySourceAsync
// later runs it reuses this client rather than leaking the first instance.
_ownedRepositoryClient ??= GalaxyRepositoryClient.Create(
await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false));
source = new GatewayGalaxyDeployWatchSource(_ownedRepositoryClient);
}
// One watcher per driver: a previous one (an InitializeAsync without a ShutdownAsync in
// between) is stopped before its replacement starts — every live InitializeAsync used to
// stack another watch-stream loop, each raising OnRediscoveryNeeded per real deploy.
var previous = _deployWatcher;
_deployWatcher = null;
if (previous is not null)
{
previous.OnRediscoveryNeeded -= OnDeployWatcherRediscoveryNeeded;
try { await previous.StopAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger.LogWarning(ex, "Previous DeployWatcher stop failed — replacing it anyway."); }
}
var watcher = new DeployWatcher(source, _logger);
watcher.OnRediscoveryNeeded += OnDeployWatcherRediscoveryNeeded;
_deployWatcher = watcher;
// StartAsync schedules the background loop and returns Task.CompletedTask immediately.
// It throws InvalidOperationException synchronously if called twice (programming error).
// Don't discard the return value — observe any synchronous throw.
var startTask = watcher.StartAsync(CancellationToken.None);
// The task is already completed (StartAsync is synchronous); surface any synchronous fault.
if (startTask.IsFaulted) startTask.GetAwaiter().GetResult();
}
private void OnDeployWatcherRediscoveryNeeded(object? sender, RediscoveryEventArgs args)
{
OnRediscoveryNeeded?.Invoke(this, args);
// A redeploy may add or remove platforms / engines; refresh the ScanState probe set.
ReseedProbePlatformsOnRediscovery();
}
/// <inheritdoc />
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!string.IsNullOrWhiteSpace(driverConfigJson)) RefuseNonEquivalentConfig(driverConfigJson);
_health = new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null);
return Task.CompletedTask;
}
/// <summary>True when the supplied DriverConfig JSON carries a real body (not empty / <c>"{}"</c> / <c>"[]"</c>).</summary>
private static bool HasConfigBody(string? driverConfigJson)
{
if (string.IsNullOrWhiteSpace(driverConfigJson)) return false;
var trimmed = driverConfigJson.Trim();
return trimmed is not "{}" and not "[]";
}
/// <summary>
/// Throw <see cref="NotSupportedException"/> unless <paramref name="driverConfigJson"/> describes options
/// runtime-equivalent to the live ones (see <see cref="OptionsAreEquivalent"/>). Shared by
/// <see cref="ReinitializeAsync"/> and <see cref="InitializeAsync"/> so neither path can silently
/// ignore a config change it cannot apply.
/// </summary>
private void RefuseNonEquivalentConfig(string driverConfigJson)
{
// In-place config reapply. The driver does not currently support hot-swapping
// GalaxyDriverOptions at runtime — changing the gateway endpoint, MxAccess
// client name, or reconnect policy requires tearing down the gw session,
// supervisor, event pump, and address space. The host stack handles that via
// DriverInstance restart, so this method only accepts an equivalent config (no
// meaningful change) and refreshes health; a non-equivalent reapply throws
// NotSupportedException so the caller knows the change wasn't applied.
//
// Materialise the incoming config and compare against the live options. We
// refuse any change that would require a session teardown rather than
// pretending to apply it.
GalaxyDriverOptions incoming;
try
{
// Reuse the factory's parse pipeline so any missing-required-field
// error surfaces with the same diagnostic text as InitializeAsync.
var transient = GalaxyDriverFactoryExtensions.CreateInstance(_driverInstanceId, driverConfigJson);
incoming = transient.Options;
// The transient instance never started a runtime — disposing is cheap.
transient.Dispose();
}
catch (Exception ex) when (ex is not NotSupportedException and not ObjectDisposedException)
{
throw new NotSupportedException(
$"GalaxyDriver could not parse the incoming DriverConfig JSON for '{_driverInstanceId}': {ex.Message}",
ex);
}
if (!OptionsAreEquivalent(_options, incoming))
{
throw new NotSupportedException(
"GalaxyDriver does not support hot-swapping driver options at runtime " +
"(gateway endpoint, MxAccess client name, reconnect policy, etc.). Restart the DriverInstance " +
"through the host stack to apply a config change.");
}
}
/// <summary>
/// Compare two <see cref="GalaxyDriverOptions"/> for runtime equivalence — every
/// field that drives gw session shape or reconnect behaviour must match. Compared
/// field-wise (the nested records supply value-equality) and <b>excluding
/// <see cref="GalaxyDriverOptions.RawTags"/></b>: the authored tag set is address-space
/// state re-applied through rediscovery, not a session-teardown trigger, and a record's
/// synthesized equality would compare the two <c>RawTags</c> lists by reference anyway.
/// </summary>
private static bool OptionsAreEquivalent(GalaxyDriverOptions a, GalaxyDriverOptions b) =>
a.Gateway == b.Gateway
&& a.MxAccess == b.MxAccess
&& a.Repository == b.Repository
&& a.Reconnect == b.Reconnect
&& a.ProbeTimeoutSeconds == b.ProbeTimeoutSeconds;
/// <summary>
/// Stop the driver and release the gateway runtime: supervisor, deploy watcher, probe
/// watcher, event pump, alarm feed, MX session (gateway <c>CloseSession</c>) and both owned
/// gRPC channels. The seams are nulled afterwards, so a later <see cref="InitializeAsync"/>
/// on this same object — the host's comms-loss recovery and the way <c>ReinitializeAsync</c>
/// is sequenced — rebuilds a fresh runtime instead of reusing a dead one. The driver object
/// itself stays usable; <see cref="DisposeAsync"/> is the final, idempotent teardown.
/// </summary>
/// <inheritdoc />
public async Task ShutdownAsync(CancellationToken cancellationToken)
{
if (_disposed) return;
_logger.LogInformation("GalaxyDriver {InstanceId} shutting down", _driverInstanceId);
await _lifecycleGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_disposed) return;
await TeardownRuntimeAsync(final: false, cancellationToken).ConfigureAwait(false);
// Terminal health lands AFTER the teardown (IDriver remark): a loop unwinding during the
// release could otherwise overwrite it with the state it was reporting when cancelled.
_health = new DriverHealth(DriverState.Unknown, _health.LastSuccessfulRead, null);
}
finally
{
_lifecycleGate.Release();
}
}
/// <inheritdoc />
public DriverHealth GetHealth()
{
// Reconnect supervisor wins when degraded — the cached _health reflects the last
// successful operation, but ongoing recovery should surface as Degraded.
if (_supervisor?.IsDegraded == true)
{
return new DriverHealth(DriverState.Degraded, _health.LastSuccessfulRead, _supervisor.LastError);
}
// #862: the transport is back but a reconnect with ReplayOnSessionLost=false left subscriptions
// without advises. LastSuccessfulRead is NOT advanced here — it only moves on real stream data, so
// if nothing else flows the host's comms-loss watchdog re-initializes the driver (which
// re-subscribes everything) exactly as for any other sustained loss.
var stranded = CountStrandedSubscriptions();
if (stranded > 0)
{
return new DriverHealth(
DriverState.Degraded,
_health.LastSuccessfulRead,
$"{stranded} Galaxy subscription(s) stranded by a gateway reconnect: Reconnect.ReplayOnSessionLost=false, " +
"so the recreated gateway session carries none of their advises — their tags are BadNoCommunication " +
"until they are re-subscribed. Set ReplayOnSessionLost=true to replay them on reconnect.");
}
return _health;
}
// ===== IHostConnectivityProbe (PR 4.7 wire-up) =====
/// <inheritdoc />
public IReadOnlyList<HostConnectivityStatus> GetHostStatuses() => _hostStatuses.Snapshot();
// ===== ITagDiscovery (PR 4.1) =====
/// <inheritdoc />
// Run-once: DiscoverAsync fetches the full Galaxy hierarchy inline and streams the complete
// node set within a single awaited call — there is no FOCAS-style background cache that fills
// in after connect. Galaxy is a heavy network driver, so the bounded post-connect retry loop
// is deliberately avoided; re-discovery on Galaxy redeploy is handled separately via
// IRediscoverable + the deploy-event watcher.
public DiscoveryRediscoverPolicy RediscoverPolicy => DiscoveryRediscoverPolicy.Once;
/// <inheritdoc />
public async Task DiscoverAsync(IAddressSpaceBuilder builder, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(builder);
// Wrap the builder with a SecurityCapturingBuilder so each discovered attribute's
// SecurityClassification is recorded in _securityByFullRef for write-time routing.
// After discovery, SyncPlatformsAsync refreshes the probe watcher's membership so
// newly added $WinPlatform / $AppEngine objects start advising their ScanState attribute.
var capturingBuilder = new SecurityCapturingBuilder(builder, _securityByFullRef);
var source = _hierarchySource ??=
await BuildDefaultHierarchySourceAsync(cancellationToken).ConfigureAwait(false);
// Thread the v3 reverse resolver so the discoverer emits each authored attribute's RawPath as
// its node reference (FullName) — the security map SecurityCapturingBuilder captures is then
// keyed by RawPath, matching what WriteAsync resolves against.
var discoverer = new GalaxyDiscoverer(
source, attributeRef => _rawTagByAttributeRef.GetValueOrDefault(attributeRef));
// One sweep: the discoverer hands back the hierarchy it materialised, and the platform
// selection below reads that instead of asking the gateway for the whole galaxy again.
var hierarchy = await discoverer.DiscoverAsync(capturingBuilder, cancellationToken).ConfigureAwait(false);
if (_probeWatcher is not null)
{
var platforms = hierarchy
.Where(o => o.TemplateChain.Any(t =>
string.Equals(t, "$WinPlatform", StringComparison.OrdinalIgnoreCase)
|| string.Equals(t, "$AppEngine", StringComparison.OrdinalIgnoreCase)))
.Select(o => o.TagName)
.Where(name => !string.IsNullOrEmpty(name));
await _probeWatcher.SyncPlatformsAsync(platforms, cancellationToken).ConfigureAwait(false);
}
}
private SecurityClassification ResolveSecurity(string fullReference) =>
_securityByFullRef.TryGetValue(fullReference, out var sec) ? sec : SecurityClassification.FreeAccess;
// ===== IReadable =====
/// <inheritdoc />
public Task<IReadOnlyList<DataValueSnapshot>> ReadAsync(
IReadOnlyList<string> fullReferences, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(fullReferences);
if (fullReferences.Count == 0) return Task.FromResult<IReadOnlyList<DataValueSnapshot>>([]);
// v3: the server addresses by RawPath; translate to the Galaxy attributeRef MXAccess dials.
// Read returns positionally, so no reverse translation is needed on the result. An unmapped
// RawPath dials as-is (identity) — the gateway rejects an unknown address → Bad, same as today.
var dialledRefs = new string[fullReferences.Count];
for (var i = 0; i < fullReferences.Count; i++) dialledRefs[i] = ToAttributeRef(fullReferences[i]);
if (_dataReader is not null)
{
// Test-only path — tests inject a canned reader via the internal ctor.
return _dataReader.ReadAsync(dialledRefs, cancellationToken);
}
if (_subscriber is null)
{
throw new NotSupportedException(
"GalaxyDriver.ReadAsync requires a connected GalaxyMxSession (production runtime not built). " +
"Either inject a test seam via the internal ctor or call InitializeAsync against a real gateway.");
}
return ReadViaSubscribeOnceAsync(dialledRefs, cancellationToken);
}
/// <summary>
/// Raw (attributeRef-domain) data changes for in-flight subscribe-once reads. Raised by
/// <see cref="OnPumpDataChange"/> for whichever pump is current, so a read survives a reconnect's
/// pump restart.
/// </summary>
private event EventHandler<DataChangeEventArgs>? ReadDataChange;
/// <summary>Upper bound on one subscribe-once read; internal so tests can shrink it.</summary>
internal TimeSpan ReadViaSubscribeDeadline { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>
/// Production read path. MxAccess has no one-shot Read RPC — every value comes
/// through the event stream. We synthesise a Read by:
/// <list type="number">
/// <item>Subscribing the requested tags through the existing
/// <see cref="SubscriptionRegistry"/> + <see cref="EventPump"/>.</item>
/// <item>Waiting for the first <c>OnDataChange</c> per item handle (the gateway
/// pushes the current value as the initial event after a SubscribeBulk).</item>
/// <item>Unsubscribing.</item>
/// </list>
/// Tags the gw rejects at SubscribeBulk time, or that never publish before the
/// caller's cancellation token fires, return a Bad-status snapshot in input order
/// so the caller still sees one snapshot per requested reference.
/// </summary>
private async Task<IReadOnlyList<DataValueSnapshot>> ReadViaSubscribeOnceAsync(
IReadOnlyList<string> fullReferences, CancellationToken callerToken)
{
// Internal deadline (archreview 06/S-3): a tag that never publishes must not hang a caller that
// passed CancellationToken.None. Still-pending slots fill with BadTimeout exactly as for a caller cancel.
using var deadlineCts = CancellationTokenSource.CreateLinkedTokenSource(callerToken);
deadlineCts.CancelAfter(ReadViaSubscribeDeadline);
var cancellationToken = deadlineCts.Token;
var generation = Volatile.Read(ref _runtimeGeneration); // see SubscribeAsync
var readSubscriber = _subscriber!;
// A live pump must exist (values arrive through it); the read listens on ReadDataChange, not
// on this instance, so it survives a reconnect's pump restart.
ThrowIfRuntimeStopping(); // the pump itself is started by AwaitCurrentEventStreamAsync below
// #865: a read waits ONLY for the initial value, which reaches only a current-session stream that is
// already requested. The internal deadline bounds this too; a deadline (not caller) cancel falls
// through so the read still answers per-ref, as it does for a deadline during the RPC.
int issueSession;
try
{
issueSession = await AwaitCurrentEventStreamAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!callerToken.IsCancellationRequested)
{
issueSession = _subscriptions.CurrentSession;
}
var subscriptionId = _subscriptions.NextSubscriptionId();
// Pre-allocate one TaskCompletionSource per full-reference so the OnDataChange
// handler can complete them out-of-order as events arrive. Wired BEFORE the
// SubscribeBulk call so we don't race with the first event the gw pushes.
var pendingByRef = new Dictionary<string, TaskCompletionSource<DataValueSnapshot>>(
StringComparer.OrdinalIgnoreCase);
foreach (var fullRef in fullReferences.Distinct(StringComparer.OrdinalIgnoreCase))
{
pendingByRef[fullRef] = new TaskCompletionSource<DataValueSnapshot>(
TaskCreationOptions.RunContinuationsAsynchronously);
}
EventHandler<DataChangeEventArgs> handler = (_, args) =>
{
// Filter to OUR subscription — the pump's OnDataChange fans out across all
// subscriptions on the driver, and we don't want a parallel ISubscribable
// caller's events to leak into our read.
if (args.SubscriptionHandle is GalaxySubscriptionHandle gsh
&& gsh.SubscriptionId == subscriptionId
&& pendingByRef.TryGetValue(args.FullReference, out var tcs))
{
tcs.TrySetResult(args.Snapshot);
}
};
ReadDataChange += handler;
var bufferedIntervalMs = _options.MxAccess.PublishingIntervalMs;
IReadOnlyList<SubscribeResult> results;
List<TagBinding> bindings;
// #859: a read waits ONLY for the initial value, and that value can overtake the SubscribeBulk
// reply — dropped as stale, a slow-changing attribute would read BadTimeout. Open the early-event
// window before the RPC and close it right after registration (the finally below), not after the
// value wait: a window held for the whole wait would park every unrelated unknown-handle event.
var earlyEventWindow = _subscriptions.BeginPendingSubscribe();
var session = issueSession; // #861/#865 — the session this SubscribeBulk is issued on (its stream verified)
try
{
// The RPC gets only the CALLER's token: the internal deadline bounds our wait, not the RPC, so a slow
// gateway can never surface an OperationCanceledException to a caller that did not cancel, and the
// handles it eventually creates are known (and unsubscribed below) rather than lost to a cancelled call.
var subscribeTask = readSubscriber.SubscribeBulkAsync(fullReferences, bufferedIntervalMs, callerToken);
try
{
results = await subscribeTask.WaitAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!callerToken.IsCancellationRequested)
{
// Internal deadline fired while the subscribe RPC was still in flight.
ReadDataChange -= handler;
var subscriber = readSubscriber;
var logger = _logger;
_ = subscribeTask.ContinueWith(t =>
{
if (!t.IsCompletedSuccessfully) return Task.CompletedTask;
// A late reply from a session that has since been replaced carries dead handle
// numbers the new session may reuse — never unsubscribe those (#861).
if (_subscriptions.CurrentSession != session) return Task.CompletedTask;
var late = t.Result.Where(r => r.WasSuccessful && r.ItemHandle > 0).Select(r => r.ItemHandle).ToArray();
return late.Length == 0
? Task.CompletedTask
: UnsubscribeAndPurgeAsync(subscriber, late, CancellationToken.None).ContinueWith(
u => logger.LogWarning(u.Exception,
"GalaxyDriver.ReadViaSubscribeOnceAsync late UnsubscribeBulk failed for {Count} handle(s).", late.Length),
TaskContinuationOptions.OnlyOnFaulted);
}, TaskScheduler.Default).Unwrap();
var now = DateTime.UtcNow;
var timedOut = new DataValueSnapshot[fullReferences.Count];
for (var i = 0; i < timedOut.Length; i++)
timedOut[i] = new DataValueSnapshot(null, StatusCodeMap.BadTimeout, null, now);
return timedOut;
}
catch
{
ReadDataChange -= handler;
throw;
}
// Register bindings so the pump knows to dispatch events for these handles.
// Index the SubscribeBulk results once and correlate to references in O(1)
// instead of FirstOrDefault per element (O(n²) over the batch). On the
// 50k-tag soak path this turns a 2.5G-comparison loop into a single
// Dictionary build + linear scan.
var resultIndex = BuildResultIndex(results);
bindings = new List<TagBinding>(fullReferences.Count);
for (var i = 0; i < fullReferences.Count; i++)
{
var fullRef = fullReferences[i];
var itemHandle = resultIndex.TryGetValue(fullRef, out var match) && match is { WasSuccessful: true }
? match.ItemHandle
: 0;
bindings.Add(new TagBinding(fullRef, itemHandle));
// Tags the gw rejected up front — complete with Bad status now so the
// wait below doesn't time out on them.
if (itemHandle <= 0
&& pendingByRef.TryGetValue(fullRef, out var rejectedTcs))
{
rejectedTcs.TrySetResult(new DataValueSnapshot(
Value: null,
StatusCode: StatusCodeMap.Bad,
SourceTimestampUtc: null,
ServerTimestampUtc: DateTime.UtcNow));
}
}
var registered = TryRegisterForGeneration(subscriptionId, bindings, generation, session);
if (registered != RegisterOutcome.Registered)
{
ReadDataChange -= handler;
earlyEventWindow.Dispose(); // before any further round-trip
if (registered == RegisterOutcome.TornDown)
{
await ReleaseOrphanedHandlesAsync(readSubscriber, bindings).ConfigureAwait(false);
throw TornDownDuringSubscribe();
}
// #861: the reply straddled a reconnect. Its handles died with the old session and
// their numbers may already belong to new-session items, so they are neither
// registered nor unsubscribed. A read is one-shot: report the lost session per tag.
_logger.LogInformation(
"GalaxyDriver {InstanceId} subscribe-once read of {Count} tag(s) straddled a gateway reconnect — returning BadCommunicationError.",
_driverInstanceId, fullReferences.Count);
var lostAt = DateTime.UtcNow;
var lost = new DataValueSnapshot[fullReferences.Count];
for (var i = 0; i < lost.Length; i++)
lost[i] = new DataValueSnapshot(null, StatusCodeMap.BadCommunicationError, null, lostAt);
return lost;
}
}
finally
{
earlyEventWindow.Dispose();
}
try
{
// Wait for every pending TCS to complete or the caller's CT to fire. When the
// CT fires before all values arrive, fill the still-pending entries with a
// Bad-status snapshot rather than throwing — Read semantics let callers see
// partial results.
using var registration = cancellationToken.Register(() =>
{
foreach (var tcs in pendingByRef.Values)
{
tcs.TrySetResult(new DataValueSnapshot(
Value: null,
StatusCode: StatusCodeMap.BadTimeout,
SourceTimestampUtc: null,
ServerTimestampUtc: DateTime.UtcNow));
}
});
var snapshots = new DataValueSnapshot[fullReferences.Count];
for (var i = 0; i < fullReferences.Count; i++)
{
snapshots[i] = await pendingByRef[fullReferences[i]].Task.ConfigureAwait(false);
}
return snapshots;
}
finally
{
ReadDataChange -= handler;
// Drop the bindings + unsubscribe the live handles. UnsubscribeBulkAsync's
// failure isn't fatal — the registry is already cleared, so any straggling
// event from the gw would be a no-op fan-out.
var removed = _subscriptions.Remove(subscriptionId, out var liveInCurrentSession);
// Unsubscribe what the registry held at removal, NOT the local `bindings` (#859 B-1): a
// reconnect replay during the wait may have rebound this read to new-session handles, and
// the original numbers may now be other tags' live items. If the entry still holds dead
// old-session handles (not yet rebound), release nothing (#861). Only when the entry was
// already gone (teardown cleared the registry) fall back to the original bindings.
IReadOnlyList<TagBinding> source = removed ?? bindings;
if (removed is not null && !liveInCurrentSession) source = [];
var liveHandles = source.Where(b => b.ItemHandle > 0).Select(b => b.ItemHandle).ToArray();
if (liveHandles.Length > 0)
{
try
{
await UnsubscribeAndPurgeAsync(readSubscriber, liveHandles, CancellationToken.None)
.ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver.ReadViaSubscribeOnceAsync UnsubscribeBulk failed for {Count} handle(s) — registry already cleared.",
liveHandles.Length);
}
}
}
}
// ===== IWritable (PR 4.3) =====
/// <inheritdoc />
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(writes);
if (writes.Count == 0) return Task.FromResult<IReadOnlyList<WriteResult>>([]);
if (_dataWriter is null)
{
// Mirror the IReadable fallback: production write path runs on top of
// GatewayGalaxyDataWriter, which is wired by InitializeAsync when the gRPC session
// connects. This guard fires only if the driver is called before initialization completes.
throw new NotSupportedException(
"GalaxyDriver.WriteAsync requires GatewayGalaxyDataWriter wired against a connected " +
"GalaxyMxSession. Call InitializeAsync and wait for a successful connection before " +
"issuing writes.");
}
// v3: WriteRequest.FullReference is a RawPath. Translate to the Galaxy attributeRef the writer
// dials to MXAccess. Security was captured at discovery keyed by RawPath (= the node's FullName),
// so the resolver the writer invokes with the DIALLED attributeRef must reverse it back to RawPath
// before the lookup. Both legs are identity on a miss, so an un-authored tag behaves as before.
var dialledWrites = new List<WriteRequest>(writes.Count);
foreach (var w in writes) dialledWrites.Add(w with { FullReference = ToAttributeRef(w.FullReference) });
return _dataWriter.WriteAsync(
dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), cancellationToken);
}
// ===== ISubscribable (PR 4.4) =====
/// <inheritdoc />
public async Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(fullReferences);
if (_subscriber is null)
{
throw new NotSupportedException(
"GalaxyDriver.SubscribeAsync requires a connected GalaxyMxSession + GatewayGalaxySubscriber. " +
"Call InitializeAsync and wait for a successful connection before subscribing.");
}
// Captured before the pump/stopping check: a teardown that starts after this point bumps the
// generation, so the Register below can tell its SubscribeBulk straddled a teardown.
var generation = Volatile.Read(ref _runtimeGeneration);
var subscriber = _subscriber;
ThrowIfRuntimeStopping(); // the pump is started per attempt by AwaitCurrentEventStreamAsync (#865)
var subscriptionId = _subscriptions.NextSubscriptionId();
if (fullReferences.Count == 0)
{
// Empty subscriptions register but never bind anything — keeps Unsubscribe
// symmetric for callers that conditionally add tags later.
RegisterOutcome outcome;
do
{
// No handles, so a session change only means "read the session again".
outcome = TryRegisterForGeneration(subscriptionId, [], generation, _subscriptions.CurrentSession);
}
while (outcome == RegisterOutcome.SessionChanged);
if (outcome == RegisterOutcome.TornDown) throw TornDownDuringSubscribe();
return new GalaxySubscriptionHandle(subscriptionId);
}
// v3: the server subscribes by RawPath; the registry + gateway operate on the Galaxy attributeRef.
// Translate here (identity on a miss — a synthetic alarm sub-ref or live-browse tag dials straight
// through). The value fan-out reverse-translates back to RawPath in OnPumpDataChange.
var dialledRefs = new string[fullReferences.Count];
for (var i = 0; i < fullReferences.Count; i++) dialledRefs[i] = ToAttributeRef(fullReferences[i]);
// PR 6.3 — when the caller doesn't set a publishing interval (TimeSpan.Zero or
// negative), fall back to the configured MxAccess.PublishingIntervalMs. The
// server's UA subscription publishingInterval drives this in production; tests
// and infrastructure callers (probe watcher, deploy watcher) hit the fallback.
var requested = (int)Math.Max(0, publishingInterval.TotalMilliseconds);
var bufferedIntervalMs = requested > 0 ? requested : _options.MxAccess.PublishingIntervalMs;
for (var attempt = 1; ; attempt++)
{
// #865: per attempt (a #861 retry is a new session): the advise's initial value reaches only a
// current-session stream that is already requested — the gateway does not replay a fresh stream.
var issueSession = await AwaitCurrentEventStreamAsync(cancellationToken).ConfigureAwait(false);
// #859: MXAccess's initial value for a new handle can reach the event pump before this
// reply is registered (the gateway gives no reply-before-event ordering, and the reply and
// the event ride separate RPCs). Open the early-event window BEFORE the RPC so such events
// are parked rather than dropped as stale; it closes once the registration (which promotes
// them for in-order replay) is done.
var earlyEventWindow = _subscriptions.BeginPendingSubscribe();
try
{
var session = issueSession; // #861/#865 — the session this SubscribeBulk is issued on (its stream verified)
var results = await subscriber
.SubscribeBulkAsync(dialledRefs, bufferedIntervalMs, cancellationToken)
.ConfigureAwait(false);
var bindings = BuildSubscribeBindings(dialledRefs, results);
switch (TryRegisterForGeneration(subscriptionId, bindings, generation, session))
{
case RegisterOutcome.Registered:
return new GalaxySubscriptionHandle(subscriptionId);
case RegisterOutcome.TornDown:
// The teardown cleared the registry while SubscribeBulk was in flight; registering
// now would carry dead handles into the next runtime. Release what we got and fail.
earlyEventWindow.Dispose(); // M-3: not held across the release round-trip
await ReleaseOrphanedHandlesAsync(subscriber, bindings).ConfigureAwait(false);
throw TornDownDuringSubscribe();
default:
// #861: the reply straddled a gateway reconnect, so its handles died with the old
// session (and are NOT unsubscribed — the new session may reuse the numbers). The
// reconnect replay only re-subscribes what was registered when it snapshotted, so
// this subscription would be lost: issue it again on the new session.
if (attempt >= MaxSubscribeSessionAttempts)
{
throw new InvalidOperationException(
$"Galaxy subscribe straddled {attempt} consecutive gateway reconnects — giving up; retry later.");
}
_logger.LogInformation(
"GalaxyDriver {InstanceId} subscribe of {Count} tag(s) straddled a gateway reconnect — re-issuing on the new session (attempt {Attempt}).",
_driverInstanceId, dialledRefs.Length, attempt + 1);
continue;
}
}
finally
{
earlyEventWindow.Dispose();
}
}
}
/// <summary>Bound on re-issuing a subscribe whose reply straddled a gateway reconnect (#861).</summary>
private const int MaxSubscribeSessionAttempts = 3;
private List<TagBinding> BuildSubscribeBindings(string[] dialledRefs, IReadOnlyList<SubscribeResult> results)
{
// Build the binding list in input order. Failed entries (gw rejected the tag) are
// recorded with a non-positive ItemHandle so the caller can detect partial failure
// by inspecting the returned handle's diagnostic context — full per-tag error
// surface lands in PR 5.3's parity tests.
// Index results once, correlate in O(1) per reference rather than
// FirstOrDefault inside the loop (O(n²) on the 50k-tag path).
// Bindings key on the dialled attributeRef — that's what the gw returns as the tag address and
// what the EventPump fans out on. OnPumpDataChange maps it back to RawPath for public consumers.
var resultIndex = BuildResultIndex(results);
var bindings = new List<TagBinding>(dialledRefs.Length);
for (var i = 0; i < dialledRefs.Length; i++)
{
var fullRef = dialledRefs[i];
var hasMatch = resultIndex.TryGetValue(fullRef, out var match);
var itemHandle = hasMatch && match is { WasSuccessful: true } ? match.ItemHandle : 0;
bindings.Add(new TagBinding(fullRef, itemHandle));
if (match is null || !match.WasSuccessful)
{
_logger.LogWarning(
"Galaxy subscribe for {FullRef} failed: {Error}",
fullRef, match?.ErrorMessage ?? "<no result returned>");
}
}
return bindings;
}
/// <inheritdoc />
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(handle);
if (handle is not GalaxySubscriptionHandle gsh)
{
throw new ArgumentException(
$"Subscription handle was not issued by this driver (expected GalaxySubscriptionHandle, got {handle.GetType().Name}).",
nameof(handle));
}
var bindings = _subscriptions.Remove(gsh.SubscriptionId, out var liveInCurrentSession);
_strandedSubscriptions.TryRemove(gsh.SubscriptionId, out _); // #862: gone ⇒ no longer degrades health
if (bindings is null) return; // already removed or never registered
// Not yet rebound after a reconnect: its handles died with the old session and the new one may
// have reused the numbers for other items — unsubscribing them would unadvise those (#861).
if (!liveInCurrentSession) return;
var liveItemHandles = bindings.Where(b => b.ItemHandle > 0).Select(b => b.ItemHandle).ToArray();
if (liveItemHandles.Length == 0 || _subscriber is null) return;
try
{
await UnsubscribeAndPurgeAsync(_subscriber, liveItemHandles, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"Galaxy UnsubscribeBulk failed for subscription {SubscriptionId} — registry already cleared on driver side.",
gsh.SubscriptionId);
}
}
/// <summary>A Subscribe/Read is refused while a teardown is in progress (the pump would belong to a dying subscriber).</summary>
private void ThrowIfRuntimeStopping()
{
lock (_pumpLock)
{
if (_runtimeStopping)
{
throw new InvalidOperationException(
"GalaxyDriver runtime is shutting down — no subscription can be served until the next InitializeAsync.");
}
}
}
/// <summary>
/// Lazily start the <see cref="EventPump"/> on the first advise. Since #865 the advise paths
/// (probe seed, Subscribe, Read) go through <see cref="AwaitCurrentEventStreamAsync"/>, and only the
/// replay replaces an existing pump. The pump is shared across every subscription on this driver —
/// fan-out happens through the <see cref="SubscriptionRegistry"/> reverse map, not by spinning a pump
/// per subscription.
/// </summary>
private EventPump EnsureEventPumpStarted()
{
lock (_pumpLock)
{
// Checked BEFORE the reuse: the flag is set before the teardown takes the pump under this
// same lock, so while it is set the live pump belongs to a dying subscriber. Handing it out
// would register handles into a registry the teardown is about to clear; creating a new one
// would leave a pump on the dead subscriber for the next InitializeAsync to inherit.
if (_runtimeStopping)
{
throw new InvalidOperationException(
"GalaxyDriver runtime is shutting down — no subscription can be served until the next InitializeAsync.");
}
if (_eventPump is not null) return _eventPump;
// The fault callback carries the pump's identity, so a late fault from a pump that is no
// longer the live one (a stale pump of a reopened session) is not escalated (#865 review).
EventPump? created = null;
created = new EventPump(
_subscriber!, _subscriptions, _logger,
channelCapacity: _options.MxAccess.EventPumpChannelCapacity,
clientName: _options.MxAccess.ClientName,
onStreamFault: cause => OnEventPumpStreamFault(created, cause),
onReplayGap: OnEventPumpReplayGap);
_eventPump = created;
_eventPump.OnDataChange += OnPumpDataChange;
_eventPump.Start();
return _eventPump;
}
}
/// <summary>
/// <see cref="EnsureEventPumpStarted"/> for infrastructure callers that must not fail because the
/// runtime is going away: null — and no pump — while a teardown is in progress or there is no subscriber.
/// </summary>
/// <returns>The running (or just started) pump; null when none may be started.</returns>
private EventPump? TryEnsureEventPumpStarted()
{
lock (_pumpLock)
{
if (_runtimeStopping || _disposed || _subscriber is null) return null;
try
{
return EnsureEventPumpStarted(); // re-enters _pumpLock (Lock is reentrant)
}
catch (InvalidOperationException)
{
// _runtimeStopping is written without _pumpLock; a teardown that flipped it between the
// check above and EnsureEventPumpStarted's own check is the same "no pump" answer.
return null;
}
}
}
/// <summary>
/// Upper bound on how long an advise waits for a current-session event stream (#865) — including, on a
/// gateway with the stream-attached ack, the ack itself (#877). Kept well under Galaxy's Tier-A Read (2 s) /
/// Subscribe (5 s) call budgets, so the "proceed anyway" fallback is reachable before the resilience
/// pipeline times the call out. The ack normally lands within one round trip, so a timeout on that path is
/// a fault worth a warning, not a routine fallback.
/// </summary>
internal TimeSpan StreamRequestWait { get; set; } = TimeSpan.FromSeconds(1);
/// <summary>
/// #865 — make sure an advise about to be issued has an event stream for its initial value, and return
/// the registry session to issue (and register) it under.
/// </summary>
/// <remarks>
/// <para>
/// A fresh StreamEvents (after_worker_sequence = 0) is never replayed, so an initial value pushed before
/// the stream attaches is lost — and a slow-changing attribute (ScanState, a setpoint) may not publish
/// again for a long time. So: start the pump if there is none, and wait until its stream is attached.
/// </para>
/// <para>
/// #877 — when the gateway advertised <c>stream-events-attached-ack</c> (<see cref="EventPump.AttachAckExpected"/>),
/// "attached" is deterministic: the wait is on <see cref="EventPump.StreamAttached"/>, the gateway's sentinel
/// that the stream is registered on the session, so the advise cannot lose its initial value. An older
/// gateway has no ack; the wait falls back to <see cref="EventPump.StreamRequested"/> (the stream call has
/// started), which only narrows the attach race.
/// </para>
/// <para>
/// A pump bound to an OLDER session belongs to a gateway session a reconnect replaced (the reopen →
/// replay window): an advise now would go to the recreated session with no stream for it, and —
/// registered under the current session — the replay would not re-advise it. The pump is not replaced
/// here (only <see cref="ReplayAsync"/> restarts it, so two streams never race for the gateway's
/// single-subscriber slot); while the supervisor is actually reopening/replaying the advise WAITS for the
/// replay's pump. During a reconnect BACKOFF (TransportLost) no replay is imminent, so it does not wait.
/// The returned session is the one the pump was verified against: a reconnect after this check makes the
/// caller's registration fail as a session straddle (#861), whose retry comes back through here.
/// </para>
/// <para>
/// Bounded by <see cref="StreamRequestWait"/> per call (a #861 retry starts a new budget). On timeout the
/// caller proceeds with the current session — no worse than the pre-#865 behaviour, but note the cost:
/// such an advise registers as current, so the replay will not re-advise it, and its initial value is
/// lost until the attribute next changes.
/// </para>
/// <para>
/// A current-session pump whose loop has ENDED is not a stream (its <see cref="EventPump.StreamRequested"/>
/// completes on exit). If the supervisor already reports Healthy, its fault was swallowed while it was
/// recovering (it ignores faults outside Healthy) — the driver would be deaf while Healthy — so it is
/// reported again to start a new recovery cycle.
/// </para>
/// </remarks>
/// <param name="cancellationToken">Cancels the wait.</param>
/// <returns>The registry session to issue the advise under.</returns>
private async Task<int> AwaitCurrentEventStreamAsync(CancellationToken cancellationToken)
{
var elapsed = System.Diagnostics.Stopwatch.StartNew();
while (true)
{
var session = _subscriptions.CurrentSession;
EventPump? pump;
bool restarting;
lock (_pumpLock)
{
restarting = _pumpRestarting;
pump = restarting ? null : TryEnsureEventPumpStarted();
}
if (pump is null && !restarting) return session; // tearing down — the caller's own fences decide
var remaining = StreamRequestWait - elapsed.Elapsed;
if (pump is not null && pump.Session == session)
{
if (pump.HasEnded)
{
ReportEndedPump(pump);
return session;
}
if (remaining > TimeSpan.Zero)
{
try
{
await pump.StreamRequested.WaitAsync(remaining, cancellationToken).ConfigureAwait(false);
// AttachAckExpected is published before StreamRequested completes (#877).
if (pump.AttachAckExpected && !pump.HasEnded)
{
remaining = StreamRequestWait - elapsed.Elapsed;
if (remaining < TimeSpan.Zero) remaining = TimeSpan.Zero;
try
{
await pump.StreamAttached.WaitAsync(remaining, cancellationToken).ConfigureAwait(false);
}
catch (TimeoutException)
{
if (pump.HasEnded) ReportEndedPump(pump);
LogNoStreamAttachedAck();
return session;
}
}
if (pump.HasEnded) ReportEndedPump(pump);
return session;
}
catch (TimeoutException)
{
// fall through to the log
}
}
else if (pump.StreamRequested.IsCompleted
&& (!pump.AttachAckExpected || pump.StreamAttached.IsCompleted))
{
if (pump.HasEnded) ReportEndedPump(pump);
return session;
}
}
else if (remaining > TimeSpan.Zero && ReplayExpectedSoon())
{
// Reopen → replay window: the replay restarts the pump for the current session.
await Task.Delay(TimeSpan.FromMilliseconds(20), cancellationToken).ConfigureAwait(false);
continue;
}
LogNoCurrentStream();
return _subscriptions.CurrentSession;
}
}
/// <summary>
/// True when a stale pump will be replaced shortly: a reopen/replay attempt is running, or there is
/// no supervisor (the injected-seam path, where the replay is driven directly), or a restart is underway.
/// </summary>
private bool ReplayExpectedSoon()
{
if (Volatile.Read(ref _pumpRestarting)) return true;
var supervisor = _supervisor;
if (supervisor is null) return true;
// Not the state: between attempts (the backoff delay, up to MaxBackoff) it still reads
// Reopening/Replaying while no replay is coming any time soon.
return supervisor.AttemptInProgress;
}
/// <summary>A current-session pump's loop ended while the supervisor was not listening (see AwaitCurrentEventStreamAsync).</summary>
private void ReportEndedPump(EventPump pump)
{
var supervisor = _supervisor;
if (supervisor is null || _runtimeStopping || supervisor.CurrentState != ReconnectSupervisor.State.Healthy) return;
lock (_pumpLock)
{
if (!ReferenceEquals(_eventPump, pump)) return; // already replaced
}
_logger.LogWarning(
"GalaxyDriver {InstanceId} event stream has ended while the reconnect supervisor reports Healthy — re-reporting the transport failure.",
_driverInstanceId);
try { supervisor.ReportTransportFailure(new InvalidOperationException("The Galaxy event stream ended; no events can be received.")); }
catch (ObjectDisposedException) { /* driver disposing */ }
}
private long _lastNoStreamWarningTicks;
private long _lastNoAckWarningTicks;
/// <summary>
/// #877 — the gateway advertised the stream-attached ack but did not send it within
/// <see cref="StreamRequestWait"/>. Loud (Warning, once a minute) because the capability promises the
/// sentinel as the stream's first message: its absence means a slow/stuck attach or a gateway bug, and the
/// advise proceeding now may lose its initial value.
/// </summary>
private void LogNoStreamAttachedAck()
{
var now = Environment.TickCount64;
var last = Interlocked.Read(ref _lastNoAckWarningTicks);
if ((last == 0 || now - last >= 60_000)
&& Interlocked.CompareExchange(ref _lastNoAckWarningTicks, now, last) == last)
{
_logger.LogWarning(
"GalaxyDriver {InstanceId}: the gateway advertises stream-events-attached-ack but its event stream sent no attach acknowledgement within {Wait} — advising anyway; initial values may be missed.",
_driverInstanceId, StreamRequestWait);
return;
}
_logger.LogDebug(
"GalaxyDriver {InstanceId} advising without the event stream's attach acknowledgement (warning rate-limited).",
_driverInstanceId);
}
/// <summary>Warning at most once a minute while the supervisor is Healthy; Debug otherwise (an outage would flood).</summary>
private void LogNoCurrentStream()
{
var supervisor = _supervisor;
var now = Environment.TickCount64;
var last = Interlocked.Read(ref _lastNoStreamWarningTicks);
if ((supervisor is null || supervisor.CurrentState == ReconnectSupervisor.State.Healthy)
&& (last == 0 || now - last >= 60_000)
&& Interlocked.CompareExchange(ref _lastNoStreamWarningTicks, now, last) == last)
{
_logger.LogWarning(
"GalaxyDriver {InstanceId} had no started event stream for the current gateway session within {Wait} — advising anyway; initial values may be missed.",
_driverInstanceId, StreamRequestWait);
return;
}
_logger.LogDebug(
"GalaxyDriver {InstanceId} advising without a started current-session event stream (supervisor not Healthy or warning rate-limited).",
_driverInstanceId);
}
/// <summary>
/// #865 — the probe watcher's pre-subscribe hook (<see cref="AwaitCurrentEventStreamAsync"/>). A probe's
/// initial ScanState value is usually its only event, and a driver with no authored tags never
/// Reads/Subscribes, so without this its pump — and every host status — never existed.
/// </summary>
private Task<int> EnsureProbeEventStreamAsync(CancellationToken cancellationToken)
{
// A seed pass a teardown already cancelled must not start a pump after the teardown finished.
cancellationToken.ThrowIfCancellationRequested();
return AwaitCurrentEventStreamAsync(cancellationToken);
}
/// <summary>
/// Replay-gap callback for the <see cref="EventPump"/>. The gateway told us it evicted
/// events we can never receive, so every cached value may be stale by an unknown amount.
/// The contract's remedy is to re-snapshot, which for this driver means re-issuing
/// SubscribeBulk: MXAccess delivers an initial value per item on subscribe, so the
/// re-subscribe is the re-snapshot.
/// </summary>
/// <remarks>
/// Three things this must not do, in order of how badly they would bite:
/// <list type="bullet">
/// <item>It must <b>not</b> restart the event pump. A gap is not a fault — the stream
/// that delivered the sentinel is healthy — and this runs ON that stream's read loop,
/// so disposing the pump from here would deadlock on its own loop.</item>
/// <item>It must <b>not</b> block. The read loop is stopped for as long as this runs,
/// and re-subscribing thousands of tags is a round-trip per subscription, so the work
/// goes to the thread pool and the loop returns to draining the stream immediately.</item>
/// <item>It must <b>not</b> stack. Re-entry is gated, so a burst of sentinels (or one
/// arriving while a re-snapshot is still running) collapses to a single pass rather
/// than queueing a subscribe storm per sentinel.</item>
/// </list>
/// <see cref="GalaxyReconnectOptions.ReplayOnSessionLost"/> is honoured here even though the
/// trigger is not a session loss: an operator who turned driver-side re-subscription off
/// is delegating recovery to the gateway, and quietly re-subscribing behind that choice
/// on a different trigger would be the same surprise they opted out of.
/// </remarks>
private void OnEventPumpReplayGap(ReplayGap gap)
{
if (_subscriber is null || _runtimeStopping) return;
if (!_options.Reconnect.ReplayOnSessionLost)
{
_logger.LogWarning(
"GalaxyDriver {InstanceId} replay-gap re-snapshot skipped — ReplayOnSessionLost=false. " +
"Values missed between worker_sequence {RequestedAfter} and {OldestAvailable} stay stale " +
"until the gateway or an operator re-primes them.",
_driverInstanceId, gap.RequestedAfterSequence, gap.OldestAvailableSequence);
return;
}
if (Interlocked.Exchange(ref _resnapshotInFlight, 1) == 1)
{
_logger.LogInformation(
"GalaxyDriver {InstanceId} replay-gap re-snapshot already in flight — coalescing.",
_driverInstanceId);
return;
}
var generation = Volatile.Read(ref _runtimeGeneration);
_ = Task.Run(async () =>
{
try
{
var entries = _subscriptions.SnapshotEntries();
if (entries.Count == 0) return;
var tagCount = await ResubscribeAllAsync(entries, generation, CancellationToken.None).ConfigureAwait(false);
_logger.LogInformation(
"GalaxyDriver {InstanceId} replay-gap re-snapshot completed — {SubCount} subscriptions, {TagCount} tags re-subscribed",
_driverInstanceId, entries.Count, tagCount);
}
catch (Exception ex)
{
// Never surface into the pump's read loop; the stream is still healthy and
// must keep draining. A failed re-snapshot leaves stale values, which the
// next reconnect or subscribe will correct.
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} replay-gap re-snapshot failed — cached values may stay stale.",
_driverInstanceId);
}
finally
{
Interlocked.Exchange(ref _resnapshotInFlight, 0);
}
});
}
/// <summary>
/// Stream-fault callback for the <see cref="EventPump"/>. The gw StreamEvents
/// stream faulted (transient gateway drop, network blip, gw restart). Forward
/// the cause to the <see cref="ReconnectSupervisor"/> so it drives reopen →
/// replay; without this hand-off a transient transport drop permanently kills
/// the event stream and <c>GetHealth()</c> keeps reporting Healthy.
/// </summary>
private int _escalatedStreamFaults;
/// <summary>Test seam (#865): stream faults that passed the superseded-pump filter (escalated toward the supervisor).</summary>
internal int EscalatedStreamFaultsForTests => Volatile.Read(ref _escalatedStreamFaults);
private void OnEventPumpStreamFault(EventPump? source, Exception cause)
{
if (_runtimeStopping)
{
// The pump is being torn down with the rest of the runtime — a fault it reports on the
// way out is shutdown noise, not something to recover from.
_logger.LogDebug(cause, "GalaxyDriver {InstanceId} event stream ended during runtime teardown.", _driverInstanceId);
return;
}
if (source is not null)
{
bool stale;
lock (_pumpLock) stale = !ReferenceEquals(_eventPump, source) || source.Session != _subscriptions.CurrentSession;
if (stale)
{
// A pump that is no longer the live one: the identity check does the work (the replay
// replaces/replaced it). The session part only matters between a reopen and its replay,
// where the supervisor ignores faults anyway — ⚠️ a future session bump while Healthy that
// keeps the same pump would make its real faults look stale here. Its fault says nothing
// about the current transport, and reported while Replaying it would fail a good replay.
_logger.LogDebug(cause, "GalaxyDriver {InstanceId} ignored a stream fault from a superseded event pump.", _driverInstanceId);
return;
}
}
Interlocked.Increment(ref _escalatedStreamFaults);
var supervisor = _supervisor;
if (supervisor is null)
{
// No production runtime (skeleton / injected-seam path) — nothing to drive.
_logger.LogWarning(cause,
"GalaxyDriver {InstanceId} event stream faulted but no reconnect supervisor is wired.",
_driverInstanceId);
return;
}
try
{
supervisor.ReportTransportFailure(cause);
}
catch (ObjectDisposedException)
{
// Driver is being disposed — the stream fault is just shutdown noise.
}
}
// ===== IAlarmSource =====
/// <summary>
/// Start the gateway alarm feed (idempotent) and wire its transitions onto this
/// driver's <see cref="OnAlarmEvent"/> bridge. The feed is session-less — it does
/// not depend on a data subscription or the <see cref="EventPump"/>.
/// </summary>
private void EnsureAlarmFeedStarted()
{
lock (_alarmFeedLock)
{
if (_alarmFeed is null)
{
throw new InvalidOperationException(
"GalaxyDriver alarm feed is not wired. InitializeAsync must run (or a feed " +
"seam must be injected via the internal ctor) before subscribing to alarms.");
}
if (_alarmFeedWired) return;
_alarmFeed.OnAlarmTransition += OnAlarmFeedTransition;
_alarmFeed.Start();
_alarmFeedWired = true;
}
}
/// <inheritdoc />
public Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(
IReadOnlyList<string> sourceNodeIds, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(sourceNodeIds);
// The driver doesn't multiplex alarm subscriptions per source-node-id today —
// every active handle receives every transition off the gateway's session-less
// StreamAlarms feed, and the server filters by source node before raising Part 9
// conditions. The subscription handle is a sentinel the server uses for
// symmetric Unsubscribe. Same shape AbCip uses.
EnsureAlarmFeedStarted();
var handle = new GalaxyAlarmSubscriptionHandle(Guid.NewGuid().ToString("N"));
lock (_alarmHandlersLock)
{
// Collapse to a SINGLE live handle. The session-less StreamAlarms feed survives an in-place
// reconnect, so DriverInstanceActor re-subscribing on every Connected re-entry (after dropping
// its own cached handle) would otherwise grow this list by one untracked handle per reconnect —
// a slow leak (the gate only checks Count > 0 and OnAlarmFeedTransition only reads [0], so the
// extras were pure dead weight). There is exactly one consumer per driver instance — enforced
// structurally by the factory-per-actor lifecycle (one GalaxyDriver is created for one owning
// DriverInstanceActor, the only caller of SubscribeAlarmsAsync), not by mere convention — so
// replacing the set with the latest handle is semantically faithful and bounds it at 1.
_alarmSubscriptions.Clear();
_alarmSubscriptions.Add(handle);
}
return Task.FromResult<IAlarmSubscriptionHandle>(handle);
}
/// <inheritdoc />
public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(handle);
if (handle is not GalaxyAlarmSubscriptionHandle gash)
{
throw new ArgumentException(
$"Subscription handle was not issued by this driver (expected GalaxyAlarmSubscriptionHandle, got {handle.GetType().Name}).",
nameof(handle));
}
lock (_alarmHandlersLock)
{
_alarmSubscriptions.Remove(gash);
}
return Task.CompletedTask;
}
/// <inheritdoc />
public async Task AcknowledgeAsync(
IReadOnlyList<AlarmAcknowledgeRequest> acknowledgements, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(acknowledgements);
if (acknowledgements.Count == 0) return;
if (_alarmAcknowledger is null)
{
throw new NotSupportedException(
"GalaxyDriver.AcknowledgeAsync requires GatewayGalaxyAlarmAcknowledger wired against a connected " +
"GalaxyMxSession. InitializeAsync must complete successfully before alarm acknowledgements can flow.");
}
// Acks are issued one-by-one — the gateway RPC accepts a single alarm
// reference per call. AlarmConditionState's per-condition Acknowledge in the
// server-side ACL layer is the natural rate-limit, so issuing in series here
// keeps the operator-comment ordering deterministic without bursting the
// worker's STA queue.
foreach (var ack in acknowledgements)
{
// ConditionId carries the alarm's RawPath (v3) for the Galaxy driver — SourceNodeId is the
// OPC UA browse path, which the gateway can't address. Translate the RawPath back to the
// Galaxy attributeRef the gateway dials (identity on a miss). The server-side condition state
// pairs them through AlarmConditionService.
var conditionReference = !string.IsNullOrEmpty(ack.ConditionId)
? ack.ConditionId
: ack.SourceNodeId;
var alarmFullReference = ToAlarmAckReference(conditionReference);
// lmxopcua#749: the gateway acknowledges as a real Galaxy account (AuthenticateUser +
// AckMsg write), and the OPC UA session has no Galaxy password. Resolve the account mapped
// to the session's API key, else the driver's fallback account; with neither, refuse —
// nothing is sent, and never with an empty operator_user.
var resolution = await _ackCredentialResolver
.ResolveAsync(ack.ApiKeyId, cancellationToken).ConfigureAwait(false);
if (resolution.Credential is not { } credential)
{
_logger.LogWarning(
"Galaxy driver {DriverInstanceId}: acknowledge of {AlarmRef} by OPC UA principal {Principal} (key {ApiKeyId}) refused: {Reason}",
_driverInstanceId, alarmFullReference, PrincipalOf(ack), ack.ApiKeyId ?? "none", resolution.RefusalReason);
throw new DriverOperationRefusedException(
$"Galaxy acknowledge of '{alarmFullReference}' refused: {resolution.RefusalReason}");
}
// The Historian records the Galaxy account; keep the OPC UA principal + key id with the ack
// so it isn't lost when the account is a shared fallback.
var comment = AnnotateAckComment(ack.Comment, ack.OperatorUser, ack.ApiKeyId);
_logger.LogInformation(
"Galaxy driver {DriverInstanceId}: acknowledging {AlarmRef} as Galaxy user {GalaxyUser} ({CredentialSource}) for OPC UA principal {Principal} (key {ApiKeyId})",
_driverInstanceId, alarmFullReference, credential.DisplayName, credential.Source,
PrincipalOf(ack), ack.ApiKeyId ?? "none");
// lmxopcua#869: the gateway's OK can mean "sent but unconfirmed". Watch for Galaxy's own acknowledged
// transition from BEFORE the RPC — the feed can deliver it ahead of the unary reply — and arm the
// watch when the reply is unconfirmed; ConfirmAcknowledgedAsync then awaits it, bounded.
var watch = _ackConfirmations.Begin(ack, alarmFullReference);
var armed = false;
try
{
var outcome = await _alarmAcknowledger.AcknowledgeAsync(
alarmFullReference, comment, credential, cancellationToken).ConfigureAwait(false);
if (!outcome.IsApplied)
{
_ackConfirmations.Arm(watch, outcome.Diagnostic);
armed = true;
}
}
finally
{
if (!armed) _ackConfirmations.Release(watch);
}
}
}
/// <inheritdoc />
/// <remarks>
/// lmxopcua#869: completes at once for an ack the gateway reported applied; for one it only SENT, waits up to
/// <c>AlarmAck.ConfirmTimeoutMs</c> (default 10 s) for Galaxy's acknowledged transition on the alarm feed and
/// throws <see cref="DriverOperationRefusedException"/> when it does not come — the host then reverts the
/// condition to unacknowledged. The feed must be running (it is whenever the host holds native conditions,
/// the only way an ack reaches this driver); without it nothing can confirm and the ack reverts.
/// </remarks>
public Task ConfirmAcknowledgedAsync(
IReadOnlyList<AlarmAcknowledgeRequest> acknowledgements, CancellationToken cancellationToken) =>
_ackConfirmations.ConfirmAsync(acknowledgements, cancellationToken);
/// <inheritdoc />
/// <remarks>
/// Only cases decidable without I/O, on a driver with no <c>AlarmAck.FallbackUser</c>: an anonymous session
/// (lmxopcua#760 — no API key, so no key-mapped Galaxy identity can exist), and a keyed session whose key the
/// <see cref="IGalaxyAckIdentityDirectory"/> reports <see cref="GalaxyAckIdentityPresence.Absent"/>
/// (lmxopcua#765 — a cached, periodically refreshed view of the Secrets store, because the store itself must
/// not be read under the SDK lock). Anything the directory does not know for certain (no directory, no
/// refresh yet, stale, a change pending) is let through: <see cref="AcknowledgeAsync"/> still refuses it,
/// and the host reverts the condition. A refusal also asks the directory to refresh, so a retry after an
/// identity was set out of band (the <c>secret</c> CLI) is not refused for a whole refresh interval.
/// </remarks>
public string? GetAcknowledgeRefusal(string? apiKeyId)
{
if (_options.AlarmAck?.HasFallback ?? false) return null;
if (string.IsNullOrWhiteSpace(apiKeyId))
{
return $"the session is anonymous (no API key) and Galaxy driver '{_driverInstanceId}' has no " +
"AlarmAck.FallbackUser configured, so the acknowledge cannot be sent to Galaxy. Connect with an API key " +
"that has a Galaxy ack identity (AdminUI /api-keys) or configure the driver's fallback ack account.";
}
if (_ackIdentityDirectory is not { } directory
|| directory.GetPresence(apiKeyId) != GalaxyAckIdentityPresence.Absent) return null;
directory.RequestRefresh();
return $"API key '{apiKeyId.Trim()}' has no Galaxy ack identity and Galaxy driver '{_driverInstanceId}' has no " +
"AlarmAck.FallbackUser configured, so the acknowledge cannot be sent to Galaxy. Map a Galaxy ack identity " +
"to the key (AdminUI /api-keys) or configure the driver's fallback ack account.";
}
private static string PrincipalOf(AlarmAcknowledgeRequest ack) =>
string.IsNullOrWhiteSpace(ack.OperatorUser) ? "anonymous" : ack.OperatorUser;
/// <summary>
/// Appends the OPC UA identity to the ack comment written to <c>AckMsg</c> (lmxopcua#749), e.g.
/// <c>"shift handover [OPC UA: mes-line1, key 0a1b…]"</c> or <c>"[OPC UA: anonymous]"</c>. The
/// Historian's Operator column holds the Galaxy account (possibly a shared fallback), so this is
/// the durable record of which client acknowledged.
/// </summary>
/// <param name="comment">The operator's comment, or null.</param>
/// <param name="principal">The OPC UA principal, or null/empty for anonymous.</param>
/// <param name="apiKeyId">The authenticating key id, or null.</param>
/// <returns>The annotated comment.</returns>
internal static string AnnotateAckComment(string? comment, string? principal, string? apiKeyId)
{
var who = string.IsNullOrWhiteSpace(principal) ? "anonymous" : principal.Trim();
var tag = string.IsNullOrWhiteSpace(apiKeyId) ? $"[OPC UA: {who}]" : $"[OPC UA: {who}, key {apiKeyId}]";
return string.IsNullOrWhiteSpace(comment) ? tag : $"{comment.TrimEnd()} {tag}";
}
/// <summary>
/// Receives <see cref="GalaxyAlarmTransition"/> events from the gateway alarm
/// feed and reshapes them into <see cref="AlarmEventArgs"/> for OPC UA-side
/// consumers. Fires <see cref="OnAlarmEvent"/> only when at least one alarm
/// subscription is active so a server that hasn't called
/// <see cref="SubscribeAlarmsAsync"/> yet doesn't surface untracked transitions.
/// </summary>
private void OnAlarmFeedTransition(object? sender, GalaxyAlarmTransition transition)
{
// lmxopcua#869: an acknowledged transition confirms any ack the gateway sent unconfirmed — before the
// subscription gate below, which only governs fan-out to OnAlarmEvent.
_ackConfirmations.Observe(transition);
// v3: the ConditionId the driver reports must be the tag's RawPath — the same key the value
// fan-out uses (OnPumpDataChange) and the identity the discoverer stamped as SourceName — so the
// server-side condition state correlates the alarm to its node and a subsequent ack round-trips
// back through AcknowledgeAsync. The feed reports the provider-qualified reference
// (Galaxy!Area.tag.Attr); reverse-map it to the authored tag, also through the plain tag.Attr form the
// AdminUI picker authors (lmxopcua#895), identity on a miss. Resolved ahead of the subscription gate so
// every transition the driver sees teaches the ack reference, fanned out or not.
var conditionRawPath = ResolveAlarmRawPath(transition.AlarmFullReference, transition.SourceObjectReference);
GalaxyAlarmSubscriptionHandle? handle;
int subCount;
lock (_alarmHandlersLock)
{
// Pick the earliest-registered handle as the event owner. The server routes
// by SourceNodeId (not by handle), so every active subscriber sees the same
// transition regardless of which handle is attached here. Using the first
// insertion-order entry is deterministic and stable as long as at least one
// subscription remains — HashSet.First() was unstable across mutations.
// _alarmSubscriptions is a List, so [0] is always the earliest-registered
// handle.
subCount = _alarmSubscriptions.Count;
handle = subCount > 0 ? _alarmSubscriptions[0] : null;
}
// Native-alarm delivery observability (was a black box): one line per feed transition with the
// resolved alarm ref, the live subscription count, and whether it fans out to OnAlarmEvent. Debug
// so a flapping galaxy doesn't flood prod, but available on demand to answer "is the feed
// delivering / is the subscription un-gating it" — the exact question this driver couldn't answer
// before the SubscribeAlarmsAsync wiring fix.
_logger.LogDebug(
"GalaxyDriver alarm feed: {Kind} {Ref} (subs={Subs}, fanout={Fanout})",
transition.TransitionKind, transition.AlarmFullReference, subCount, handle is not null);
if (handle is null) return;
var args = new AlarmEventArgs(
SubscriptionHandle: handle,
SourceNodeId: transition.SourceObjectReference,
ConditionId: conditionRawPath,
AlarmType: transition.AlarmTypeName,
Message: transition.Description,
Severity: transition.SeverityBucket,
// lmxopcua#887: the exact Part 9 severity from the priority table, so the live condition reads the same
// number as its AVEVA history row (EventMapper → GalaxyAlarmPriority). Without it the host would re-map the
// bucket through its generic 200/500/700/900 ladder and live and history would disagree.
OpcUaSeverity: transition.OpcUaSeverity,
SourceTimestampUtc: transition.TransitionTimestampUtc,
OperatorComment: string.IsNullOrEmpty(transition.OperatorComment) ? null : transition.OperatorComment,
OriginalRaiseTimestampUtc: transition.OriginalRaiseTimestampUtc,
AlarmCategory: string.IsNullOrEmpty(transition.Category) ? null : transition.Category,
// Fully-qualify the Core.Abstractions enum: this file also imports
// MxGateway.Contracts.Proto, which defines a same-named AlarmTransitionKind.
Kind: transition.TransitionKind switch
{
GalaxyAlarmTransitionKind.Raise => Core.Abstractions.AlarmTransitionKind.Raise,
GalaxyAlarmTransitionKind.Acknowledge => Core.Abstractions.AlarmTransitionKind.Acknowledge,
GalaxyAlarmTransitionKind.Clear => Core.Abstractions.AlarmTransitionKind.Clear,
GalaxyAlarmTransitionKind.Retrigger => Core.Abstractions.AlarmTransitionKind.Retrigger,
GalaxyAlarmTransitionKind.ActiveAcknowledged => Core.Abstractions.AlarmTransitionKind.ActiveAcknowledged,
_ => Core.Abstractions.AlarmTransitionKind.Unspecified,
},
// A snapshot entry re-states upstream state — history-only signal for the host.
IsRestatement: transition.IsRestatement);
try
{
OnAlarmEvent?.Invoke(this, args);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver OnAlarmEvent handler threw for {AlarmRef} — continuing.",
transition.AlarmFullReference);
}
}
/// <summary>
/// Forwards every fan-out event to the public <see cref="OnDataChange"/> for
/// ISubscribable consumers, AND routes ScanState changes to the per-platform
/// probe watcher (PR 4.7) so platform health entries update without the watcher
/// consuming the event stream itself.
/// </summary>
private void OnPumpDataChange(object? sender, DataChangeEventArgs args)
{
// Anything the gateway pushes on the stream proves it is alive and serving this session —
// the comms-loss watchdog's evidence (G-11: the stamp used to move only at init and on a
// supervisor Healthy transition, so a 90 s Degraded tripped a re-init under flowing data).
StampLiveness();
// Subscribe-once reads listen here (attributeRef domain), not on a pump instance: a reconnect
// replaces the pump, and a read attached to the dead one never saw the replayed value (#859 B-1).
try { ReadDataChange?.Invoke(this, args); }
catch (Exception ex)
{
_logger.LogWarning(ex, "GalaxyDriver {InstanceId} read listener threw — continuing.", _driverInstanceId);
}
// Probe traffic rides the reserved registry entry and stays in the attributeRef domain —
// ScanState attributes are discovered platform attributes, never authored RawPaths. It is
// the watcher's alone: the host never subscribed it and must not see it on OnDataChange.
if (args.SubscriptionHandle is GalaxySubscriptionHandle { SubscriptionId: SubscriptionRegistry.ProbeSubscriptionId })
{
// The probe decoder takes a raw quality byte. Recover it via the canonical
// StatusCodeMap.ToQualityCategoryByte helper so the mapping lives in one
// place next to its inverse (FromQualityByte) and cannot desync silently.
var qualityByte = StatusCodeMap.ToQualityCategoryByte(args.Snapshot.StatusCode);
_probeWatcher?.OnProbeValueChanged(args.FullReference, args.Snapshot.Value, qualityByte);
return;
}
// v3: the pump fans out keyed by the dialled attributeRef; the server correlates values to nodes
// by RawPath (the node's FullName). Reverse-map before surfacing to public OnDataChange consumers.
// Identity on a miss, so a live-browse tag surfaces under its attributeRef unchanged.
var publicArgs = args;
var rawPath = ToRawPath(args.FullReference);
if (!string.Equals(rawPath, args.FullReference, StringComparison.Ordinal))
{
publicArgs = args with { FullReference = rawPath };
}
OnDataChange?.Invoke(this, publicArgs);
}
/// <summary>Minimum gap between two <c>LastSuccessfulRead</c> stamps from stream data. Internal so tests can widen it.</summary>
internal TimeSpan LivenessStampThrottle { get; set; } = TimeSpan.FromSeconds(1);
private long _lastLivenessStampTicks;
/// <summary>
/// Advance <c>LastSuccessfulRead</c> from inbound stream data, at most once per
/// <see cref="LivenessStampThrottle"/> — this runs on the pump's dispatch loop for every
/// event, so a 50k-tag galaxy must not pay a health-record allocation per value.
/// </summary>
private void StampLiveness()
{
var now = DateTime.UtcNow;
var last = Volatile.Read(ref _lastLivenessStampTicks);
if (now.Ticks - last < LivenessStampThrottle.Ticks) return;
Volatile.Write(ref _lastLivenessStampTicks, now.Ticks);
_health = _health with { LastSuccessfulRead = now };
}
/// <summary>
/// Lazily builds the default <see cref="IGalaxyHierarchySource"/> from
/// <c>_options.Gateway</c>. Owned <see cref="GalaxyRepositoryClient"/> is disposed in
/// <see cref="Dispose"/>. Tests bypass this by injecting their own source via the
/// internal ctor.
/// </summary>
private async Task<IGalaxyHierarchySource> BuildDefaultHierarchySourceAsync(CancellationToken cancellationToken)
{
// Reuse a client that StartDeployWatcherAsync may have already created (??=) rather
// than always overwriting the field and leaking the first instance. Both paths
// produce equivalent clients from the same options. The client-options build is
// async now (secret: arm resolves through the shared ISecretResolver).
_ownedRepositoryClient ??= GalaxyRepositoryClient.Create(
await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false));
return new TracedGalaxyHierarchySource(
new GatewayGalaxyHierarchySource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize),
_options.MxAccess.ClientName);
}
/// <summary>
/// Asynchronous disposal. Prefer <c>await using</c> over <c>using</c> — the
/// async path does not block the caller while awaiting EventPump / session /
/// client shutdown (the sync path blocks on <c>GetAwaiter().GetResult()</c>
/// for every async sub-component, risking a deadlock under thread-pool
/// starvation).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public async ValueTask DisposeAsync()
{
if (_disposed) return;
await _lifecycleGate.WaitAsync().ConfigureAwait(false);
try
{
if (_disposed) return;
_disposed = true;
// Same release sequence as ShutdownAsync, plus the injected seams this instance will
// never need again. Idempotent: a ShutdownAsync before this finds nothing left to do.
await TeardownRuntimeAsync(final: true, CancellationToken.None).ConfigureAwait(false);
}
finally
{
_lifecycleGate.Release();
}
}
/// <summary>
/// Synchronous disposal. Prefer <see cref="DisposeAsync"/> in async contexts —
/// this path must block on every async sub-component shutdown. Provided for
/// compatibility with <c>using</c> statements that cannot <c>await</c>.
/// </summary>
public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult();
/// <summary>
/// Address-space builder wrapper that records each variable's
/// <see cref="DriverAttributeInfo.SecurityClass"/> into the supplied dictionary
/// before delegating to the inner builder. Used by <see cref="DiscoverAsync"/>
/// to capture per-tag classifications for the IWritable routing decision —
/// PR 4.3 needs the data, but the discoverer itself doesn't (and shouldn't)
/// know about the driver's internal state.
/// </summary>
private sealed class SecurityCapturingBuilder(
IAddressSpaceBuilder inner,
System.Collections.Concurrent.ConcurrentDictionary<string, SecurityClassification> map)
: IAddressSpaceBuilder
{
/// <inheritdoc />
public IAddressSpaceBuilder Folder(string browseName, string displayName)
=> new SecurityCapturingBuilder(inner.Folder(browseName, displayName), map);
/// <inheritdoc />
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
{
map[attributeInfo.FullName] = attributeInfo.SecurityClass;
return inner.Variable(browseName, displayName, attributeInfo);
}
/// <inheritdoc />
public void AddProperty(string browseName, DriverDataType dataType, object? value)
=> inner.AddProperty(browseName, dataType, value);
}
}