Merge #991: Galaxy secured-write map filled at init, dropped pump events resync, deploy-watch backoff, replay-gap handle release, HTTP/2 keep-alive on driver channels

This commit is contained in:
Joseph Doherty
2026-12-03 10:36:36 -05:00
27 changed files with 2027 additions and 145 deletions
@@ -129,6 +129,14 @@ public sealed record GalaxyAlarmAckOptions(
// legitimate worst case while still failing fast on a wedged worker.
// StreamTimeoutSeconds = 0 — unlimited; the StreamEvents RPC must run for the
// lifetime of the driver. Set a finite value only for diagnostic runs.
// KeepAlivePingDelaySeconds = 15 / KeepAlivePingTimeoutSeconds = 10 (#991 G-19) — HTTP/2 PING
// frames on every gateway channel, sent even while no call is active. A long-lived
// server stream (StreamEvents, StreamAlarms, WatchDeployEvents) sends nothing after its
// request, so a gateway host that loses power or a firewall that starts dropping the
// flow (no FIN/RST) used to leave the stream waiting forever — Galaxy stayed Healthy
// serving stale Good values. An unanswered ping now fails the connection within
// delay + timeout (~25 s), the stream faults and the reconnect supervisor takes over.
// 0 disables the pings (the .NET default).
public sealed record GalaxyGatewayOptions(
string Endpoint,
string ApiKeySecretRef,
@@ -136,7 +144,9 @@ public sealed record GalaxyGatewayOptions(
string? CaCertificatePath = null,
int ConnectTimeoutSeconds = 10,
int DefaultCallTimeoutSeconds = 30,
int StreamTimeoutSeconds = 0);
int StreamTimeoutSeconds = 0,
int KeepAlivePingDelaySeconds = 15,
int KeepAlivePingTimeoutSeconds = 10);
/// <summary>
/// MXAccess-specific knobs the gateway forwards to the worker process.
@@ -27,17 +27,26 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
/// so a reconnect doesn't fan out a redundant rediscover for state we already
/// knew about.
/// </para>
/// <para>
/// A stream the gateway COMPLETES without an error is paced exactly like a fault (#991 G-3): it used to
/// loop straight back into a new RPC, and since every event — the bootstrap each stream delivers
/// included — reset the backoff, a gateway that ends its streams after the bootstrap (a drain, an
/// idle-stream limit) was re-subscribed as fast as the RPC round-trips. The backoff now resets only when
/// a stream stayed open for <c>stableStreamDuration</c>.
/// </para>
/// </remarks>
public sealed class DeployWatcher : IDisposable
{
private static readonly TimeSpan DefaultInitialBackoff = TimeSpan.FromSeconds(1);
private static readonly TimeSpan DefaultMaxBackoff = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DefaultStableStreamDuration = TimeSpan.FromSeconds(60);
private readonly IGalaxyDeployWatchSource _source;
private readonly ILogger _logger;
private readonly TimeSpan _initialBackoff;
private readonly TimeSpan _maxBackoff;
private readonly Func<int, TimeSpan>? _jitter;
private readonly TimeSpan _stableStreamDuration;
private CancellationTokenSource? _cts;
private Task? _loopTask;
@@ -63,13 +72,19 @@ public sealed class DeployWatcher : IDisposable
/// <param name="initialBackoff">Initial backoff duration for retry.</param>
/// <param name="maxBackoff">Maximum backoff duration for retry.</param>
/// <param name="jitter">Optional function to apply jitter to backoff intervals.</param>
/// <param name="stableStreamDuration">
/// How long a stream must stay open before its end resets the backoff (default 60 s). A shorter-lived
/// stream — clean completion or fault — keeps growing the backoff.
/// </param>
internal DeployWatcher(
IGalaxyDeployWatchSource source,
ILogger? logger,
TimeSpan initialBackoff,
TimeSpan maxBackoff,
Func<int, TimeSpan>? jitter)
Func<int, TimeSpan>? jitter,
TimeSpan? stableStreamDuration = null)
{
_stableStreamDuration = stableStreamDuration ?? DefaultStableStreamDuration;
_source = source ?? throw new ArgumentNullException(nameof(source));
_logger = logger ?? NullLogger.Instance;
_initialBackoff = initialBackoff;
@@ -140,6 +155,8 @@ public sealed class DeployWatcher : IDisposable
while (!cancellationToken.IsCancellationRequested)
{
var streamOpened = System.Diagnostics.Stopwatch.StartNew();
Exception? fault = null;
try
{
await foreach (DeployEvent ev in _source
@@ -147,10 +164,6 @@ public sealed class DeployWatcher : IDisposable
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
// Successful read — reset retry state.
backoff = _initialBackoff;
attempt = 0;
DateTimeOffset? observedTime = ev.TimeOfLastDeployPresent && ev.TimeOfLastDeploy is not null
? ev.TimeOfLastDeploy.ToDateTimeOffset()
: null;
@@ -200,10 +213,9 @@ public sealed class DeployWatcher : IDisposable
}
}
// Stream completed normally — gateway closed the subscription. Re-open
// immediately if we weren't asked to stop.
_logger.LogDebug("DeployWatcher stream completed; re-subscribing.");
continue;
// Stream completed normally — the gateway (or a proxy) closed the subscription. Paced below like
// a fault (#991 G-3): an immediate re-open hammered a gateway that ends every stream after the
// bootstrap event.
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
@@ -211,26 +223,47 @@ public sealed class DeployWatcher : IDisposable
}
catch (Exception ex)
{
attempt++;
TimeSpan jitterAmount = _jitter?.Invoke(attempt) ?? RandomJitter(backoff);
TimeSpan delay = backoff + jitterAmount;
_logger.LogWarning(ex,
fault = ex;
}
if (cancellationToken.IsCancellationRequested) break;
// Reset only after a stream that stayed up — an event alone (every stream's bootstrap) proves nothing
// about the gateway keeping it open.
if (streamOpened.Elapsed >= _stableStreamDuration)
{
backoff = _initialBackoff;
attempt = 0;
}
attempt++;
TimeSpan jitterAmount = _jitter?.Invoke(attempt) ?? RandomJitter(backoff);
TimeSpan delay = backoff + jitterAmount;
if (fault is not null)
{
_logger.LogWarning(fault,
"DeployWatcher source threw; retrying in {Delay} (attempt {Attempt}, last-seen time {LastSeen}).",
delay, attempt, lastSeenDeployTime);
try
{
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
// Exponential backoff capped at _maxBackoff.
var doubled = TimeSpan.FromTicks(Math.Min(_maxBackoff.Ticks, backoff.Ticks * 2));
backoff = doubled < _initialBackoff ? _initialBackoff : doubled;
}
else
{
_logger.LogDebug(
"DeployWatcher stream completed by the gateway after {Open}; re-subscribing in {Delay} (attempt {Attempt}).",
streamOpened.Elapsed, delay, attempt);
}
try
{
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
// Exponential backoff capped at _maxBackoff.
var doubled = TimeSpan.FromTicks(Math.Min(_maxBackoff.Ticks, backoff.Ticks * 2));
backoff = doubled < _initialBackoff ? _initialBackoff : doubled;
}
}
@@ -0,0 +1,114 @@
using System.Collections.Concurrent;
using Grpc.Core;
using ZB.MOM.WW.MxGateway.Client;
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
/// <summary>
/// Driver-side seam for the per-attribute <c>security_classification</c> of the AUTHORED Galaxy objects
/// (#991 G-1). <c>WriteAsync</c> routes SecuredWrite / VerifiedWrite attributes to <c>WriteSecured</c>; that
/// classification used to come only from <c>DiscoverAsync</c>, which the runtime never calls on a served driver,
/// so every write took the raw path. The driver seeds its security map from this at <c>InitializeAsync</c> and
/// on every deploy-watcher rediscovery.
/// </summary>
public interface IGalaxyAttributeSecuritySource
{
/// <summary>The named objects with their attributes. A name the Galaxy does not hold is simply absent.</summary>
/// <param name="tagNames">Object <c>tag_name</c>s (the part of an attributeRef before its first dot).</param>
/// <param name="cancellationToken">Cancellation token for the query.</param>
/// <returns>The objects found, each with its attributes.</returns>
Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken);
}
/// <summary>
/// Default <see cref="IGalaxyAttributeSecuritySource"/>: one <c>DiscoverHierarchy</c> per authored object, rooted
/// at its <c>tag_name</c> with <c>max_depth = 0</c> and attributes included — the cost scales with the authored
/// objects, not the Galaxy (the full-hierarchy dump the <c>/raw</c> picker pulls would be fetched on every driver
/// init). A bounded number run concurrently; an object the gateway reports <c>NotFound</c> is skipped.
/// </summary>
public sealed class GatewayGalaxyAttributeSecuritySource : IGalaxyAttributeSecuritySource
{
/// <summary>Concurrent per-object queries.</summary>
public const int MaxConcurrency = 4;
private readonly GalaxyRepositoryClient _client;
/// <summary>Initializes a new instance of the <see cref="GatewayGalaxyAttributeSecuritySource"/> class.</summary>
/// <param name="client">The gateway's Galaxy repository client.</param>
public GatewayGalaxyAttributeSecuritySource(GalaxyRepositoryClient client)
=> _client = client ?? throw new ArgumentNullException(nameof(client));
/// <inheritdoc />
public Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(
IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken)
=> QueryAsync(_client.DiscoverHierarchyRawAsync, tagNames, MaxConcurrency, cancellationToken);
/// <summary>The per-object queries behind a delegate, so they are unit-testable without a channel.</summary>
/// <param name="discover">The raw <c>DiscoverHierarchy</c> RPC.</param>
/// <param name="tagNames">The objects to fetch.</param>
/// <param name="maxConcurrency">Concurrent queries.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The objects found (only the requested root of each reply).</returns>
internal static async Task<IReadOnlyList<GalaxyObject>> QueryAsync(
Func<DiscoverHierarchyRequest, CancellationToken, Task<DiscoverHierarchyReply>> discover,
IReadOnlyCollection<string> tagNames,
int maxConcurrency,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(discover);
var found = new ConcurrentBag<GalaxyObject>();
await Parallel.ForEachAsync(
tagNames,
new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, maxConcurrency), CancellationToken = cancellationToken },
async (tagName, token) =>
{
var request = new DiscoverHierarchyRequest
{
RootTagName = tagName,
MaxDepth = 0,
IncludeAttributes = true,
PageSize = 1,
};
DiscoverHierarchyReply reply;
try
{
reply = await discover(request, token).ConfigureAwait(false);
}
catch (Exception ex) when (IsNotFound(ex))
{
return; // not deployed (any more) — no classification to learn
}
foreach (var obj in reply.Objects)
{
if (string.Equals(obj.TagName, tagName, StringComparison.OrdinalIgnoreCase)) found.Add(obj);
}
}).ConfigureAwait(false);
return [.. found];
}
private static bool IsNotFound(Exception ex)
{
for (var e = ex; e is not null; e = e.InnerException)
{
if (e is RpcException { StatusCode: StatusCode.NotFound }) return true;
}
return false;
}
}
/// <summary>
/// <see cref="IGalaxyAttributeSecuritySource"/> over an injected <see cref="IGalaxyHierarchySource"/> — the
/// seam-mode fallback, so a driver built around a hierarchy source seeds the same way production does.
/// </summary>
internal sealed class HierarchyAttributeSecuritySource(IGalaxyHierarchySource hierarchy) : IGalaxyAttributeSecuritySource
{
/// <inheritdoc />
public async Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(
IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken)
{
var wanted = new HashSet<string>(tagNames, StringComparer.OrdinalIgnoreCase);
var all = await hierarchy.GetHierarchyAsync(cancellationToken).ConfigureAwait(false);
return [.. all.Where(o => wanted.Contains(o.TagName))];
}
}
@@ -190,6 +190,40 @@ public sealed class GalaxyDriver
// BuildProductionRuntimeAsync entirely.
private GalaxyMxSession? _ownedMxSession;
private MxGatewayClient? _ownedMxClient;
// #991 G-19: the keep-alive channels the owned clients run on (a client over a caller-owned channel does not
// dispose it), released after their client in the teardown.
private Grpc.Net.Client.GrpcChannel? _ownedMxChannel;
private Grpc.Net.Client.GrpcChannel? _ownedRepositoryChannel;
/// <summary>A gateway channel with this driver's HTTP/2 keep-alive settings (#991 G-19).</summary>
private Grpc.Net.Client.GrpcChannel CreateGatewayChannel(MxGatewayClientOptions clientOptions) =>
GalaxyGatewayChannelFactory.CreateChannel(clientOptions, _options.Gateway);
/// <summary>
/// The owned repository client (deploy watch, platform / security seeds, lazy discovery), built once per
/// runtime over a keep-alive channel — <c>WatchDeployEvents</c> is a long-lived server stream too.
/// </summary>
private async Task<GalaxyRepositoryClient> EnsureOwnedRepositoryClientAsync(CancellationToken cancellationToken)
{
if (_ownedRepositoryClient is { } existing) return existing;
var clientOptions = await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false);
if (_ownedRepositoryClient is { } raced) return raced;
var channel = CreateGatewayChannel(clientOptions);
try
{
_ownedRepositoryClient = GalaxyRepositoryClient.Create(channel, clientOptions);
}
catch
{
channel.Dispose();
throw;
}
_ownedRepositoryChannel = channel;
return _ownedRepositoryClient;
}
/// <summary>Test seam: the keep-alive channel the owned gateway client runs on.</summary>
internal Grpc.Net.Client.GrpcChannel? OwnedMxChannelForTests => _ownedMxChannel;
// PR 4.5 — reconnect supervisor. Reflects in DriverState.Degraded while not Healthy.
private ReconnectSupervisor? _supervisor;
@@ -216,6 +250,12 @@ public sealed class GalaxyDriver
// from DiscoverAsync alone left the production watcher with no platforms, ever.
private readonly IGalaxyPlatformSource? _platformSource;
private IGalaxyPlatformSource? _ownedPlatformSource;
// #991 G-1: the authored tags' security classifications, for WriteAsync's WriteSecured routing. Injected seam
// (tests) or, on the production path, per-object DiscoverHierarchy queries over the owned repository client.
// Seeded by the same background worker as the platform set (init + every rediscovery).
private readonly IGalaxyAttributeSecuritySource? _securitySource;
private IGalaxyAttributeSecuritySource? _ownedSecuritySource;
// 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
@@ -388,6 +428,10 @@ public sealed class GalaxyDriver
/// over <see cref="GalaxyDriverOptions.AlarmAck"/> and <paramref name="secretResolver"/>.
/// </param>
/// <param name="ackIdentityDirectory">Optional cached key → Galaxy-identity set (lmxopcua#765).</param>
/// <param name="securitySource">
/// Optional security-classification seam (#991 G-1). Without it, seam mode falls back to
/// <paramref name="hierarchySource"/>; production builds a <see cref="GatewayGalaxyAttributeSecuritySource"/>.
/// </param>
internal GalaxyDriver(
string driverInstanceId,
GalaxyDriverOptions options,
@@ -402,9 +446,11 @@ public sealed class GalaxyDriver
IGalaxyDeployWatchSource? deployWatchSource = null,
IGalaxyPlatformSource? platformSource = null,
IGalaxyAckCredentialResolver? ackCredentialResolver = null,
IGalaxyAckIdentityDirectory? ackIdentityDirectory = null)
IGalaxyAckIdentityDirectory? ackIdentityDirectory = null,
IGalaxyAttributeSecuritySource? securitySource = null)
{
_ackIdentityDirectory = ackIdentityDirectory;
_securitySource = securitySource;
_deployWatchSource = deployWatchSource;
_platformSource = platformSource;
_driverInstanceId = !string.IsNullOrWhiteSpace(driverInstanceId)
@@ -754,24 +800,38 @@ public sealed class GalaxyDriver
/// </summary>
private async Task PrepareProbeSeedAsync(CancellationToken cancellationToken)
{
if (_probeWatcher is null) return;
var wantsProbe = _probeWatcher is not null;
var wantsSecurity = _rawTagByAttributeRef.Count > 0; // #991 G-1: authored tags need their classifications
if (!wantsProbe && !wantsSecurity) return;
_seedCts ??= new CancellationTokenSource();
if (_platformSource is not null || !_ownsRuntime || _ownedPlatformSource is not null) return;
if (!_ownsRuntime) return; // seam mode: injected sources only
var needPlatform = wantsProbe && _platformSource is null && _ownedPlatformSource is null;
var needSecurity = wantsSecurity && _securitySource is null && _ownedSecuritySource is null;
if (!needPlatform && !needSecurity) return;
try
{
_ownedRepositoryClient ??= GalaxyRepositoryClient.Create(
await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false));
_ownedPlatformSource =
new GatewayGalaxyPlatformSource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize);
var repository = await EnsureOwnedRepositoryClientAsync(cancellationToken).ConfigureAwait(false);
if (needPlatform)
{
_ownedPlatformSource =
new GatewayGalaxyPlatformSource(repository, _options.Repository.DiscoverPageSize);
}
if (needSecurity) _ownedSecuritySource = new GatewayGalaxyAttributeSecuritySource(repository);
}
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.",
"GalaxyDriver {InstanceId} could not build the repository queries — per-platform host status and secured-write routing stay unseeded until the next rediscovery.",
_driverInstanceId);
}
}
/// <summary>The security-classification source for the current runtime (#991 G-1), or null.</summary>
private IGalaxyAttributeSecuritySource? ResolveSecuritySource() =>
_securitySource
?? _ownedSecuritySource
?? (!_ownsRuntime && _hierarchySource is { } hierarchy ? new HierarchyAttributeSecuritySource(hierarchy) : null);
/// <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
@@ -780,7 +840,8 @@ public sealed class GalaxyDriver
/// </summary>
private void RequestProbeSeed(string reason)
{
if (_runtimeStopping || _probeWatcher is null) return;
if (_runtimeStopping) return;
if (_probeWatcher is null && (_rawTagByAttributeRef.Count == 0 || ResolveSecuritySource() is null)) return;
_seedReason = reason;
if (Interlocked.Increment(ref _reseedRequests) != 1) return; // the running worker will serve it
@@ -794,7 +855,9 @@ public sealed class GalaxyDriver
var seedCts = Volatile.Read(ref _seedCts);
if (!_runtimeStopping && seedCts is not null)
{
await SeedProbePlatformsAsync(_seedReason, generation, seedCts.Token).ConfigureAwait(false);
var reason = _seedReason;
await SeedProbePlatformsAsync(reason, generation, seedCts.Token).ConfigureAwait(false);
await SeedSecurityClassificationsAsync(reason, generation, seedCts.Token).ConfigureAwait(false);
}
}
while (Interlocked.Add(ref _reseedRequests, -served) != 0);
@@ -843,6 +906,89 @@ public sealed class GalaxyDriver
}
}
/// <summary>
/// #991 G-1 — one security seed pass: fetch the authored objects' attributes and record each authored tag's
/// <see cref="SecurityClassification"/> under its RawPath, the key <see cref="WriteAsync"/> resolves against.
/// Before this the map was filled only by <see cref="DiscoverAsync"/>, which the runtime never calls on a
/// served driver, so every write — SecuredWrite / VerifiedWrite attributes included — took the raw path and
/// was refused. Never throws; a failed or late pass leaves the map as it was (FreeAccess for anything unseen,
/// i.e. the raw path, which fails closed).
/// </summary>
private async Task SeedSecurityClassificationsAsync(string reason, int generation, CancellationToken cancellationToken)
{
if (_rawTagByAttributeRef.Count == 0) return;
var source = ResolveSecuritySource();
if (source is null) return;
// tag_name is the part of the attributeRef before its first dot; a provider-qualified reference
// ("Galaxy!Area.tag.Attr") names an alarm, never a writable value.
var tagNames = _rawTagByAttributeRef.Keys
.Where(r => !r.Contains('!', StringComparison.Ordinal) && r.IndexOf('.', StringComparison.Ordinal) > 0)
.Select(r => r[..r.IndexOf('.', StringComparison.Ordinal)])
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
if (tagNames.Length == 0) return;
try
{
var objects = await source.GetObjectsAsync(tagNames, cancellationToken).ConfigureAwait(false);
if (Volatile.Read(ref _runtimeGeneration) != generation || _runtimeStopping)
{
_logger.LogDebug(
"GalaxyDriver {InstanceId} discarded a security seed ({Reason}) — its runtime was torn down.",
_driverInstanceId, reason);
return;
}
var seeded = new Dictionary<string, SecurityClassification>(StringComparer.OrdinalIgnoreCase);
foreach (var obj in objects)
{
foreach (var attr in obj.Attributes)
{
if (string.IsNullOrEmpty(attr.AttributeName)) continue;
// Same attributeRef derivation as GalaxyDiscoverer, so the two paths key identically.
var attributeRef = !string.IsNullOrEmpty(attr.FullTagReference)
? (attr.FullTagReference.EndsWith("[]", StringComparison.Ordinal)
? attr.FullTagReference[..^2]
: attr.FullTagReference)
: obj.TagName + "." + attr.AttributeName;
if (_rawTagByAttributeRef.TryGetValue(attributeRef, out var entry))
seeded[entry.RawPath] = SecurityMap.Map(attr.SecurityClassification);
}
}
foreach (var entry in _rawTagByAttributeRef.Values)
{
if (seeded.TryGetValue(entry.RawPath, out var classification)) _securityByFullRef[entry.RawPath] = classification;
else _securityByFullRef.TryRemove(entry.RawPath, out _); // gone from the Galaxy: back to the default
}
var secured = seeded.Values.Count(c => c is SecurityClassification.SecuredWrite or SecurityClassification.VerifiedWrite);
_logger.LogInformation(
"GalaxyDriver {InstanceId} security classifications seeded for {Count} authored tag(s), {Secured} secured/verified ({Reason}).",
_driverInstanceId, seeded.Count, secured, reason);
if (secured > 0 && _options.MxAccess.WriteUserId == 0)
{
_logger.LogWarning(
"GalaxyDriver {InstanceId} has {Secured} SecuredWrite/VerifiedWrite tag(s) but MxAccess.WriteUserId is 0 — " +
"WriteSecured carries no ArchestrA user, so MXAccess is expected to refuse those writes.",
_driverInstanceId, secured);
}
}
catch (Exception ex) when (cancellationToken.IsCancellationRequested
|| Volatile.Read(ref _runtimeGeneration) != generation)
{
_logger.LogDebug(ex, "GalaxyDriver {InstanceId} security seed ({Reason}) abandoned by a teardown.",
_driverInstanceId, reason);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} security seed failed ({Reason}) — secured-write routing 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");
@@ -972,10 +1118,14 @@ public sealed class GalaxyDriver
_ownsRuntime = true;
var clientOptions = await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false);
_ownedMxClient = MxGatewayClient.Create(clientOptions);
// #991 G-19: every long-lived gateway client runs over a channel with HTTP/2 keep-alive pings — the alarm
// feed's StreamAlarms on this one, StreamEvents on the session's own (ChannelFactory below).
_ownedMxChannel = CreateGatewayChannel(clientOptions);
_ownedMxClient = MxGatewayClient.Create(_ownedMxChannel, clientOptions);
_ownedMxSession = new GalaxyMxSession(_options.MxAccess, _logger)
{
OpenAndRegisterOverrideForTests = SessionOpenOverrideForTests,
ChannelFactory = CreateGatewayChannel,
};
await _ownedMxSession.ConnectAsync(clientOptions, cancellationToken).ConfigureAwait(false);
@@ -1148,6 +1298,10 @@ public sealed class GalaxyDriver
_ownedRepositoryClient = null;
}
// #991 G-19: the keep-alive channels, after the clients built over them (which do not dispose them).
DisposeChannel(ref _ownedMxChannel, "MxClient");
DisposeChannel(ref _ownedRepositoryChannel, "RepositoryClient");
if (_ownsRuntime || final)
{
// Null the seams so the next InitializeAsync rebuilds (production) — injected seams
@@ -1157,6 +1311,7 @@ public sealed class GalaxyDriver
_hierarchySource = null;
_alarmAcknowledger = null;
_ownedPlatformSource = null;
_ownedSecuritySource = null;
_ownsRuntime = false;
}
}
@@ -1166,6 +1321,15 @@ public sealed class GalaxyDriver
}
}
private void DisposeChannel(ref Grpc.Net.Client.GrpcChannel? channel, string owner)
{
var c = channel;
channel = null;
if (c is null) return;
try { c.Dispose(); }
catch (Exception ex) { _logger.LogWarning(ex, "{Owner} channel dispose failed", owner); }
}
/// <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
@@ -1401,12 +1565,20 @@ public sealed class GalaxyDriver
/// <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="sameSession">
/// True when <paramref name="entries"/> hold handles the CURRENT gateway session issued (the replay-gap
/// re-snapshot): those are still advised, so every handle a re-advise supersedes is released (#991 G-6 —
/// each gap used to double the gateway's advise count), and a tag whose re-advise fails keeps its live
/// handle. False for the reconnect replay, whose handles died with the old session and whose numbers the
/// new session reuses — they are never sent.
/// </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)
CancellationToken cancellationToken,
bool sameSession = false)
{
var tagCount = 0;
// M-b: the session this pass belongs to, read ONCE. Any later change fences the rest of the
@@ -1425,44 +1597,106 @@ public sealed class GalaxyDriver
{
// 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).
// status keeps updating after a reconnect (it used to go permanently deaf). It releases
// same-session handles it supersedes on its own (#991 G-6).
tagCount += await probeWatcher.ResubscribeAsync(cancellationToken).ConfigureAwait(false);
continue;
}
var refs = oldBindings
.Select(b => b.FullReference)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
if (refs.Length == 0) continue;
var (keepGoing, count) = await ReadviseSubscriptionAsync(
subscriptionId, oldBindings, only: null, session, generation, sameSession, cancellationToken).ConfigureAwait(false);
tagCount += count;
if (!keepGoing) return tagCount;
}
// #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!
return tagCount;
}
/// <summary>
/// Re-advise one subscription's tags — all of them (<paramref name="only"/> null) or just the named references —
/// and rebind the registry to the fresh handles. MXAccess answers every advise with the attribute's current
/// value, which is what makes this the re-snapshot primitive for the reconnect replay, the replay-gap
/// re-snapshot and the dropped-event resync (#991 G-4).
/// </summary>
/// <param name="subscriptionId">The subscription.</param>
/// <param name="oldBindings">Its bindings as snapshotted.</param>
/// <param name="only">The references to re-advise (case-insensitive); null = every reference.</param>
/// <param name="session">The registry session this pass runs under.</param>
/// <param name="generation">The runtime generation this pass belongs to.</param>
/// <param name="sameSession">See <see cref="ResubscribeAllAsync"/>.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Whether the caller may continue with further subscriptions, and the references re-advised.</returns>
private async Task<(bool KeepGoing, int Count)> ReadviseSubscriptionAsync(
long subscriptionId,
IReadOnlyList<TagBinding> oldBindings,
ISet<string>? only,
int session,
int generation,
bool sameSession,
CancellationToken cancellationToken)
{
var refs = oldBindings
.Select(b => b.FullReference)
.Where(r => only is null || only.Contains(r))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
if (refs.Length == 0) return (true, 0);
// #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 subscription: 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.
IReadOnlyList<SubscribeResult> results;
using (_subscriptions.BeginPendingSubscribe())
{
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)
List<TagBinding> newBindings;
var superseded = new HashSet<int>();
if (!sameSession)
{
var itemHandle = byAddress.TryGetValue(fullRef, out var match) && match.WasSuccessful
? match.ItemHandle
: 0;
newBindings.Add(new TagBinding(fullRef, itemHandle));
// Reconnect replay: the old handles are dead — the bindings become exactly the re-advised refs.
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));
}
}
else
{
// Same session: replace each re-advised binding whose advise succeeded and release the handle it
// held; a binding not re-advised, or whose re-advise failed, keeps its (still live) handle.
newBindings = new List<TagBinding>(oldBindings.Count);
foreach (var binding in oldBindings)
{
if ((only is null || only.Contains(binding.FullReference))
&& byAddress.TryGetValue(binding.FullReference, out var match) && match.WasSuccessful
&& match.ItemHandle > 0)
{
newBindings.Add(new TagBinding(binding.FullReference, match.ItemHandle));
if (binding.ItemHandle > 0 && binding.ItemHandle != match.ItemHandle) superseded.Add(binding.ItemHandle);
}
else
{
newBindings.Add(binding);
}
}
}
// 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.
// Rebind so the EventPump fan-out reverse map points at the fresh 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;
if (Volatile.Read(ref _runtimeGeneration) != generation) return (false, 0);
outcome = _subscriptions.TryRebind(subscriptionId, newBindings, session);
}
@@ -1473,32 +1707,39 @@ public sealed class GalaxyDriver
_logger.LogDebug(
"GalaxyDriver {InstanceId} re-subscribe abandoned — the gateway session changed again.",
_driverInstanceId);
return tagCount;
return (false, 0);
}
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;
var orphaned = results.Where(r => r.WasSuccessful && r.ItemHandle > 0).Select(r => r.ItemHandle).ToArray();
await ReleaseHandlesAsync(orphaned,
"re-subscribed for a subscription removed during the pass").ConfigureAwait(false);
return (true, 0);
}
tagCount += refs.Length;
}
return tagCount;
if (superseded.Count > 0)
{
await ReleaseHandlesAsync([.. superseded], "superseded by a same-session re-advise").ConfigureAwait(false);
}
}
return (true, refs.Length);
}
private async Task ReleaseHandlesAsync(IReadOnlyList<int> handles, string why)
{
if (handles.Count == 0) return;
try
{
await UnsubscribeAndPurgeAsync(_subscriber!, handles, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} could not release {Count} handle(s) {Why}.",
_driverInstanceId, handles.Count, why);
}
}
/// <summary>
@@ -1629,9 +1870,8 @@ public sealed class GalaxyDriver
// 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);
source = new GatewayGalaxyDeployWatchSource(
await EnsureOwnedRepositoryClientAsync(cancellationToken).ConfigureAwait(false));
}
// One watcher per driver: a previous one (an InitializeAsync without a ShutdownAsync in
@@ -2371,7 +2611,8 @@ public sealed class GalaxyDriver
channelCapacity: _options.MxAccess.EventPumpChannelCapacity,
clientName: _options.MxAccess.ClientName,
onStreamFault: cause => OnEventPumpStreamFault(created, cause),
onReplayGap: OnEventPumpReplayGap);
onReplayGap: OnEventPumpReplayGap,
onEventsDropped: handles => OnEventPumpEventsDropped(created, handles));
_eventPump = created;
_eventPump.OnDataChange += OnPumpDataChange;
_eventPump.Start();
@@ -2662,12 +2903,17 @@ public sealed class GalaxyDriver
var generation = Volatile.Read(ref _runtimeGeneration);
_ = Task.Run(async () =>
{
await _resnapshotGate.WaitAsync().ConfigureAwait(false);
try
{
var entries = _subscriptions.SnapshotEntries();
// Only subscriptions whose handles this session issued: they are still advised, so the re-advise
// releases the ones it supersedes (#991 G-6). One still holding an older session's handles is the
// reconnect replay's to re-subscribe.
var entries = _subscriptions.SnapshotEntriesIn(_subscriptions.CurrentSession);
if (entries.Count == 0) return;
var tagCount = await ResubscribeAllAsync(entries, generation, CancellationToken.None).ConfigureAwait(false);
var tagCount = await ResubscribeAllAsync(
entries, generation, CancellationToken.None, sameSession: true).ConfigureAwait(false);
_logger.LogInformation(
"GalaxyDriver {InstanceId} replay-gap re-snapshot completed — {SubCount} subscriptions, {TagCount} tags re-subscribed",
_driverInstanceId, entries.Count, tagCount);
@@ -2683,11 +2929,139 @@ public sealed class GalaxyDriver
}
finally
{
_resnapshotGate.Release();
Interlocked.Exchange(ref _resnapshotInFlight, 0);
}
});
}
// #991 G-4: item handles whose data-change events the pump's full channel dropped, waiting for a re-advise.
// Keyed by the session that issued them; guarded by _droppedLock.
private readonly Lock _droppedLock = new();
private readonly HashSet<int> _droppedPending = [];
private int _droppedSession;
private int _dropResyncRunning;
// Serialises the same-session re-advise passes (replay-gap re-snapshot, dropped-event resync): both rebind a
// subscription from a snapshot of its bindings, so two interleaved passes could rebind over each other and
// release handles the other one bound.
private readonly SemaphoreSlim _resnapshotGate = new(1, 1);
/// <summary>
/// #991 G-4 — the pump dropped data-change events for <paramref name="itemHandles"/> because its channel was
/// full (raised once the channel drained). MXAccess sends a value only when it changes, so each of those tags
/// would otherwise keep its previous value, Good, until the attribute happens to change again. Queue them for
/// a re-advise — MXAccess answers an advise with the current value — on one coalescing background worker.
/// Runs on the pump's dispatch thread: must not block.
/// </summary>
private void OnEventPumpEventsDropped(EventPump? source, IReadOnlyCollection<int> itemHandles)
{
if (_runtimeStopping || _subscriber is null || source is null || itemHandles.Count == 0) return;
var session = source.Session;
// A pump of an older session: the reconnect replay re-advises everything on the new session anyway.
if (session != _subscriptions.CurrentSession) return;
lock (_droppedLock)
{
if (_droppedSession != session)
{
_droppedPending.Clear();
_droppedSession = session;
}
_droppedPending.UnionWith(itemHandles);
}
if (Interlocked.Exchange(ref _dropResyncRunning, 1) == 1) return; // the running worker picks them up
_ = Task.Run(async () =>
{
while (true)
{
int[] batch;
int batchSession;
lock (_droppedLock)
{
if (_droppedPending.Count == 0 || _runtimeStopping)
{
_droppedPending.Clear();
Volatile.Write(ref _dropResyncRunning, 0); // under the lock: a later add starts a new worker
return;
}
batch = [.. _droppedPending];
_droppedPending.Clear();
batchSession = _droppedSession;
}
try
{
await ResyncDroppedHandlesAsync(batch, batchSession).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} could not re-read {Count} tag(s) whose changes were dropped — they may stay stale until they next change.",
_driverInstanceId, batch.Length);
}
}
});
}
/// <summary>
/// Re-advise exactly the tags bound to <paramref name="itemHandles"/> (still issued by <paramref name="session"/>)
/// and release the handles they replace. A handle no subscription holds any more needs nothing.
/// </summary>
private async Task ResyncDroppedHandlesAsync(IReadOnlyCollection<int> itemHandles, int session)
{
await _resnapshotGate.WaitAsync().ConfigureAwait(false);
try
{
var generation = Volatile.Read(ref _runtimeGeneration);
if (_runtimeStopping || _subscriber is null || _subscriptions.CurrentSession != session) return;
var dropped = itemHandles.ToHashSet();
var probeAffected = false;
var tagCount = 0;
foreach (var (subscriptionId, bindings) in _subscriptions.SnapshotEntriesIn(session))
{
HashSet<string>? affected = null;
foreach (var binding in bindings)
{
if (binding.ItemHandle <= 0 || !dropped.Contains(binding.ItemHandle)) continue;
(affected ??= new HashSet<string>(StringComparer.OrdinalIgnoreCase)).Add(binding.FullReference);
}
if (affected is null) continue;
if (subscriptionId == SubscriptionRegistry.ProbeSubscriptionId)
{
probeAffected = true; // the watcher owns its handles
continue;
}
var (keepGoing, count) = await ReadviseSubscriptionAsync(
subscriptionId, bindings, affected, session, generation, sameSession: true, CancellationToken.None)
.ConfigureAwait(false);
tagCount += count;
if (!keepGoing) return;
}
if (probeAffected && _probeWatcher is { } probeWatcher
&& Volatile.Read(ref _runtimeGeneration) == generation && _subscriptions.CurrentSession == session)
{
tagCount += await probeWatcher.ResubscribeAsync(CancellationToken.None).ConfigureAwait(false);
}
if (tagCount > 0)
{
_logger.LogInformation(
"GalaxyDriver {InstanceId} re-advised {TagCount} tag(s) whose changes the event channel dropped.",
_driverInstanceId, tagCount);
}
}
finally
{
_resnapshotGate.Release();
}
}
/// <summary>
/// Stream-fault callback for the <see cref="EventPump"/>. The gw StreamEvents
/// stream faulted (transient gateway drop, network blip, gw restart). Forward
@@ -3380,10 +3754,9 @@ public sealed class GalaxyDriver
// 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));
var repository = await EnsureOwnedRepositoryClientAsync(cancellationToken).ConfigureAwait(false);
return new TracedGalaxyHierarchySource(
new GatewayGalaxyHierarchySource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize),
new GatewayGalaxyHierarchySource(repository, _options.Repository.DiscoverPageSize),
_options.MxAccess.ClientName);
}
@@ -106,7 +106,9 @@ public static class GalaxyDriverFactoryExtensions
CaCertificatePath: dto.Gateway.CaCertificatePath,
ConnectTimeoutSeconds: dto.Gateway.ConnectTimeoutSeconds ?? 10,
DefaultCallTimeoutSeconds: dto.Gateway.DefaultCallTimeoutSeconds ?? 30,
StreamTimeoutSeconds: dto.Gateway.StreamTimeoutSeconds ?? 0),
StreamTimeoutSeconds: dto.Gateway.StreamTimeoutSeconds ?? 0,
KeepAlivePingDelaySeconds: dto.Gateway.KeepAlivePingDelaySeconds ?? 15,
KeepAlivePingTimeoutSeconds: dto.Gateway.KeepAlivePingTimeoutSeconds ?? 10),
MxAccess: new GalaxyMxAccessOptions(
ClientName: dto.MxAccess?.ClientName
?? throw new InvalidOperationException(
@@ -199,6 +201,10 @@ public static class GalaxyDriverFactoryExtensions
public int? DefaultCallTimeoutSeconds { get; init; }
/// <summary>Gets or sets the stream timeout in seconds.</summary>
public int? StreamTimeoutSeconds { get; init; }
/// <summary>Gets or sets the HTTP/2 keep-alive ping interval in seconds (0 = no pings; #991 G-19).</summary>
public int? KeepAlivePingDelaySeconds { get; init; }
/// <summary>Gets or sets how long an unanswered keep-alive ping may wait before the connection fails.</summary>
public int? KeepAlivePingTimeoutSeconds { get; init; }
}
/// <summary>MX Access configuration section.</summary>
@@ -241,6 +241,10 @@ public sealed class PerPlatformProbeWatcher : IDisposable
// ran while SubscribeBulk was in flight already cleared the map and the registry entry, so
// recording now would resurrect the probe entry into the next runtime's registry.
bool stopped;
// #991 G-6: handles this subscribe replaces that the SAME session issued are still advised on the gateway
// (the replay-gap re-snapshot) and are released below. A previous session's handles are dead and their
// numbers reused by the current session, so they are never sent.
var superseded = new List<int>();
lock (_syncLock)
{
stopped = _disposed;
@@ -253,11 +257,32 @@ public sealed class PerPlatformProbeWatcher : IDisposable
return false;
}
foreach (var (platform, itemHandle, _) in acquired)
{
if (_itemHandlesByPlatform.TryGetValue(platform, out var previous)
&& previous.Session == session && previous.ItemHandle > 0 && previous.ItemHandle != itemHandle)
{
superseded.Add(previous.ItemHandle);
}
_itemHandlesByPlatform[platform] = new ProbeHandle(itemHandle, session);
}
if (!PublishBindingsLocked(session)) return false;
}
}
if (!stopped && superseded.Count > 0)
{
try { await _subscriber.UnsubscribeBulkAsync(superseded, CancellationToken.None).ConfigureAwait(false); }
catch (Exception ex)
{
_logger.LogWarning(ex,
"PerPlatformProbeWatcher could not release {Count} superseded probe handle(s)", superseded.Count);
}
finally
{
_registry?.PurgeParked(superseded, session);
}
}
if (stopped)
{
var orphans = acquired.Where(a => a.ItemHandle > 0).Select(a => a.ItemHandle).ToArray();
@@ -73,6 +73,13 @@ internal sealed class EventPump : IAsyncDisposable
private readonly Func<long, ISubscriptionHandle> _handleFactory;
private readonly Action<Exception>? _onStreamFault;
private readonly Action<ReplayGap>? _onReplayGap;
private readonly Action<IReadOnlyCollection<int>>? _onEventsDropped;
// #991 G-4: item handles whose data-change events were dropped since the last flush. Written by the read loop,
// drained by the dispatch loop once the channel is empty.
private readonly Lock _droppedLock = new();
private readonly HashSet<int> _droppedHandles = [];
private volatile bool _dropsPending;
private readonly Channel<MxEvent> _channel;
private readonly KeyValuePair<string, object?> _clientTag;
private readonly CancellationTokenSource _cts = new();
@@ -103,6 +110,12 @@ internal sealed class EventPump : IAsyncDisposable
/// Optional callback invoked when the gateway reports a replay gap. The contract
/// obliges the client to re-snapshot; see <see cref="HandleReplayGap"/>.
/// </param>
/// <param name="onEventsDropped">
/// #991 G-4 — optional callback receiving the item handles whose data-change events the full channel
/// dropped, raised on the dispatch thread once the channel has drained (so a resync is not swallowed by
/// the same congestion). MXAccess sends a value only on change, so each such tag is stale until re-read.
/// Must not block.
/// </param>
public EventPump(
IGalaxySubscriber subscriber,
SubscriptionRegistry registry,
@@ -111,7 +124,8 @@ internal sealed class EventPump : IAsyncDisposable
int channelCapacity = DefaultChannelCapacity,
string? clientName = null,
Action<Exception>? onStreamFault = null,
Action<ReplayGap>? onReplayGap = null)
Action<ReplayGap>? onReplayGap = null,
Action<IReadOnlyCollection<int>>? onEventsDropped = null)
{
_subscriber = subscriber ?? throw new ArgumentNullException(nameof(subscriber));
_registry = registry ?? throw new ArgumentNullException(nameof(registry));
@@ -119,6 +133,7 @@ internal sealed class EventPump : IAsyncDisposable
_handleFactory = handleFactory ?? (id => new GalaxySubscriptionHandle(id));
_onStreamFault = onStreamFault;
_onReplayGap = onReplayGap;
_onEventsDropped = onEventsDropped;
if (channelCapacity < 1)
{
@@ -158,6 +173,11 @@ internal sealed class EventPump : IAsyncDisposable
/// </summary>
internal int Session => _session;
private long _droppedCount;
/// <summary>Test seam: events this pump dropped because its bounded channel was full.</summary>
internal long DroppedCountForTests => Interlocked.Read(ref _droppedCount);
/// <summary>True once the stream loop has exited (faulted, completed by the gateway, or disposed).</summary>
internal bool HasEnded => Volatile.Read(ref _ended);
@@ -298,6 +318,8 @@ internal sealed class EventPump : IAsyncDisposable
if (!_channel.Writer.TryWrite(ev))
{
EventsDropped.Add(1, _clientTag);
Interlocked.Increment(ref _droppedCount);
RecordDrop(ev);
}
}
@@ -451,10 +473,13 @@ internal sealed class EventPump : IAsyncDisposable
if (ReferenceEquals(ev, WakeSentinel))
{
DispatchReadyEvents();
continue;
}
Dispatch(ev);
EventsDispatched.Add(1, _clientTag);
else
{
Dispatch(ev);
EventsDispatched.Add(1, _clientTag);
}
if (_dropsPending && _channel.Reader.Count == 0) FlushDrops();
}
}
catch (Exception) when (ct.IsCancellationRequested)
@@ -473,6 +498,43 @@ internal sealed class EventPump : IAsyncDisposable
}
}
/// <summary>
/// #991 G-4 — remember the item handle of a dropped data-change event, then wake the dispatch loop. The wake
/// usually fails (the channel is full — the loop is busy and checks after each item); it succeeds exactly when
/// the loop drained the channel between this drop and now, and would otherwise sleep with the drop unflushed.
/// </summary>
private void RecordDrop(MxEvent ev)
{
if (_onEventsDropped is null || ev.Family != MxEventFamily.OnDataChange || ev.ItemHandle <= 0) return;
lock (_droppedLock)
{
_droppedHandles.Add(ev.ItemHandle);
_dropsPending = true;
}
_channel.Writer.TryWrite(WakeSentinel);
}
/// <summary>Hand every recorded dropped handle to the owner (dispatch thread, channel drained).</summary>
private void FlushDrops()
{
int[] handles;
lock (_droppedLock)
{
handles = [.. _droppedHandles];
_droppedHandles.Clear();
_dropsPending = false;
}
if (handles.Length == 0 || _onEventsDropped is null) return;
_logger.LogWarning(
"Galaxy EventPump dropped data changes for {Count} item(s) while its channel was full — re-reading them.",
handles.Length);
try { _onEventsDropped(handles); }
catch (Exception ex)
{
_logger.LogWarning(ex, "Galaxy EventPump dropped-events callback threw — those values may stay stale.");
}
}
private void Dispatch(MxEvent ev)
{
switch (ev.Family)
@@ -546,7 +608,7 @@ internal sealed class EventPump : IAsyncDisposable
var snapshot = ToSnapshot(ev);
foreach (var (subscriptionId, fullReference) in subscribers)
{
var handle = _handleFactory(subscriptionId);
var handle = HandleFor(subscriptionId);
try
{
OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, fullReference, snapshot));
@@ -560,6 +622,21 @@ internal sealed class EventPump : IAsyncDisposable
}
}
// #991 G-5: one handle object per subscription instead of one per subscriber per event. Touched only by the
// dispatch thread (every FanOut runs there), so it needs no lock. Subscription ids are never reused, and
// subscribe-once reads mint one each, so the cache is simply dropped when it grows past the bound.
private readonly Dictionary<long, ISubscriptionHandle> _handleCache = [];
private const int HandleCacheBound = 4_096;
private ISubscriptionHandle HandleFor(long subscriptionId)
{
if (_handleCache.TryGetValue(subscriptionId, out var cached)) return cached;
if (_handleCache.Count >= HandleCacheBound) _handleCache.Clear();
var created = _handleFactory(subscriptionId);
_handleCache[subscriptionId] = created;
return created;
}
private DataValueSnapshot ToSnapshot(MxEvent ev)
{
if (!MxValueDecoder.TryDecode(ev.Value, out var value))
@@ -0,0 +1,117 @@
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Grpc.Net.Client;
using ZB.MOM.WW.MxGateway.Client;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
/// <summary>
/// #991 G-19 — builds the gRPC channels the driver's long-lived gateway clients run on, with HTTP/2 keep-alive
/// pings. <see cref="MxGatewayClient.Create(MxGatewayClientOptions)"/> (mxaccessgw client 0.4.0) builds its own
/// <see cref="SocketsHttpHandler"/> with only <c>ConnectTimeout</c>, so pings are off: a server-streaming call
/// (StreamEvents, StreamAlarms, WatchDeployEvents) sends nothing after its request, and a gateway host that loses
/// power — or a firewall that starts silently dropping the flow — never surfaces a TCP error. The stream waited
/// forever, the reconnect supervisor was never told, and Galaxy stayed Healthy serving stale Good values.
/// </summary>
/// <remarks>
/// <para>
/// With <see cref="HttpKeepAlivePingPolicy.Always"/> the client PINGs the connection every
/// <c>KeepAlivePingDelaySeconds</c> whether or not a call is active, and fails the connection — and every stream on
/// it — when a PING goes unanswered for <c>KeepAlivePingTimeoutSeconds</c>. The stream's fault then reaches the
/// supervisor exactly like a gateway crash. A PING is answered by the peer's HTTP/2 stack itself (mandatory per
/// RFC 9113 §6.7), so this needs nothing from the gateway; Kestrel applies no client-ping rate policy.
/// </para>
/// <para>
/// ⚠️ The TLS settings below MIRROR the client library's own handler (<c>MxGatewayClient.CreateHttpHandler</c>,
/// 0.4.0): CA-pinned custom-root trust with the host-name check kept, <c>RequireCertificateValidation</c>, and
/// <c>ServerNameOverride</c>. Keep them in step if the client's changes — or, better, retire this once the client
/// exposes keep-alive options itself (the cross-repo half of #991 G-19).
/// </para>
/// </remarks>
internal static class GalaxyGatewayChannelFactory
{
/// <summary>Builds a channel to <paramref name="options"/>' endpoint with keep-alive pings per <paramref name="gateway"/>.</summary>
/// <param name="options">The client options (endpoint, TLS, message limits, logging).</param>
/// <param name="gateway">The driver's gateway options (keep-alive settings).</param>
/// <returns>A channel the caller owns and must dispose after the client built over it.</returns>
public static GrpcChannel CreateChannel(MxGatewayClientOptions options, GalaxyGatewayOptions gateway)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(gateway);
options.Validate();
return GrpcChannel.ForAddress(options.Endpoint, new GrpcChannelOptions
{
HttpHandler = CreateHttpHandler(options, KeepAliveDelay(gateway), KeepAliveTimeout(gateway)),
DisposeHttpClient = true,
LoggerFactory = options.LoggerFactory,
MaxReceiveMessageSize = options.MaxGrpcMessageBytes,
MaxSendMessageSize = options.MaxGrpcMessageBytes,
});
}
/// <summary>The ping interval; infinite (no pings) when not positive.</summary>
internal static TimeSpan KeepAliveDelay(GalaxyGatewayOptions gateway) =>
gateway.KeepAlivePingDelaySeconds > 0 ? TimeSpan.FromSeconds(gateway.KeepAlivePingDelaySeconds) : Timeout.InfiniteTimeSpan;
/// <summary>How long an unanswered ping may wait; the .NET default (20 s) when not positive.</summary>
internal static TimeSpan KeepAliveTimeout(GalaxyGatewayOptions gateway) =>
gateway.KeepAlivePingTimeoutSeconds > 0 ? TimeSpan.FromSeconds(gateway.KeepAlivePingTimeoutSeconds) : TimeSpan.FromSeconds(20);
/// <summary>
/// The handler: the client library's connect-timeout + TLS behaviour, plus keep-alive pings when
/// <paramref name="keepAlivePingDelay"/> is finite.
/// </summary>
/// <param name="options">The client options.</param>
/// <param name="keepAlivePingDelay">Ping interval; <see cref="Timeout.InfiniteTimeSpan"/> = no pings.</param>
/// <param name="keepAlivePingTimeout">Unanswered-ping budget.</param>
/// <returns>The configured handler.</returns>
internal static SocketsHttpHandler CreateHttpHandler(
MxGatewayClientOptions options, TimeSpan keepAlivePingDelay, TimeSpan keepAlivePingTimeout)
{
var handler = new SocketsHttpHandler
{
ConnectTimeout = options.ConnectTimeout,
};
if (keepAlivePingDelay != Timeout.InfiniteTimeSpan)
{
handler.KeepAlivePingDelay = keepAlivePingDelay;
handler.KeepAlivePingTimeout = keepAlivePingTimeout;
handler.KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always;
}
if (!options.UseTls) return handler;
handler.SslOptions = new SslClientAuthenticationOptions();
if (!string.IsNullOrWhiteSpace(options.ServerNameOverride))
{
handler.SslOptions.TargetHost = options.ServerNameOverride;
}
if (!string.IsNullOrWhiteSpace(options.CaCertificatePath))
{
var trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath);
handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, _, errors) =>
{
if ((errors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) return false;
if (certificate is null) return false;
using var customChain = new X509Chain();
customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
customChain.ChainPolicy.CustomTrustStore.Add(trustedRoot);
customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
var toValidate = certificate as X509Certificate2
?? X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert));
return customChain.Build(toValidate);
};
}
else if (!options.RequireCertificateValidation)
{
handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
}
return handler;
}
}
@@ -26,7 +26,15 @@ public sealed class GalaxyMxSession : IAsyncDisposable
// Owned gateway client + session — populated when ConnectAsync runs. Tests can leave
// them null and exercise the surface via injected IGalaxyDataReader fakes.
private MxGatewayClient? _ownedClient;
private Grpc.Net.Client.GrpcChannel? _ownedChannel;
private MxGatewaySession? _session;
/// <summary>
/// Optional channel builder (#991 G-19). When set, the owned client runs over the channel it returns (the
/// driver supplies one with HTTP/2 keep-alive pings); the session disposes it after the client. Null = the
/// client library builds its own channel.
/// </summary>
internal Func<MxGatewayClientOptions, Grpc.Net.Client.GrpcChannel>? ChannelFactory { get; init; }
private int _serverHandle;
private bool _connected;
private bool _disposed;
@@ -88,7 +96,17 @@ public sealed class GalaxyMxSession : IAsyncDisposable
}
else
{
_ownedClient = MxGatewayClient.Create(clientOptions);
// #991 G-19: over a driver-built channel with HTTP/2 keep-alive pings when one is supplied — the
// client's own handler has none, so a silently dead gateway never faulted StreamEvents.
if (ChannelFactory is { } channelFactory)
{
_ownedChannel = channelFactory(clientOptions);
_ownedClient = MxGatewayClient.Create(_ownedChannel, clientOptions);
}
else
{
_ownedClient = MxGatewayClient.Create(clientOptions);
}
_session = await _ownedClient.OpenSessionAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
_serverHandle = await _session.RegisterAsync(_options.ClientName, cancellationToken).ConfigureAwait(false);
}
@@ -209,5 +227,16 @@ public sealed class GalaxyMxSession : IAsyncDisposable
catch (Exception ex) { _logger.LogWarning(ex, "GalaxyMxSession client dispose failed (best-effort)"); }
_ownedClient = null;
}
if (_ownedChannel is not null)
{
// A client created over a caller-owned channel does not dispose it.
try { _ownedChannel.Dispose(); }
catch (Exception ex) { _logger.LogWarning(ex, "GalaxyMxSession channel dispose failed (best-effort)"); }
_ownedChannel = null;
}
}
/// <summary>Test seam: the driver-built channel the owned client runs on, or null.</summary>
internal Grpc.Net.Client.GrpcChannel? OwnedChannelForTests => _ownedChannel;
}
@@ -361,8 +361,12 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
/// directly and route through <c>InvokeAsync</c>. Verifier user is left at zero
/// for SecuredWrite; VerifiedWrite uses the same path because the gw's worker
/// interprets the underlying MXAccess command kind.
/// <para>#991 G-1: the current user is the configured <c>MxAccess.WriteUserId</c> — the same identity the
/// raw path writes under — instead of a hard-coded 0. With the default 0 a secured write carries no
/// ArchestrA user and MXAccess is expected to refuse it; a VerifiedWrite additionally needs a verifier,
/// which nothing supplies yet (follow-up: a per-caller Galaxy identity, like the #749 ack credential).</para>
/// </summary>
private static Task<MxCommandReply> InvokeWriteSecuredAsync(
private Task<MxCommandReply> InvokeWriteSecuredAsync(
IMxWriteOps ops, int itemHandle, MxValue value, CancellationToken ct)
{
var command = new MxCommand
@@ -373,7 +377,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
ServerHandle = ops.ServerHandle,
ItemHandle = itemHandle,
Value = value,
CurrentUserId = 0,
CurrentUserId = _writeUserId,
VerifierUserId = 0,
},
};
@@ -79,7 +79,13 @@ internal static class StatusCodeMap
/// <param name="q">The OPC DA quality byte to convert.</param>
/// <param name="logger">Optional logger for diagnostics on unknown quality bytes.</param>
/// <returns>The OPC UA status code.</returns>
public static uint FromQualityByte(byte q, ILogger? logger = null) => q switch
/// <remarks>
/// #991 G-2: the two OPC DA LIMIT bits (<c>LL</c> in <c>QQSSSSLL</c> — low-limited, high-limited, constant) are
/// masked off before the lookup. They never change the quality category or substatus and every table entry has
/// them clear, so <c>Good | LowLimited</c> (0xC1) used to miss the table and log a Warning on EVERY event — on
/// the pump's single dispatch thread. A byte still unlisted after the mask warns once per distinct value.
/// </remarks>
public static uint FromQualityByte(byte q, ILogger? logger = null) => (byte)(q & QualityLimitMask) switch
{
// Good family — top two bits 11b (192-255).
192 => Good,
@@ -256,13 +262,21 @@ internal static class StatusCodeMap
return Bad;
}
/// <summary>Clears the OPC DA limit bits (the low two bits of the quality byte).</summary>
private const byte QualityLimitMask = 0xFC;
/// <summary>One flag per quality byte, set once that byte has been warned about (#991 G-2). Process-wide.</summary>
private static readonly int[] UnrecognisedQualityWarned = new int[256];
private static void Log(ILogger? logger, byte q, string bucket)
{
// Best-effort diagnostic so field captures can extend the table — once per bucket
// per session is plenty (the LogWarning level is rate-limited by Serilog filters
// in production).
logger?.LogWarning(
// Best-effort diagnostic so field captures can extend the table — once per distinct byte per process
// (#991 G-2). This runs on the event pump's dispatch thread for every event carrying the byte, and a
// per-event Warning slowed dispatch until the bounded channel started dropping events.
if (logger is null || Interlocked.Exchange(ref UnrecognisedQualityWarned[q], 1) != 0) return;
logger.LogWarning(
"Unrecognised MXAccess quality byte 0x{Q:X2} — falling back to {Bucket} category. " +
"Field capture welcome — extend StatusCodeMap.FromQualityByte.", q, bucket);
"Field capture welcome — extend StatusCodeMap.FromQualityByte. Further occurrences of this byte are not logged.",
q, bucket);
}
}
@@ -1,5 +1,4 @@
using System.Collections.Concurrent;
using System.Collections.Immutable;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
@@ -31,7 +30,10 @@ internal sealed class SubscriptionRegistry
public const long ProbeSubscriptionId = -1;
private readonly ConcurrentDictionary<long, SubscriptionEntry> _bySubscriptionId = new();
private readonly ConcurrentDictionary<int, ImmutableHashSet<long>> _subscribersByItemHandle = new();
// #991 G-5: each item handle's subscribers as a pre-built, never-mutated array — rebuilt (copy-on-write, under
// _parkGate) only when a subscription binds or unbinds, so the per-event lookup on the dispatch thread hands the
// array out as-is instead of allocating a list, a LINQ Distinct and a boxed set enumerator per event.
private readonly ConcurrentDictionary<int, (long SubscriptionId, string FullReference)[]> _subscribersByItemHandle = new();
private long _nextSubscriptionId;
/// <summary>True when <paramref name="subscriptionId"/> is currently registered.</summary>
@@ -154,14 +156,15 @@ internal sealed class SubscriptionRegistry
return BindOutcome.UnknownId;
}
_bySubscriptionId[subscriptionId] = new SubscriptionEntry(subscriptionId, bindings, _session);
foreach (var binding in bindings)
var entry = new SubscriptionEntry(subscriptionId, bindings, _session);
_bySubscriptionId[subscriptionId] = entry;
// The entry's index holds each positive handle once (failed gw subscribes — handle <= 0 — expect no
// events), with the subscription's reference for it.
foreach (var (itemHandle, fullRef) in entry.FullRefByItemHandle)
{
if (binding.ItemHandle <= 0) continue; // failed gw subscribe — no events expected
_subscribersByItemHandle.AddOrUpdate(
binding.ItemHandle,
_ => [subscriptionId],
(_, set) => set.Add(subscriptionId));
_subscribersByItemHandle[itemHandle] = _subscribersByItemHandle.TryGetValue(itemHandle, out var current)
? WithSubscriber(current, subscriptionId, fullRef)
: [(subscriptionId, fullRef)];
}
AfterMapWriteForTests?.Invoke();
promoted = PromoteParkedEventsLocked(bindings);
@@ -172,19 +175,32 @@ internal sealed class SubscriptionRegistry
private void RemoveFromReverseMap(SubscriptionEntry entry)
{
foreach (var binding in entry.Bindings)
foreach (var itemHandle in entry.FullRefByItemHandle.Keys)
{
if (binding.ItemHandle <= 0) continue;
if (!_subscribersByItemHandle.TryGetValue(binding.ItemHandle, out var set)) continue;
var remaining = set.Remove(entry.SubscriptionId);
if (remaining.IsEmpty)
{
_subscribersByItemHandle.TryRemove(binding.ItemHandle, out _);
}
else _subscribersByItemHandle[binding.ItemHandle] = remaining;
if (!_subscribersByItemHandle.TryGetValue(itemHandle, out var current)) continue;
var remaining = Array.FindAll(current, s => s.SubscriptionId != entry.SubscriptionId);
if (remaining.Length == 0) _subscribersByItemHandle.TryRemove(itemHandle, out _);
else if (remaining.Length != current.Length) _subscribersByItemHandle[itemHandle] = remaining;
}
}
/// <summary>A copy of <paramref name="current"/> with <paramref name="subscriptionId"/> set to <paramref name="fullRef"/>.</summary>
private static (long SubscriptionId, string FullReference)[] WithSubscriber(
(long SubscriptionId, string FullReference)[] current, long subscriptionId, string fullRef)
{
var index = Array.FindIndex(current, s => s.SubscriptionId == subscriptionId);
if (index >= 0)
{
var replaced = ((long SubscriptionId, string FullReference)[])current.Clone();
replaced[index] = (subscriptionId, fullRef);
return replaced;
}
var grown = new (long SubscriptionId, string FullReference)[current.Length + 1];
current.CopyTo(grown, 0);
grown[^1] = (subscriptionId, fullRef);
return grown;
}
/// <summary>
/// Remove a subscription. Returns the bindings the caller should pass to
/// <c>UnsubscribeBulkAsync</c>; null when the id was never registered.
@@ -220,21 +236,14 @@ internal sealed class SubscriptionRegistry
/// </summary>
/// <param name="itemHandle">The gateway item handle.</param>
/// <returns>A list of subscription and reference pairs for the item handle.</returns>
public IReadOnlyList<(long SubscriptionId, string FullReference)> ResolveSubscribers(int itemHandle)
{
if (!_subscribersByItemHandle.TryGetValue(itemHandle, out var bag)) return [];
// Each subscription may include the tag once. Walk every active subscription that
// claims this handle and pull the full ref from its index in O(1).
var result = new List<(long, string)>();
foreach (var subId in bag.Distinct())
{
if (!_bySubscriptionId.TryGetValue(subId, out var entry)) continue;
if (entry.FullRefByItemHandle.TryGetValue(itemHandle, out var fullRef))
result.Add((subId, fullRef));
}
return result;
}
/// <remarks>
/// Allocation-free (#991 G-5): returns the handle's pre-built subscriber array itself. It is never mutated —
/// a bind or unbind publishes a new array — so the caller may enumerate it while the map changes.
/// </remarks>
public IReadOnlyList<(long SubscriptionId, string FullReference)> ResolveSubscribers(int itemHandle) =>
_subscribersByItemHandle.TryGetValue(itemHandle, out var subscribers)
? subscribers
: Array.Empty<(long SubscriptionId, string FullReference)>();
/// <summary>
/// Drop every subscription and the whole reverse map. Used by the driver's runtime teardown:
@@ -650,6 +659,17 @@ internal sealed class SubscriptionRegistry
public IReadOnlyList<(long SubscriptionId, IReadOnlyList<TagBinding> Bindings)> SnapshotEntriesNotIn(int session) =>
[.. _bySubscriptionId.Values.Where(e => e.Session != session).Select(e => (e.SubscriptionId, e.Bindings))];
/// <summary>
/// <see cref="SnapshotEntries"/> limited to subscriptions whose handles WERE issued by <paramref name="session"/>
/// — the same-session re-advise work list (#991: replay-gap re-snapshot, dropped-event resync). Their handles
/// are live, so a re-advise must release the ones it supersedes; a subscription still holding an older
/// session's handles belongs to the reconnect replay instead.
/// </summary>
/// <param name="session">The current session.</param>
/// <returns>The current-session subscriptions with their bindings.</returns>
public IReadOnlyList<(long SubscriptionId, IReadOnlyList<TagBinding> Bindings)> SnapshotEntriesIn(int session) =>
[.. _bySubscriptionId.Values.Where(e => e.Session == session).Select(e => (e.SubscriptionId, e.Bindings))];
/// <summary>
/// Per-subscription bookkeeping. <see cref="FullRefByItemHandle"/> is an index
/// over <see cref="Bindings"/> keyed by item handle so <c>ResolveSubscribers</c>