Merge branch 'master' into fix/832-docker-dev-batch

This commit is contained in:
Joseph Doherty
2026-11-11 02:32:42 -05:00
140 changed files with 6336 additions and 568 deletions
@@ -64,9 +64,11 @@ public sealed record GalaxyDriverOptions(
/// </list>
/// </para>
/// <para>
/// <see cref="FallbackPasswordSecretRef"/> must be a reference — <c>secret:NAME</c> (production),
/// <c>env:NAME</c>, <c>file:PATH</c> or <c>dev:VALUE</c> (rigs only). A bare literal is rejected so a
/// Galaxy password can never sit in cleartext in the DriverConfig JSON / config DB.
/// <see cref="FallbackPasswordSecretRef"/> must be a Galaxy-namespaced reference (lmxopcua#815) —
/// <c>secret:galaxy/NAME</c> / <c>secret:otopcua/galaxy/NAME</c> (production), <c>env:OTOPCUA_GALAXY_NAME</c>
/// / <c>env:GALAXY_MXGW_NAME</c>, or <c>dev:VALUE</c> (rigs only). A bare literal, <c>file:</c> and any other
/// reference are rejected so a Galaxy password never sits in cleartext in the config DB and the field can
/// never name another subsystem's secret.
/// </para>
/// </remarks>
/// <param name="FallbackUser">Galaxy user the fallback acknowledges as; null/empty = no fallback.</param>
@@ -84,20 +86,16 @@ public sealed record GalaxyAlarmAckOptions(
/// <summary>
/// Connection details for the MxAccess gateway. <see cref="ApiKeySecretRef"/> is
/// resolved by <see cref="GalaxySecretRef.ResolveApiKeyAsync"/> at InitializeAsync time. Five forms
/// supported, in priority order:
/// resolved by <see cref="GalaxySecretRef.ResolveApiKeyAsync"/> at InitializeAsync time. References are confined
/// to the Galaxy namespace (lmxopcua#815 — the key is sent to the authored <c>Endpoint</c>):
/// <list type="bullet">
/// <item><c>env:NAME</c> — read from an environment variable (recommended for
/// production; the central config DB holds only the indirection, not the key).</item>
/// <item><c>file:PATH</c> — read from an ACL'd file outside the repo.</item>
/// <item><c>secret:NAME</c> — resolved through the shared <c>ZB.MOM.WW.Secrets</c>
/// <item><c>secret:galaxy/NAME</c> (or <c>secret:otopcua/galaxy/NAME</c>) — the shared <c>ZB.MOM.WW.Secrets</c>
/// encrypted store; fail-closed if absent (the production path).</item>
/// <item><c>dev:KEY</c> — explicit cleartext opt-in for dev rigs / parity tests;
/// no startup warning.</item>
/// <item>Anything else — treated as a literal cleartext API key for back-compat.
/// The resolver emits a <c>Warning</c> at startup so an operator who accidentally
/// committed a cleartext key sees it; production should migrate to <c>env:</c>
/// or <c>file:</c>.</item>
/// <item><c>env:OTOPCUA_GALAXY_NAME</c> (or legacy <c>env:GALAXY_MXGW_NAME</c>) — an environment variable.</item>
/// <item><c>dev:KEY</c> — explicit cleartext opt-in for dev rigs / parity tests; no startup warning.</item>
/// <item>Any other unprefixed string — a literal cleartext API key for back-compat, with a startup
/// <c>Warning</c>.</item>
/// <item>Any other <c>secret:</c>/<c>env:</c> reference, and every <c>file:</c> reference — refused.</item>
/// </list>
/// </summary>
// PR 6.5 tuning notes:
@@ -1,33 +1,24 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
/// <summary>
/// Resolves <c>Gateway.ApiKeySecretRef</c> to the actual API-key string. Five
/// forms supported, evaluated in order:
/// Resolves <c>Gateway.ApiKeySecretRef</c> to the actual API-key string. The reference is resolved on the node
/// and sent to the operator-authored <c>Gateway.Endpoint</c>, so references are confined to the Galaxy
/// namespace (lmxopcua#815, <see cref="DriverCredentialPolicy.GalaxyScope"/>) and the check is repeated here, at
/// resolve time, before any store or environment read:
/// <list type="number">
/// <item><c>env:NAME</c> — reads <c>Environment.GetEnvironmentVariable(NAME)</c>.
/// Throws when the variable is unset, so a misconfigured deployment fails
/// fast rather than silently sending an empty key.</item>
/// <item><c>file:PATH</c> — reads UTF-8 text from <c>PATH</c>, trimming
/// whitespace. Lets operators stash the key in an ACL'd file outside the
/// repo (the same pattern as the legacy <c>.local/galaxy-host-secret.txt</c>).</item>
/// <item><c>dev:KEY</c> — explicit cleartext literal. The <c>dev:</c> prefix
/// is a deliberate opt-in signal (dev box, parity rig) so the resolver
/// doesn't emit a warning; production should never use this arm.</item>
/// <item><c>secret:NAME</c> — resolves NAME through the shared
/// <c>ZB.MOM.WW.Secrets</c> <see cref="ISecretResolver"/> (the encrypted-at-rest
/// store). Fail-closed: a <c>secret:</c> ref whose secret is absent/tombstoned
/// throws rather than falling through to the literal arm — the production path
/// that retires the cleartext <c>dev:</c>/literal-in-DB model.</item>
/// <item>Anything else — used as the literal API key for back-compat with
/// configs that pre-date this resolver. When a logger is supplied the
/// resolver emits a startup warning so an operator who accidentally
/// committed a cleartext key sees it.</item>
/// <item><c>secret:galaxy/NAME</c> (or <c>${secret:galaxy/NAME}</c>) — resolved through the shared
/// <c>ZB.MOM.WW.Secrets</c> <see cref="ISecretResolver"/>; fail-closed when absent.</item>
/// <item><c>env:OTOPCUA_GALAXY_NAME</c> / legacy <c>env:GALAXY_MXGW_NAME</c> — the process environment;
/// fail-closed when unset.</item>
/// <item><c>dev:KEY</c> — explicit cleartext literal (dev box, parity rig); no warning.</item>
/// <item>Any other unprefixed string — the literal key (back-compat), with a warning when a logger is supplied.</item>
/// <item>A <c>secret:</c>/<c>env:</c> reference OUTSIDE the namespace, and every <c>file:</c> reference (it
/// read any file the node could open) — refused with <see cref="CredentialReferenceException"/>.</item>
/// </list>
/// A future PR can swap any of these arms for a different backing store without
/// changing the call site.
/// </summary>
/// <remarks>
/// Lives in the Contracts project so both the runtime <c>GalaxyDriver</c> and the
@@ -37,80 +28,108 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
public static class GalaxySecretRef
{
/// <summary>
/// Resolves the supplied secret reference. The <c>secret:NAME</c> arm resolves
/// through <paramref name="resolver"/> and is fail-closed (throws when the secret
/// is absent). When the ref falls through to the back-compat literal arm (an
/// unprefixed cleartext API key in <c>DriverConfig</c> JSON) and a
/// <paramref name="logger"/> is supplied, emits a <see cref="LogLevel.Warning"/>.
/// The <c>dev:</c> prefix is the explicit opt-in path that doesn't warn.
/// Resolves the supplied API-key reference (see the type remarks). Fail-closed for an out-of-namespace
/// reference, a <c>file:</c> reference, an absent secret and an unset variable.
/// </summary>
/// <param name="secretRef">The secret reference string to resolve.</param>
/// <param name="resolver">The shared secret resolver used by the <c>secret:</c> arm.</param>
/// <param name="logger">Optional logger for warning on cleartext keys.</param>
/// <param name="ct">Cancellation token for the async <c>secret:</c> resolution.</param>
/// <param name="environment">Environment reader (tests); null ⇒ the process environment.</param>
/// <param name="legacy">
/// ⚠️ Deprecated #815 compatibility: the RUNNING driver passes its tracker, so a pre-#815 out-of-namespace
/// reference is resolved with the old semantics and warned about instead of failing. The AdminUI browser
/// passes null (hard-fail). See <see cref="LegacyCredentialReferenceTracker"/>.
/// </param>
/// <returns>The resolved API-key string.</returns>
public static async Task<string> ResolveApiKeyAsync(
string secretRef,
ISecretResolver resolver,
ILogger? logger = null,
CancellationToken ct = default)
CancellationToken ct = default,
Func<string, string?>? environment = null,
LegacyCredentialReferenceTracker? legacy = null)
{
ArgumentException.ThrowIfNullOrEmpty(secretRef);
ArgumentNullException.ThrowIfNull(resolver);
var scope = DriverCredentialPolicy.GalaxyScope;
var kind = CredentialReferences.Parse(secretRef, scope, out _);
if (kind == CredentialReferenceKind.OutOfScope && legacy is not null)
{
legacy.Report("Gateway.ApiKeySecretRef");
return await LegacyResolveApiKeyAsync(secretRef, resolver, logger, ct, environment).ConfigureAwait(false);
}
if (kind == CredentialReferenceKind.Literal)
{
if (secretRef.StartsWith(CredentialReferences.DevPrefix, StringComparison.OrdinalIgnoreCase))
{
// Explicit dev opt-in — no warning, the operator deliberately chose a cleartext literal.
return secretRef[CredentialReferences.DevPrefix.Length..];
}
// Back-compat literal arm. Warn so an operator who accidentally committed a cleartext key sees it.
logger?.LogWarning(
"Galaxy.Gateway.ApiKeySecretRef is being treated as a literal cleartext API key. " +
"Prefer secret:galaxy/<name> or env:OTOPCUA_GALAXY_<NAME>, or the explicit dev:KEY prefix for dev rigs — " +
"a literal key in DriverConfig JSON is stored in cleartext in the central config DB.");
return secretRef;
}
// secret:/env: inside the namespace resolve; anything else (out of scope, file:) throws before any read.
return await CredentialReferences.ResolveAsync(
secretRef,
scope,
"Galaxy.Gateway.ApiKeySecretRef",
DriverCredentialPolicy.GalaxyApiKeyField.Literals,
async (name, c) => await resolver.GetAsync(new SecretName(name), c).ConfigureAwait(false),
environment,
ct).ConfigureAwait(false);
}
/// <summary>
/// ⚠️ DEPRECATED (lmxopcua#815 warn-only compatibility; delete in the hard-fail release): the pre-#815 resolver,
/// verbatim — case-insensitive <c>env:</c> / <c>file:</c> / <c>dev:</c> / <c>secret:</c>, anything else a
/// literal. Reached ONLY for an out-of-namespace reference in an already-deployed, running driver.
/// </summary>
private static async Task<string> LegacyResolveApiKeyAsync(
string secretRef, ISecretResolver resolver, ILogger? logger, CancellationToken ct, Func<string, string?>? environment)
{
if (secretRef.StartsWith("env:", StringComparison.OrdinalIgnoreCase))
{
var name = secretRef[4..];
var value = Environment.GetEnvironmentVariable(name);
var value = (environment ?? Environment.GetEnvironmentVariable)(name);
return !string.IsNullOrEmpty(value)
? value
: throw new InvalidOperationException(
$"Galaxy.Gateway.ApiKeySecretRef='{secretRef}' resolves to env var '{name}', but it is unset.");
$"Galaxy.Gateway.ApiKeySecretRef resolves to env var '{name}', but it is unset.");
}
if (secretRef.StartsWith("file:", StringComparison.OrdinalIgnoreCase))
{
var path = secretRef[5..];
if (!File.Exists(path))
{
throw new InvalidOperationException(
$"Galaxy.Gateway.ApiKeySecretRef='{secretRef}' points at '{path}', which doesn't exist.");
}
var contents = File.ReadAllText(path).Trim();
throw new InvalidOperationException($"Galaxy.Gateway.ApiKeySecretRef points at '{path}', which doesn't exist.");
var contents = (await File.ReadAllTextAsync(path, ct).ConfigureAwait(false)).Trim();
return !string.IsNullOrEmpty(contents)
? contents
: throw new InvalidOperationException(
$"Galaxy.Gateway.ApiKeySecretRef='{secretRef}' file '{path}' is empty.");
: throw new InvalidOperationException($"Galaxy.Gateway.ApiKeySecretRef file '{path}' is empty.");
}
if (secretRef.StartsWith("dev:", StringComparison.OrdinalIgnoreCase))
{
// Explicit dev opt-in — no warning, the operator deliberately chose a
// cleartext literal (dev box, parity rig).
return secretRef[4..];
}
if (secretRef.StartsWith("dev:", StringComparison.OrdinalIgnoreCase)) return secretRef[4..];
if (secretRef.StartsWith("secret:", StringComparison.OrdinalIgnoreCase))
{
// Production path: resolve the name through the shared encrypted secret store.
// Fail-closed — an absent/tombstoned secret throws rather than falling through
// to the literal arm (which would silently treat the ref string as the key).
var name = secretRef["secret:".Length..];
var value = await resolver.GetAsync(new SecretName(name), ct).ConfigureAwait(false);
return !string.IsNullOrEmpty(value)
? value
: throw new InvalidOperationException(
$"Galaxy.Gateway.ApiKeySecretRef='{secretRef}' resolves secret '{name}', but it is absent from the store (fail-closed).");
$"Galaxy.Gateway.ApiKeySecretRef resolves secret '{name}', but it is absent from the store (fail-closed).");
}
// Back-compat literal arm. An unprefixed string is treated as the literal
// API key — but emit a warning so an operator who accidentally committed a
// cleartext key into DriverConfig sees it. Use the dev: prefix to suppress
// this warning when the literal is intentional.
logger?.LogWarning(
"Galaxy.Gateway.ApiKeySecretRef is being treated as a literal cleartext API key. " +
"Prefer env:NAME, file:PATH, or the explicit dev:KEY prefix for dev rigs — " +
"a literal key in DriverConfig JSON is stored in cleartext in the central config DB.");
logger?.LogWarning("Galaxy.Gateway.ApiKeySecretRef is being treated as a literal cleartext API key.");
return secretRef;
}
}
@@ -38,8 +38,17 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy;
/// </para>
/// </remarks>
public sealed class GalaxyDriver
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmAcknowledgePreflight, ISkippedTagReporter, IDisposable, IAsyncDisposable
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmAcknowledgePreflight, ISkippedTagReporter, IDriverDiagnostics, IDisposable, IAsyncDisposable
{
// ⚠️ lmxopcua#815 warn-only compatibility (deprecated): this RUNNING driver keeps resolving a pre-#815
// out-of-namespace credential reference (API key on InitializeAsync AND every gateway ReopenAsync, plus the
// ack fallback password) with the old semantics, warning rate-limited and surfacing it on the diagnostics bag.
// The AdminUI browser and the probe never get a tracker, so they stay hard-fail.
private readonly LegacyCredentialReferenceTracker _legacyCredentials;
/// <inheritdoc />
IReadOnlyDictionary<string, string> IDriverDiagnostics.GetDiagnostics() => _legacyCredentials.Diagnostics;
/// <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();
@@ -342,6 +351,8 @@ public sealed class GalaxyDriver
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? NullLogger<GalaxyDriver>.Instance;
_secretResolver = secretResolver ?? NullSecretResolver.Instance;
_legacyCredentials = new LegacyCredentialReferenceTracker(
DriverCredentialPolicy.GalaxyScope, _driverInstanceId, message => _logger.LogWarning("{CredentialCompatWarning}", message));
_hierarchySource = hierarchySource;
_dataReader = dataReader;
_dataWriter = dataWriter;
@@ -349,7 +360,7 @@ public sealed class GalaxyDriver
_alarmAcknowledger = alarmAcknowledger;
_alarmFeed = alarmFeed;
_ackCredentialResolver = ackCredentialResolver
?? new GalaxyAckCredentialResolver(_driverInstanceId, _options.AlarmAck, _secretResolver, _logger);
?? new GalaxyAckCredentialResolver(_driverInstanceId, _options.AlarmAck, _secretResolver, _logger, legacy: _legacyCredentials);
// 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.
@@ -1098,7 +1109,9 @@ public sealed class GalaxyDriver
}
}
private async Task<MxGatewayClientOptions> BuildClientOptionsAsync(
// Internal: the ONE client-options build InitializeAsync, ReopenAsync (every gateway reconnect) and the
// repository/alarm clients share — the #815 warn-only tests drive it directly to prove a reconnect re-resolves.
internal async Task<MxGatewayClientOptions> BuildClientOptionsAsync(
GalaxyGatewayOptions gw, CancellationToken cancellationToken)
{
// Resolve the API-key ref BEFORE the object initializer — the secret: arm is
@@ -1108,7 +1121,7 @@ public sealed class GalaxyDriver
// (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)
.ResolveApiKeyAsync(gw.ApiKeySecretRef, _secretResolver, _logger, cancellationToken, legacy: _legacyCredentials)
.ConfigureAwait(false);
return new MxGatewayClientOptions
{
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
using ZB.MOM.WW.Secrets.Abstractions;
@@ -20,15 +21,22 @@ internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver
private readonly GalaxyAlarmAckOptions _options;
private readonly ISecretResolver _secrets;
private readonly ILogger _logger;
private readonly Func<string, string?>? _environment;
private readonly LegacyCredentialReferenceTracker? _legacy;
/// <summary>Initializes a new instance of the <see cref="GalaxyAckCredentialResolver"/> class.</summary>
/// <param name="driverInstanceId">The owning driver instance id (for messages).</param>
/// <param name="options">The driver's ack-credential options.</param>
/// <param name="secrets">The shared secret resolver.</param>
/// <param name="logger">Logger; never receives a secret.</param>
/// <param name="environment">Environment reader (tests); null ⇒ the process environment.</param>
/// <param name="legacy">⚠️ #815 warn-only compatibility tracker of the running driver (deprecated); null ⇒ hard-fail.</param>
public GalaxyAckCredentialResolver(
string driverInstanceId, GalaxyAlarmAckOptions? options, ISecretResolver secrets, ILogger logger)
string driverInstanceId, GalaxyAlarmAckOptions? options, ISecretResolver secrets, ILogger logger,
Func<string, string?>? environment = null, LegacyCredentialReferenceTracker? legacy = null)
{
_environment = environment;
_legacy = legacy;
_driverInstanceId = driverInstanceId;
_options = options ?? new GalaxyAlarmAckOptions();
_secrets = secrets ?? throw new ArgumentNullException(nameof(secrets));
@@ -142,56 +150,57 @@ internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver
}
/// <summary>
/// Resolves a password reference. Accepts <c>secret:NAME</c>, <c>${secret:NAME}</c>, <c>env:NAME</c>,
/// <c>file:PATH</c> and <c>dev:VALUE</c>; returns null when the referenced value is absent; throws
/// <see cref="FormatException"/> for a bare literal (a cleartext password in DriverConfig).
/// Resolves the fallback password reference through the shared lmxopcua#815 resolver: <c>secret:galaxy/NAME</c>
/// (or <c>secret:otopcua/galaxy/NAME</c>, <c>${secret:…}</c>), <c>env:OTOPCUA_GALAXY_NAME</c> /
/// <c>env:GALAXY_MXGW_NAME</c>, or <c>dev:VALUE</c>; returns null when the referenced value is absent; throws
/// <see cref="CredentialReferenceException"/> — before any store/environment read — for a bare literal, a
/// <c>file:</c> reference, or a reference outside the Galaxy namespace (the password is sent to the
/// operator-authored gateway endpoint, so it must never be able to name another subsystem's secret).
/// </summary>
internal async Task<string?> ResolvePasswordRefAsync(string reference, CancellationToken ct)
{
if (_legacy is not null
&& CredentialReferences.Parse(reference, DriverCredentialPolicy.GalaxyScope, out _) == CredentialReferenceKind.OutOfScope)
{
_legacy.Report("AlarmAck.FallbackPasswordSecretRef");
return await LegacyResolvePasswordRefAsync(reference, ct).ConfigureAwait(false);
}
var resolved = await CredentialReferences.ResolveOrNullAsync(
reference,
DriverCredentialPolicy.GalaxyScope,
"AlarmAck.FallbackPasswordSecretRef",
DriverCredentialPolicy.GalaxyAckPasswordField.Literals,
async (name, c) => await _secrets.GetAsync(new SecretName(name), c).ConfigureAwait(false),
_environment,
ct).ConfigureAwait(false);
return resolved is not null && reference.StartsWith(CredentialReferences.DevPrefix, StringComparison.OrdinalIgnoreCase)
? resolved[CredentialReferences.DevPrefix.Length..]
: resolved;
}
/// <summary>
/// ⚠️ DEPRECATED (lmxopcua#815 warn-only compatibility; delete in the hard-fail release): the pre-#815 resolver,
/// verbatim. Reached ONLY for an out-of-namespace reference in an already-deployed, running driver.
/// </summary>
private async Task<string?> LegacyResolvePasswordRefAsync(string reference, CancellationToken ct)
{
if (reference.StartsWith("${secret:", StringComparison.OrdinalIgnoreCase) && reference.EndsWith('}'))
{
reference = "secret:" + reference["${secret:".Length..^1];
}
if (reference.StartsWith("secret:", StringComparison.OrdinalIgnoreCase))
{
return await _secrets.GetAsync(new SecretName(reference["secret:".Length..]), ct).ConfigureAwait(false);
}
if (reference.StartsWith("env:", StringComparison.OrdinalIgnoreCase))
{
return Environment.GetEnvironmentVariable(reference[4..]);
}
return (_environment ?? Environment.GetEnvironmentVariable)(reference[4..]);
if (reference.StartsWith("file:", StringComparison.OrdinalIgnoreCase))
{
var path = reference[5..];
return File.Exists(path)
? (await File.ReadAllTextAsync(path, ct).ConfigureAwait(false)).TrimEnd('\r', '\n')
: null;
return File.Exists(path) ? (await File.ReadAllTextAsync(path, ct).ConfigureAwait(false)).TrimEnd('\r', '\n') : null;
}
if (reference.StartsWith("dev:", StringComparison.OrdinalIgnoreCase))
{
return reference[4..];
}
throw new FormatException("AlarmAck.FallbackPasswordSecretRef must be a secret:/env:/file:/dev: reference, not a literal.");
if (reference.StartsWith("dev:", StringComparison.OrdinalIgnoreCase)) return reference[4..];
throw new FormatException("AlarmAck.FallbackPasswordSecretRef must be a secret:/env:/dev: reference, not a literal.");
}
// Safe-to-print form of a reference: the kind + name for secret/env/file, never the dev: value or a literal.
internal static string DescribeRef(string reference)
{
var r = reference.Trim();
if (r.StartsWith("dev:", StringComparison.OrdinalIgnoreCase)) return "dev:<redacted>";
if (r.StartsWith("${secret:", StringComparison.OrdinalIgnoreCase)
|| r.StartsWith("secret:", StringComparison.OrdinalIgnoreCase)
|| r.StartsWith("env:", StringComparison.OrdinalIgnoreCase)
|| r.StartsWith("file:", StringComparison.OrdinalIgnoreCase))
{
return r;
}
return "<literal redacted>";
}
internal static string DescribeRef(string reference) => CredentialReferences.Describe(reference);
}
@@ -30,6 +30,12 @@ public enum HeidenhainAddressKind
/// <summary>A data-path value read via <c>R_DP</c> (DATA role).</summary>
DataPath,
/// <summary>
/// An <c>ALARM:</c> selector — a native Part 9 condition driven from the alarm list (<c>R_RI 27/28</c>), never a
/// value (lmxopcua#831). Requires the cross-driver <c>alarm</c> object on the tag.
/// </summary>
Alarm,
}
/// <summary>A parsed, validated Heidenhain tag address.</summary>
@@ -39,13 +45,15 @@ public enum HeidenhainAddressKind
/// <param name="Area">The PLC area, for <see cref="HeidenhainAddressKind.Plc"/>.</param>
/// <param name="Index">The PLC <b>element</b> index (not an absolute address), for <see cref="HeidenhainAddressKind.Plc"/>.</param>
/// <param name="DataPath">The data path as authored, for <see cref="HeidenhainAddressKind.DataPath"/>.</param>
/// <param name="AlarmSelector">The alarm selector, for <see cref="HeidenhainAddressKind.Alarm"/>.</param>
public sealed record HeidenhainAddress(
HeidenhainAddressKind Kind,
string Text,
HeidenhainCatalogEntry? Catalog = null,
HeidenhainPlcArea? Area = null,
long Index = 0,
string? DataPath = null)
string? DataPath = null,
HeidenhainAlarmSelector? AlarmSelector = null)
{
/// <summary>Legacy-buffer LSV2 payload maximum (255-byte frame − 8-byte header).</summary>
public const int MaxPayload = 247;
@@ -117,6 +125,14 @@ public sealed record HeidenhainAddress(
return false;
}
if (t.StartsWith(HeidenhainAlarmSelector.Prefix, StringComparison.Ordinal))
{
if (!HeidenhainAlarmSelector.TryParse(t[HeidenhainAlarmSelector.Prefix.Length..], out var selector, out error)) return false;
address = new HeidenhainAddress(HeidenhainAddressKind.Alarm, HeidenhainAlarmSelector.Prefix + selector.Canonical,
AlarmSelector: selector);
return true;
}
if (t.StartsWith(DataPrefix, StringComparison.Ordinal))
{
var path = t[DataPrefix.Length..];
@@ -157,7 +173,7 @@ public sealed record HeidenhainAddress(
return true;
}
error = $"'{t}' is not a fixed Heidenhain leaf (e.g. Status/ExecutionState), a PLC:AREA:INDEX binding or a DATA:/path binding.";
error = $"'{t}' is not a fixed Heidenhain leaf (e.g. Status/ExecutionState), a PLC:AREA:INDEX binding, a DATA:/path binding or an ALARM: selector.";
return false;
}
@@ -0,0 +1,191 @@
using System.Globalization;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
/// <summary>Which controller alarms an <c>ALARM:</c> address selects.</summary>
public enum HeidenhainAlarmSelectorKind
{
/// <summary><c>ALARM:*</c> — any active alarm on the tag's control (a device summary condition).</summary>
Any,
/// <summary>
/// <c>ALARM:OTHER</c> — active alarms that no <see cref="Filter"/> selector on the same control matches (the
/// "unmatched" bucket). <see cref="Any"/> and other <see cref="Other"/> tags do not claim an alarm.
/// </summary>
Other,
/// <summary><c>ALARM:CLASS=7</c>, <c>ALARM:CLASS=7/GROUP=4</c>, <c>ALARM:NUMBER=100..199</c>, …</summary>
Filter,
}
/// <summary>An inclusive integer range; <see cref="Low"/> == <see cref="High"/> for a single value.</summary>
/// <param name="Low">Lowest matched value.</param>
/// <param name="High">Highest matched value (inclusive).</param>
public readonly record struct HeidenhainAlarmRange(long Low, long High)
{
/// <summary>Whether <paramref name="value"/> lies in the range.</summary>
/// <param name="value">The value.</param>
/// <returns>True when matched.</returns>
public bool Contains(long value) => value >= Low && value <= High;
/// <inheritdoc />
public override string ToString() => Low == High
? Low.ToString(CultureInfo.InvariantCulture)
: $"{Low.ToString(CultureInfo.InvariantCulture)}..{High.ToString(CultureInfo.InvariantCulture)}";
}
/// <summary>
/// The selector half of an <c>ALARM:</c> Heidenhain address (lmxopcua#831): which entries of the control's
/// active-alarm list (<c>R_RI 27</c> then <c>28</c> — class, group, number, text) drive the ONE Part 9 condition
/// the raw tag is materialised as.
/// </summary>
/// <remarks>
/// <para>Grammar of the text after <c>ALARM:</c> (keys case-insensitive, no whitespace):</para>
/// <list type="table">
/// <listheader><term>Form</term><description>Matches</description></listheader>
/// <item><term><c>*</c></term><description>any active alarm on the control</description></item>
/// <item><term><c>OTHER</c></term><description>alarms no filter selector on the control matches</description></item>
/// <item><term><c>CLASS=&lt;r&gt;</c>, <c>GROUP=&lt;r&gt;</c>, <c>NUMBER=&lt;r&gt;</c>, joined by <c>/</c></term>
/// <description>every named field in its range (each key at most once)</description></item>
/// </list>
/// <para>A range <c>&lt;r&gt;</c> is <c>n</c> or <c>lo..hi</c> (inclusive; <c>..</c> rather than <c>-</c> because
/// alarm numbers can be negative — a real iTNC 530 reports <c>-1</c>). CLASS and GROUP are the wire's uint16
/// fields (0–65535); NUMBER is int32.</para>
/// <para><b>No semantic names.</b> The meaning of the class/group codes is not documented in the reference
/// (pyLSV2 / the Java port keep them raw), so — like FOCAS's unconfirmed 30i type table — nothing is guessed:
/// observe the raw values on <c>Alarms/Classes</c> / <c>Alarms/Groups</c> or in a condition message, then filter.</para>
/// <para><b>One authority.</b> Backs the AdminUI editor, the deploy inspector and the driver's table build.</para>
/// </remarks>
/// <param name="Kind">The selector kind.</param>
/// <param name="Class">The class range, or null for any class (filter only).</param>
/// <param name="Group">The group range, or null for any group (filter only).</param>
/// <param name="Number">The number range, or null for any number (filter only).</param>
public sealed record HeidenhainAlarmSelector(
HeidenhainAlarmSelectorKind Kind,
HeidenhainAlarmRange? Class = null,
HeidenhainAlarmRange? Group = null,
HeidenhainAlarmRange? Number = null)
{
/// <summary>Address prefix of an alarm condition.</summary>
public const string Prefix = "ALARM:";
/// <summary>The <c>*</c> body.</summary>
public const string AnyToken = "*";
/// <summary>The <c>OTHER</c> body.</summary>
public const string OtherToken = "OTHER";
/// <summary>The canonical text after <c>ALARM:</c>.</summary>
public string Canonical => Kind switch
{
HeidenhainAlarmSelectorKind.Any => AnyToken,
HeidenhainAlarmSelectorKind.Other => OtherToken,
_ => string.Join("/", new[]
{
Class is { } c ? $"CLASS={c}" : null,
Group is { } g ? $"GROUP={g}" : null,
Number is { } n ? $"NUMBER={n}" : null,
}.Where(s => s is not null)),
};
/// <summary>
/// Whether this selector matches one alarm on its own terms. <see cref="HeidenhainAlarmSelectorKind.Other"/>
/// answers false here — "unmatched" depends on the other selectors on the control, which the caller evaluates.
/// </summary>
/// <param name="errorClass">The alarm's class.</param>
/// <param name="group">The alarm's group.</param>
/// <param name="number">The alarm's number.</param>
/// <returns>True when selected.</returns>
public bool Matches(int errorClass, int group, int number) => Kind switch
{
HeidenhainAlarmSelectorKind.Any => true,
HeidenhainAlarmSelectorKind.Other => false,
_ => (Class is not { } c || c.Contains(errorClass))
&& (Group is not { } g || g.Contains(group))
&& (Number is not { } n || n.Contains(number)),
};
/// <summary>Parses the text after <c>ALARM:</c>. Never throws.</summary>
/// <param name="body">The selector text.</param>
/// <param name="selector">The selector on success.</param>
/// <param name="error">Why it was rejected.</param>
/// <returns>True when valid.</returns>
public static bool TryParse(string? body, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out HeidenhainAlarmSelector? selector, out string? error)
{
selector = null;
error = null;
var t = body?.Trim() ?? "";
if (t.Length == 0)
{
error = Grammar("an alarm selector is required");
return false;
}
if (t == AnyToken)
{
selector = new HeidenhainAlarmSelector(HeidenhainAlarmSelectorKind.Any);
return true;
}
if (string.Equals(t, OtherToken, StringComparison.OrdinalIgnoreCase))
{
selector = new HeidenhainAlarmSelector(HeidenhainAlarmSelectorKind.Other);
return true;
}
HeidenhainAlarmRange? cls = null, grp = null, num = null;
foreach (var segment in t.Split('/'))
{
var eq = segment.IndexOf('=');
if (eq <= 0)
{
error = Grammar($"'{segment}' is not KEY=VALUE");
return false;
}
var key = segment[..eq].ToUpperInvariant();
var value = segment[(eq + 1)..];
var (min, max) = key == "NUMBER" ? ((long)int.MinValue, (long)int.MaxValue) : (0L, 65535L);
if (key is not ("CLASS" or "GROUP" or "NUMBER"))
{
error = Grammar($"unknown key '{segment[..eq]}'");
return false;
}
if (!TryParseRange(value, min, max, out var range))
{
error = Grammar($"{key} value '{value}' must be an integer {min}–{max} or lo..hi with lo ≤ hi");
return false;
}
ref var slot = ref key == "CLASS" ? ref cls : ref key == "GROUP" ? ref grp : ref num;
if (slot is not null)
{
error = Grammar($"{key} appears twice");
return false;
}
slot = range;
}
selector = new HeidenhainAlarmSelector(HeidenhainAlarmSelectorKind.Filter, cls, grp, num);
return true;
}
private static bool TryParseRange(string text, long min, long max, out HeidenhainAlarmRange range)
{
range = default;
var dots = text.IndexOf("..", StringComparison.Ordinal);
var loText = dots < 0 ? text : text[..dots];
var hiText = dots < 0 ? text : text[(dots + 2)..];
if (!long.TryParse(loText, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var lo)
|| !long.TryParse(hiText, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var hi))
return false;
if (lo < min || hi > max || lo > hi) return false;
range = new HeidenhainAlarmRange(lo, hi);
return true;
}
private static string Grammar(string why) =>
$"Invalid alarm selector: {why}. Use ALARM:*, ALARM:OTHER or ALARM:CLASS=<n>[/GROUP=<n>][/NUMBER=<n>|<lo>..<hi>].";
}
@@ -13,6 +13,9 @@ public enum HeidenhainPollGroup
/// <summary>Identity, tool, alarms, timers and capability strings (<c>Polling.SlowMs</c>).</summary>
Slow,
/// <summary>The alarm-list walk behind <c>ALARM:</c> Part 9 conditions (<c>Polling.AlarmMs</c>, lmxopcua#831).</summary>
Alarm,
}
/// <summary>One fixed-namespace leaf: its address, OPC data type, rank, cadence and the feature that serves it.</summary>
@@ -50,6 +53,9 @@ public static class HeidenhainCatalog
/// <summary>Feature id reported for the optional DNC login.</summary>
public const string DncLoginFeature = "DncLogin";
/// <summary>Feature id of the alarm-list walk (<c>R_RI 27/28</c>) — shared by the <c>Alarms/*</c> leaves and <c>ALARM:</c> conditions.</summary>
public const string AlarmsFeature = "Alarms";
/// <summary>Feature id reported for the opt-in DATA login.</summary>
public const string DataLoginFeature = "DataLogin";
@@ -107,6 +107,13 @@ public sealed class HeidenhainPollingOptions
/// <summary>Slow group: identity, tool, alarms, timers, capabilities. Default 10000 ms.</summary>
public int SlowMs { get; init; } = 10000;
/// <summary>
/// Alarm-condition group: the alarm-list walk that drives authored <c>ALARM:</c> Part 9 conditions
/// (lmxopcua#831). Default 2000 ms (the FOCAS alarm-poll precedent). Only polled for a control that carries an
/// <c>ALARM:</c> tag; the <c>Alarms/*</c> typed arrays stay on <see cref="SlowMs"/>.
/// </summary>
public int AlarmMs { get; init; } = 2000;
/// <summary>Alarm list limit (1–256). Overflow makes every alarm leaf Bad rather than truncating. Default 64.</summary>
public int MaxAlarms { get; init; } = 64;
@@ -1,4 +1,5 @@
using System.Text.Json;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
@@ -21,14 +22,14 @@ public static class HeidenhainOptionsParser
/// exfiltration guard: the reference is resolved on the node and sent in cleartext in <c>A_LG</c> to a Host
/// the author chose, so it must never be able to name another subsystem's secret.
/// </summary>
public const string SecretNamespace = "heidenhain/";
public static readonly string SecretNamespace = DriverCredentialPolicy.HeidenhainScope.SecretNamespaces[0];
/// <summary>
/// The ONLY environment variables a Heidenhain password may name: <c>env:OTOPCUA_HEIDENHAIN_&lt;NAME&gt;</c>
/// (exact upper-case prefix; <c>NAME</c> is <c>[A-Z0-9_]+</c>) — never <c>ConnectionStrings__*</c>,
/// <c>ServerHistorian__ApiKey</c> or any other process variable.
/// </summary>
public const string EnvVariablePrefix = "OTOPCUA_HEIDENHAIN_";
public static readonly string EnvVariablePrefix = DriverCredentialPolicy.HeidenhainScope.EnvVariablePrefixes[0];
/// <summary>The password fields a Heidenhain DriverConfig/DeviceConfig may carry.</summary>
public static readonly IReadOnlyList<string> PasswordFields = ["InspectPassword", "DncPassword", "DataPassword"];
@@ -110,7 +111,7 @@ public static class HeidenhainOptionsParser
var errors = new List<string>();
if (o.TimeoutMs is < 100 or > 60000) errors.Add("TimeoutMs must be 100–60000 ms.");
var p = o.Polling;
foreach (var (name, v) in new[] { ("StatusMs", p.StatusMs), ("CustomMs", p.CustomMs), ("SlowMs", p.SlowMs) })
foreach (var (name, v) in new[] { ("StatusMs", p.StatusMs), ("CustomMs", p.CustomMs), ("SlowMs", p.SlowMs), ("AlarmMs", p.AlarmMs) })
if (v is < 100 or > 3_600_000) errors.Add($"Polling.{name} must be 100–3600000 ms.");
if (p.MaxAlarms is < 1 or > 256) errors.Add("Polling.MaxAlarms must be 1–256.");
var r = o.Reconnect;
@@ -164,105 +165,41 @@ public static class HeidenhainOptionsParser
/// <returns>True for blank or a namespaced reference.</returns>
public static bool TryParseCredentialReference(string? value, out CredentialKind kind, out string name)
{
kind = CredentialKind.None;
name = "";
if (string.IsNullOrEmpty(value)) return true;
if (value.StartsWith(SecretPrefix, StringComparison.Ordinal))
// The shared lmxopcua#815 parser — one rule for every driver that resolves credential references.
switch (CredentialReferences.Parse(value, DriverCredentialPolicy.HeidenhainScope, out name))
{
var secret = value[SecretPrefix.Length..];
if (!secret.StartsWith(SecretNamespace, StringComparison.Ordinal)) return false;
var rest = secret[SecretNamespace.Length..];
if (rest.Length is 0 or > 200) return false;
foreach (var c in rest)
if (!(char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.' or '/')) return false;
if (rest.Split('/').Any(seg => seg.Length == 0 || seg is "." or "..")) return false;
kind = CredentialKind.Secret;
name = secret;
return true;
}
if (value.StartsWith(EnvPrefix, StringComparison.Ordinal))
{
var variable = value[EnvPrefix.Length..];
if (!variable.StartsWith(EnvVariablePrefix, StringComparison.Ordinal)) return false;
var rest = variable[EnvVariablePrefix.Length..];
if (rest.Length is 0 or > 100 || !rest.All(c => char.IsAsciiLetterUpper(c) || char.IsAsciiDigit(c) || c == '_'))
case CredentialReferenceKind.Blank:
kind = CredentialKind.None;
return true;
case CredentialReferenceKind.Secret:
kind = CredentialKind.Secret;
return true;
case CredentialReferenceKind.Environment:
kind = CredentialKind.Environment;
return true;
default:
kind = CredentialKind.None;
name = "";
return false;
kind = CredentialKind.Environment;
name = variable;
return true;
}
return false;
}
/// <summary>
/// Scans a RAW DriverConfig or DeviceConfig document (before it is stored) for password fields that are not
/// namespaced references — at the top level (a device / merged config), under <c>Access</c>, and under every
/// <c>Devices[]</c> entry; keys matched case-insensitively, as the parser binds them. The messages name the
/// field, never the value. Unreadable JSON is reported, since it cannot be checked.
/// namespaced references — at any depth (top level, <c>Access</c>, <c>Devices[]</c>…); keys matched
/// case-insensitively, as the parser binds them. The messages name the field, never the value. Unreadable
/// JSON is reported, since it cannot be checked. Delegates to the shared <see cref="DriverCredentialPolicy"/>.
/// </summary>
/// <param name="json">The config JSON.</param>
/// <returns>The problems; empty when every password field is acceptable.</returns>
public static IReadOnlyList<string> DescribeCredentialProblems(string? json)
{
var problems = new List<string>();
if (string.IsNullOrWhiteSpace(json)) return problems;
JsonDocument doc;
try
{
doc = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
}
catch (JsonException)
{
problems.Add("Heidenhain config is not valid JSON, so its credential fields cannot be checked.");
return problems;
}
using (doc)
{
if (doc.RootElement.ValueKind != JsonValueKind.Object) return problems;
ScanObject(doc.RootElement, "", problems);
foreach (var p in doc.RootElement.EnumerateObject())
{
if (string.Equals(p.Name, "Access", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.Object)
ScanObject(p.Value, "Access.", problems);
if (string.Equals(p.Name, "Devices", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.Array)
{
var i = 0;
foreach (var d in p.Value.EnumerateArray())
{
if (d.ValueKind == JsonValueKind.Object) ScanObject(d, $"Devices[{i}].", problems);
i++;
}
}
}
}
return problems;
}
public static IReadOnlyList<string> DescribeCredentialProblems(string? json) =>
DriverCredentialPolicy.DescribeProblems(DriverTypeNames.Heidenhain, json);
/// <summary>The one wording of the credential rule (never includes the value).</summary>
/// <param name="field">The field.</param>
/// <returns>The message.</returns>
public static string CredentialRuleMessage(string field) =>
$"{field} must be blank, 'secret:{SecretNamespace}<name>' or 'env:{EnvVariablePrefix}<NAME>' — a literal "
+ "password, or a reference outside the Heidenhain namespace, is refused.";
private static void ScanObject(JsonElement obj, string prefix, List<string> problems)
{
foreach (var p in obj.EnumerateObject())
{
if (!PasswordFields.Any(f => string.Equals(f, p.Name, StringComparison.OrdinalIgnoreCase))) continue;
var ok = p.Value.ValueKind switch
{
JsonValueKind.Null => true,
JsonValueKind.String => IsCredentialReference(p.Value.GetString()),
_ => false,
};
if (!ok) problems.Add(CredentialRuleMessage(prefix + p.Name));
}
}
CredentialReferences.RuleMessage(field, DriverCredentialPolicy.HeidenhainScope, CredentialLiteralPolicy.Refused);
private static void CheckRef(List<string> errors, string field, string? value)
{
@@ -9,15 +9,30 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
/// <param name="Address">The parsed address.</param>
/// <param name="DataType">The OPC data type the driver publishes.</param>
/// <param name="IsArray">Whether the value is a 1-D array.</param>
/// <param name="Alarm">
/// The cross-driver <c>alarm</c> object, present exactly when <see cref="Address"/> is an <c>ALARM:</c> selector
/// (lmxopcua#831); the tag is then a Part 9 condition, never a value.
/// </param>
public sealed record HeidenhainTagDefinition(
string RawPath, string DeviceName, HeidenhainAddress Address, DriverDataType DataType, bool IsArray)
string RawPath, string DeviceName, HeidenhainAddress Address, DriverDataType DataType, bool IsArray,
HeidenhainTagAlarm? Alarm = null)
{
/// <summary>The poll cadence this tag rides.</summary>
public HeidenhainPollGroup Group => Address.Kind == HeidenhainAddressKind.Standard
? Address.Catalog!.Group
: HeidenhainPollGroup.Custom;
public HeidenhainPollGroup Group => Address.Kind switch
{
HeidenhainAddressKind.Standard => Address.Catalog!.Group,
HeidenhainAddressKind.Alarm => HeidenhainPollGroup.Alarm,
_ => HeidenhainPollGroup.Custom,
};
/// <summary>True for an <c>ALARM:</c> condition tag.</summary>
public bool IsAlarmCondition => Address.Kind == HeidenhainAddressKind.Alarm;
}
/// <summary>The driver's view of a tag's cross-driver <c>alarm</c> object.</summary>
/// <param name="Severity">The authored integer <c>alarm.severity</c>, or null when absent / not an integer.</param>
public sealed record HeidenhainTagAlarm(int? Severity);
/// <summary>
/// The single authority on a Heidenhain raw tag's <c>TagConfig</c>: consumed by the driver's table build,
/// the deploy-time gate (<see cref="Inspect"/>) and the AdminUI typed editor's <c>Validate()</c>, so the
@@ -29,6 +44,10 @@ public sealed record HeidenhainTagDefinition(
/// <c>{"address": "DATA:/TABLE/TOOL/T/1/DOC", "dataType": "String"}</c>. Array leaves
/// (<c>Axes/*</c>, <c>Alarms/Classes|Groups|Numbers|Messages</c>) must carry <c>"isArray": true</c> so the
/// node's rank matches what the driver publishes; every other address must not.</para>
/// <para><b>Alarm conditions</b> (lmxopcua#831): <c>{"address": "ALARM:CLASS=7", "dataType": "Boolean",
/// "alarm": {...}}</c>. An <c>ALARM:</c> address and the <c>alarm</c> object only work together — either alone is
/// refused (a condition nothing can raise, or a selector with no value to read). The data type is fixed at
/// <c>Boolean</c>.</para>
/// <para><b>Never a write flag.</b> There is no <c>writable</c> key: the driver is read-only and the deploy
/// gate refuses a ReadWrite access level on any Heidenhain tag.</para>
/// <para><b>Data types are parsed by NAME only.</b> A digits-only value (a numerically-serialized enum) is
@@ -59,6 +78,7 @@ public static class HeidenhainTagDefinitionFactory
string? dataTypeText;
bool dataTypePresent;
bool? isArray;
HeidenhainTagAlarm? alarm;
try
{
using var doc = JsonDocument.Parse(tagConfig);
@@ -95,6 +115,15 @@ public static class HeidenhainTagDefinitionFactory
}
}
alarm = null;
// Exact-case, exactly as the host's TagConfigIntent reads it: the condition exists iff the host sees it.
if (root.TryGetProperty("alarm", out var a) && a.ValueKind == JsonValueKind.Object)
{
int? severity = a.TryGetProperty("severity", out var sev) && sev.ValueKind == JsonValueKind.Number
&& sev.TryGetInt32(out var sv) ? sv : null;
alarm = new HeidenhainTagAlarm(severity);
}
if (TryGetProperty(root, "writable", out var w) && w.ValueKind == JsonValueKind.True)
{
error = "Heidenhain tags are read-only; remove \"writable\": true.";
@@ -121,9 +150,34 @@ public static class HeidenhainTagDefinitionFactory
declared = parsed;
}
if (address.Kind == HeidenhainAddressKind.Alarm && alarm is null)
{
error = $"'{address.Text}' is an alarm selector — enable the tag's native alarm (the 'alarm' object); " +
"an ALARM: tag is a Part 9 condition and has no value to read.";
return false;
}
if (address.Kind != HeidenhainAddressKind.Alarm && alarm is not null)
{
error = $"The tag carries an 'alarm' object but '{address.Text}' is not an ALARM: selector — nothing could " +
"ever raise the condition. Use ALARM:*, ALARM:OTHER or ALARM:CLASS=<n>[/GROUP=<n>][/NUMBER=<n>|<lo>..<hi>].";
return false;
}
DriverDataType type;
bool array;
if (address.Kind == HeidenhainAddressKind.Standard)
if (address.Kind == HeidenhainAddressKind.Alarm)
{
if (declared is { } d && d != AlarmConditionDataType)
{
error = $"An ALARM: condition tag is {AlarmConditionDataType}; dataType {d} does not match.";
return false;
}
type = AlarmConditionDataType;
array = false;
}
else if (address.Kind == HeidenhainAddressKind.Standard)
{
var entry = address.Catalog!;
if (declared is { } d && d != entry.DataType)
@@ -172,10 +226,13 @@ public static class HeidenhainTagDefinitionFactory
return false;
}
definition = new HeidenhainTagDefinition(rawPath, deviceName, address, type, array);
definition = new HeidenhainTagDefinition(rawPath, deviceName, address, type, array, alarm);
return true;
}
/// <summary>The fixed <c>Tag.DataType</c> of an <c>ALARM:</c> condition tag (active / inactive).</summary>
public const DriverDataType AlarmConditionDataType = DriverDataType.Boolean;
/// <summary>
/// Deploy-time inspection: empty when <see cref="TryFromTagConfig"/> accepts the blob (never stricter),
/// otherwise one warning explaining the rejection. Never throws.
@@ -0,0 +1,287 @@
using System.Text;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Lsv2;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
/// <summary>An authored <c>ALARM:</c> raw tag the driver drives a Part 9 condition for.</summary>
/// <param name="RawPath">The tag's RawPath — the ConditionId, the only key the host routes on.</param>
/// <param name="HostName">The control (<c>host:port</c>) whose alarm list the tag selects from.</param>
/// <param name="Selector">Which alarms on that control drive the condition.</param>
/// <param name="AuthoredSeverity">The authored <c>alarm.severity</c>, or null.</param>
internal sealed record HeidenhainAlarmTag(string RawPath, string HostName, HeidenhainAlarmSelector Selector, int? AuthoredSeverity);
/// <summary>
/// A controller alarm's identity: class, group, number AND text. The number alone is not an identity — a real
/// iTNC 530 reports <c>-1</c> for (at least) "Run test of cutout channels" — so two different texts under one
/// number are two alarms.
/// </summary>
internal readonly record struct HeidenhainAlarmKey(int Class, int Group, int Number, string Message)
{
public static HeidenhainAlarmKey Of(Lsv2Alarm a) => new(a.ErrorClass, a.Group, a.Number, (a.Message ?? "").Trim());
}
/// <summary>What one condition last told the server — the diff baseline (re-subscribe / reconnect never re-raise).</summary>
internal sealed record HeidenhainToldCondition(
bool Active,
IReadOnlySet<HeidenhainAlarmKey> Keys,
HeidenhainAlarmKey? Winner,
string Message,
AlarmSeverity Severity,
int? OpcUaSeverity);
/// <summary>
/// Pure selection + transition rules for Heidenhain alarm conditions (lmxopcua#831) — the FOCAS #647 semantics
/// applied to the LSV2 alarm list.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><b>Overlap is intended</b>: one alarm drives every selector that matches it (<c>*</c> and
/// <c>CLASS=7</c>). <c>OTHER</c> is what no FILTER selector on the same control claims.</item>
/// <item><b>Displayed alarm is deterministic</b> — ascending (class, group, number, text), never wire order,
/// so a reordered unchanged list cannot re-raise.</item>
/// <item><b>Transitions</b>: inactive → active = <c>Raise</c>; a key not in the told set appears, or the
/// displayed alarm leaves while others remain = <c>Retrigger</c> (un-acknowledges: a statement the operator
/// has not seen); a non-displayed member leaves = nothing; nothing matches = <c>Clear</c>.</item>
/// <item><b>Severity</b>: an authored integer <c>alarm.severity</c> is sent exactly (<c>OpcUaSeverity</c>);
/// otherwise the bucket is High and no exact value is sent. Class semantics are undocumented, so no
/// class→severity table is invented.</item>
/// </list>
/// </remarks>
internal static class HeidenhainAlarmRules
{
/// <summary>The <see cref="AlarmEventArgs.AlarmType"/> every Heidenhain condition event carries.</summary>
public const string AlarmType = "HeidenhainAlarm";
/// <summary>The alarms one condition matches, in display order (distinct by key).</summary>
public static IReadOnlyList<HeidenhainAlarmKey> Evaluate(
HeidenhainAlarmSelector selector, IReadOnlyList<Lsv2Alarm> alarms, IReadOnlyCollection<HeidenhainAlarmSelector> deviceSelectors)
{
var filters = selector.Kind == HeidenhainAlarmSelectorKind.Other
? deviceSelectors.Where(s => s.Kind == HeidenhainAlarmSelectorKind.Filter).ToList()
: null;
return alarms
.Where(a => filters is null
? selector.Matches(a.ErrorClass, a.Group, a.Number)
: !filters.Any(f => f.Matches(a.ErrorClass, a.Group, a.Number)))
.Select(HeidenhainAlarmKey.Of)
.Distinct()
.OrderBy(k => k.Class).ThenBy(k => k.Group).ThenBy(k => k.Number)
.ThenBy(k => k.Message, StringComparer.Ordinal)
.ToList();
}
/// <summary>The event moving the server from <paramref name="told"/> to <paramref name="matched"/>, and the new record.</summary>
public static (AlarmEventArgs? Event, HeidenhainToldCondition Told) Transition(
HeidenhainToldCondition? told, IReadOnlyList<HeidenhainAlarmKey> matched, HeidenhainAlarmTag tag,
IAlarmSubscriptionHandle handle, DateTime nowUtc)
{
var keys = matched.ToHashSet();
if (matched.Count == 0)
{
if (told is not { Active: true })
return (null, told ?? new HeidenhainToldCondition(false, keys, null, "", AlarmSeverity.Low, null));
return (Build(tag, handle, nowUtc, AlarmTransitionKind.Clear, $"Cleared: {told.Message}", told.Severity, told.OpcUaSeverity),
told with { Active = false, Keys = keys, Winner = null });
}
var winner = matched[0];
var (bucket, exact) = tag.AuthoredSeverity is { } s ? (BucketOf(s), (int?)s) : (AlarmSeverity.High, null);
var message = MessageOf(matched);
var raised = new HeidenhainToldCondition(true, keys, winner, message, bucket, exact);
if (told is not { Active: true })
return (Build(tag, handle, nowUtc, AlarmTransitionKind.Raise, message, bucket, exact), raised);
if (keys.Any(k => !told.Keys.Contains(k)) || told.Winner != winner)
return (Build(tag, handle, nowUtc, AlarmTransitionKind.Retrigger, message, bucket, exact), raised);
return (null, told with { Keys = keys });
}
/// <summary>The nearest bucket of an exact 1..1000 severity.</summary>
public static AlarmSeverity BucketOf(int severity) => severity switch
{
< 400 => AlarmSeverity.Low,
< 600 => AlarmSeverity.Medium,
< 800 => AlarmSeverity.High,
_ => AlarmSeverity.Critical,
};
/// <summary><c>-1 Run test of cutout channels (class 7, group 4) [+2 more]</c>.</summary>
public static string MessageOf(IReadOnlyList<HeidenhainAlarmKey> matched)
{
var w = matched[0];
var b = new StringBuilder();
b.Append(w.Number);
if (w.Message.Length > 0) b.Append(' ').Append(w.Message);
b.Append(" (class ").Append(w.Class).Append(", group ").Append(w.Group).Append(')');
if (matched.Count > 1) b.Append(" [+").Append(matched.Count - 1).Append(" more]");
return b.ToString();
}
public static AlarmEventArgs Build(HeidenhainAlarmTag tag, IAlarmSubscriptionHandle handle, DateTime nowUtc,
AlarmTransitionKind kind, string message, AlarmSeverity bucket, int? exact, uint? quality = null) =>
new(handle,
SourceNodeId: tag.HostName,
ConditionId: tag.RawPath,
AlarmType: AlarmType,
Message: message,
Severity: bucket,
SourceTimestampUtc: nowUtc,
Kind: kind,
OpcUaSeverity: exact,
QualityStatusCode: quality);
}
/// <summary>
/// Drives one Part 9 condition per subscribed <c>ALARM:</c> raw tag from the alarm walks the device loops already
/// perform (lmxopcua#831). There is NO extra connection and NO extra request type: the walk is the same
/// allowlisted <c>R_RI 27/28</c> the <c>Alarms/*</c> arrays use, issued by the control's single acquisition loop on
/// the <c>Polling.AlarmMs</c> cadence.
/// </summary>
/// <remarks>
/// <para><b>Lives as long as the driver</b> (not re-created on re-initialise), so the told record survives a
/// reconnect, a same-set re-subscribe and an in-place re-init — re-raising there would un-acknowledge. A changed
/// subscribed set prunes only the RawPaths that left it.</para>
/// <para><b>A failed walk is not "no alarms".</b> A refusal, a list overflow, a decode error or comms loss keeps
/// every condition's Active/Acked state and annotates its quality once (quality-only event, no <c>/alerts</c>
/// row); the next good walk lifts it to Good before diffing. Only a down session degrades driver health (the
/// runtime's rule) — a refusal never does, or the #527 watchdog would reconnect-loop a production control.</para>
/// <para><b>Read-only acknowledgement.</b> LSV2 has no acknowledge request in the allowlist, and none is added:
/// <see cref="HeidenhainDriver.AcknowledgeAsync"/> is the no-op success the host routes a Part 9 Acknowledge to
/// (the FOCAS / MTConnect posture) — the ack is applied server-side only; the control clears an alarm when its
/// cause is reset. Confirm / shelve / enable are refused by the host for every native condition.</para>
/// <para>Recorded only while a handler is attached (the host detaches while it reconnects), so the re-subscribe
/// that follows still sees the difference. Delivery runs under <see cref="_lock"/>; the only production handler
/// is <c>DriverInstanceActor</c>'s non-blocking <c>Tell</c>.</para>
/// </remarks>
internal sealed class HeidenhainAlarmProjection(object sender, Func<EventHandler<AlarmEventArgs>?> handlers, ILogger logger)
{
private readonly Lock _lock = new();
private readonly Dictionary<string, HeidenhainToldCondition> _told = new(StringComparer.Ordinal);
private readonly Dictionary<string, uint> _qualityTold = new(StringComparer.Ordinal);
private readonly Dictionary<string, uint> _failing = new(StringComparer.Ordinal);
private IReadOnlyDictionary<string, HeidenhainAlarmTag> _tags = new Dictionary<string, HeidenhainAlarmTag>();
private Subscription? _current;
private long _nextId;
/// <summary>The authored alarm tags (RawPath → tag). Swapped whole on every table build.</summary>
public IReadOnlyDictionary<string, HeidenhainAlarmTag> Tags
{
get => Volatile.Read(ref _tags);
set => Volatile.Write(ref _tags, value);
}
/// <summary>The live subscription (test seam).</summary>
internal Subscription? Current => Volatile.Read(ref _current);
public IAlarmSubscriptionHandle Subscribe(IReadOnlyList<string> sourceNodeIds)
{
ArgumentNullException.ThrowIfNull(sourceNodeIds);
var refs = sourceNodeIds.Where(r => !string.IsNullOrWhiteSpace(r)).ToHashSet(StringComparer.Ordinal);
var sub = new Subscription(new HeidenhainAlarmSubscriptionHandle(Interlocked.Increment(ref _nextId)), refs);
lock (_lock)
{
foreach (var gone in _told.Keys.Where(k => !refs.Contains(k)).ToList()) _told.Remove(gone);
// A (re)subscribe follows a host-side reconnect, where the host re-annotates its conditions; forget which
// ones this projection marked, so a still-failing control re-asserts its quality on the next walk.
_qualityTold.Clear();
Volatile.Write(ref _current, sub);
}
return sub.Handle;
}
public void Unsubscribe(IAlarmSubscriptionHandle handle)
{
lock (_lock)
{
if (Volatile.Read(ref _current) is { } live && ReferenceEquals(live.Handle, handle)) Volatile.Write(ref _current, null);
}
}
/// <summary>One alarm-walk outcome of <paramref name="hostName"/> (Good + list, or a non-Good status).</summary>
public void OnWalk(string hostName, uint status, IReadOnlyList<Lsv2Alarm>? alarms)
{
var now = DateTime.UtcNow;
var tags = Tags;
lock (_lock)
{
if (Volatile.Read(ref _current) is not { } sub) return;
var deviceTags = tags.Values.Where(t => t.HostName == hostName).ToList();
var subscribed = deviceTags.Where(t => sub.References.Contains(t.RawPath)).ToList();
if (subscribed.Count == 0) return;
if (status != HeidenhainStatus.Good || alarms is null)
{
if (!_failing.TryGetValue(hostName, out var was) || was != status)
{
_failing[hostName] = status;
logger.LogWarning(
"Heidenhain {Host}: alarm list unavailable ({Status}); its {Count} alarm condition(s) keep their state and are marked with that quality",
hostName, HeidenhainStatus.State(status), subscribed.Count);
}
}
else if (_failing.Remove(hostName))
{
logger.LogInformation("Heidenhain {Host}: alarm list readable again", hostName);
}
var h = handlers();
if (h is null) return; // nobody listening: record nothing, the re-subscribe diffs again
if (status != HeidenhainStatus.Good || alarms is null)
{
foreach (var tag in subscribed)
{
if (_qualityTold.TryGetValue(tag.RawPath, out var q) && q == status) continue;
_qualityTold[tag.RawPath] = status;
Deliver(h, QualityOnly(tag, sub.Handle, status, now));
}
return;
}
var selectors = deviceTags.Select(t => t.Selector).ToList();
foreach (var tag in subscribed)
{
// Lift a non-Good this projection put there BEFORE the diff, so recovery + a change reads Good then the transition.
if (_qualityTold.Remove(tag.RawPath)) Deliver(h, QualityOnly(tag, sub.Handle, HeidenhainStatus.Good, now));
_told.TryGetValue(tag.RawPath, out var told);
var (evt, nowTold) = HeidenhainAlarmRules.Transition(
told, HeidenhainAlarmRules.Evaluate(tag.Selector, alarms, selectors), tag, sub.Handle, now);
_told[tag.RawPath] = nowTold;
if (evt is not null) Deliver(h, evt);
}
}
}
private AlarmEventArgs QualityOnly(HeidenhainAlarmTag tag, IAlarmSubscriptionHandle handle, uint quality, DateTime now)
{
_told.TryGetValue(tag.RawPath, out var told);
return HeidenhainAlarmRules.Build(tag, handle, now, AlarmTransitionKind.Unspecified, told?.Message ?? "",
told?.Severity ?? AlarmSeverity.Low, told?.OpcUaSeverity, quality);
}
private void Deliver(EventHandler<AlarmEventArgs> h, AlarmEventArgs evt)
{
foreach (var registration in h.GetInvocationList())
{
try { ((EventHandler<AlarmEventArgs>)registration).Invoke(sender, evt); }
catch (Exception ex)
{
logger.LogWarning(ex, "Heidenhain alarm subscriber threw for {ConditionId}; delivery continues", evt.ConditionId);
}
}
}
/// <summary>The live subscription: its handle and the ConditionIds (RawPaths) it names.</summary>
internal sealed record Subscription(HeidenhainAlarmSubscriptionHandle Handle, IReadOnlySet<string> References);
}
/// <summary>Handle returned by <see cref="HeidenhainDriver.SubscribeAlarmsAsync"/>.</summary>
/// <param name="Id">The driver-local subscription number.</param>
public sealed record HeidenhainAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle
{
/// <inheritdoc />
public string DiagnosticId => $"heidenhain-alarm-sub-{Id}";
}
@@ -1,3 +1,4 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
@@ -31,26 +32,23 @@ internal sealed class HeidenhainCredentials(ISecretResolver? resolver, Func<stri
return await ResolveReferenceAsync(reference, role, ct).ConfigureAwait(false);
}
/// <summary>Resolves one reference.</summary>
/// <summary>Resolves one reference through the shared lmxopcua#815 resolver (scope re-checked before any read).</summary>
public async ValueTask<string> ResolveReferenceAsync(string? reference, string role, CancellationToken ct)
{
if (!HeidenhainOptionsParser.TryParseCredentialReference(reference, out var kind, out var name))
throw new HeidenhainCredentialException(HeidenhainOptionsParser.CredentialRuleMessage($"{role} password") + " (fail-closed)");
switch (kind)
try
{
case HeidenhainOptionsParser.CredentialKind.None:
return "";
case HeidenhainOptionsParser.CredentialKind.Environment:
return _environment(name) is { Length: > 0 } value
? value
: throw new HeidenhainCredentialException($"{role} password environment variable '{name}' is not set (fail-closed).");
default:
if (resolver is null)
throw new HeidenhainCredentialException($"{role} password references secret '{name}' but no secret store is available (fail-closed).");
var resolved = await resolver.GetAsync(new SecretName(name), ct).ConfigureAwait(false);
return !string.IsNullOrEmpty(resolved)
? resolved
: throw new HeidenhainCredentialException($"{role} password secret '{name}' is absent from the store (fail-closed).");
return await CredentialReferences.ResolveAsync(
reference,
DriverCredentialPolicy.HeidenhainScope,
$"{role} password",
CredentialLiteralPolicy.Refused,
resolver is null ? null : async (name, c) => await resolver.GetAsync(new SecretName(name), c).ConfigureAwait(false),
_environment,
ct).ConfigureAwait(false);
}
catch (CredentialReferenceException ex)
{
throw new HeidenhainCredentialException(ex.Message);
}
}
}
@@ -26,6 +26,15 @@ public enum HeidenhainConnectionState
/// <summary>Builds the client for an endpoint (test seam).</summary>
internal delegate Lsv2Client Lsv2ClientFactory(string host, int port, TimeSpan timeout);
/// <summary>
/// The alarm-walk outcome for a control's <c>ALARM:</c> conditions (lmxopcua#831): <paramref name="status"/> Good
/// with the complete list, or a non-Good status (refusal, overflow, comms loss) with <c>null</c> — never "no alarms".
/// </summary>
internal delegate void HeidenhainAlarmSink(HeidenhainDeviceRuntime runtime, uint status, IReadOnlyList<Lsv2Alarm>? alarms);
/// <summary>A session's controller identity, reported once per established session (lmxopcua#831 rediscovery).</summary>
internal delegate void HeidenhainIdentitySink(HeidenhainDeviceRuntime runtime, Lsv2Versions identity);
/// <summary>
/// One controller's acquisition engine: a single background loop owns the session, so every LSV2 transaction
/// for the device is serialized. The loop connects, polls the three cadence groups, publishes into the cache
@@ -54,6 +63,9 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
private readonly Lsv2ClientFactory _clientFactory;
private readonly TimeProvider _time;
private readonly ILogger _logger;
private readonly HeidenhainAlarmSink? _alarms;
private readonly HeidenhainIdentitySink? _identity;
private readonly IReadOnlyList<HeidenhainTagDefinition> _alarmTags;
private readonly object _publication = new();
private readonly object _lifecycle = new();
private readonly Dictionary<HeidenhainPollGroup, bool> _groupGood = new();
@@ -81,7 +93,9 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
Action<HeidenhainDeviceRuntime, HeidenhainConnectionState, HeidenhainConnectionState> stateChanged,
Lsv2ClientFactory clientFactory,
TimeProvider time,
ILogger logger)
ILogger logger,
HeidenhainAlarmSink? alarms = null,
HeidenhainIdentitySink? identity = null)
{
_device = device;
_options = HeidenhainOptionsParser.Normalize(options);
@@ -92,6 +106,9 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
_clientFactory = clientFactory;
_time = time;
_logger = logger;
_alarms = alarms;
_identity = identity;
_alarmTags = tags.Where(t => t.IsAlarmCondition).ToList();
_stateChangedUtc = time.GetUtcNow().UtcDateTime;
_groups = tags.GroupBy(t => t.Group).ToDictionary(g => g.Key, g => (IReadOnlyList<HeidenhainTagDefinition>)g.ToList());
}
@@ -220,6 +237,12 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
SetState(HeidenhainConnectionState.Connected, null);
_logger.LogInformation("Heidenhain {Host} connected ({Model})", HostName, session.Identity?.Model);
if (session.Identity is { } identity && _identity is not null)
{
try { _identity(this, identity); }
catch (Exception ex) { _logger.LogWarning(ex, "Heidenhain {Host} identity handler threw", HostName); }
}
await PollAsync(session, generation, ct).ConfigureAwait(false);
// Poll returns only on session loss.
Retire(generation, "LSV2 communication lost");
@@ -254,6 +277,7 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
[HeidenhainPollGroup.Status] = TimeSpan.FromMilliseconds(Math.Max(100, _options.Polling.StatusMs)),
[HeidenhainPollGroup.Custom] = TimeSpan.FromMilliseconds(Math.Max(100, _options.Polling.CustomMs)),
[HeidenhainPollGroup.Slow] = TimeSpan.FromMilliseconds(Math.Max(100, _options.Polling.SlowMs)),
[HeidenhainPollGroup.Alarm] = TimeSpan.FromMilliseconds(Math.Max(100, _options.Polling.AlarmMs)),
};
var start = _time.GetTimestamp();
var due = _groups.Keys.ToDictionary(g => g, _ => TimeSpan.Zero);
@@ -267,7 +291,7 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
while (!ct.IsCancellationRequested)
{
var elapsed = _time.GetElapsedTime(start);
foreach (var group in new[] { HeidenhainPollGroup.Status, HeidenhainPollGroup.Custom, HeidenhainPollGroup.Slow })
foreach (var group in new[] { HeidenhainPollGroup.Status, HeidenhainPollGroup.Alarm, HeidenhainPollGroup.Custom, HeidenhainPollGroup.Slow })
{
if (!due.TryGetValue(group, out var at) || at > elapsed) continue;
var tags = _groups[group];
@@ -291,9 +315,19 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
if (generation != _generation || !ReferenceEquals(_session, session)) return false;
if (session.CommunicationLost) return false;
var good = true;
var alarmsDelivered = false;
for (var i = 0; i < tags.Count; i++)
{
var s = samples[i];
if (tags[i].IsAlarmCondition)
{
// One alarm walk per batch serves every ALARM: condition of this control (they share the outcome).
if (!alarmsDelivered) DeliverAlarms(s.Status, s.Status == HeidenhainStatus.Good ? s.Value as IReadOnlyList<Lsv2Alarm> : null);
alarmsDelivered = true;
if (s.Status != HeidenhainStatus.Good) good = false;
continue;
}
_publish(tags[i].RawPath, new DataValueSnapshot(s.Value, s.Status, now, now));
if (tags[i].Address.Catalog?.IsCapability == true) continue;
// Explicitly disabled optional timers are not partial data.
@@ -341,14 +375,25 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
private void Invalidate(DateTime now)
{
if (_alarmTags.Count > 0) DeliverAlarms(HeidenhainStatus.BadNoCommunication, null);
foreach (var tag in _tags)
{
if (tag.IsAlarmCondition) continue;
_publish(tag.RawPath, tag.Address.Catalog?.IsCapability == true
? new DataValueSnapshot(HeidenhainCatalog.States.CommunicationLost, HeidenhainStatus.Good, now, now)
: new DataValueSnapshot(null, HeidenhainStatus.BadNoCommunication, now, now));
}
}
/// <summary>Hands an alarm-walk outcome to the projection. Called under <see cref="_publication"/> (ordered with the generation).</summary>
private void DeliverAlarms(uint status, IReadOnlyList<Lsv2Alarm>? alarms)
{
if (_alarms is null) return;
if (status == HeidenhainStatus.Good && alarms is null) status = HeidenhainStatus.BadDecodingError;
try { _alarms(this, status, status == HeidenhainStatus.Good ? alarms : null); }
catch (Exception ex) { _logger.LogWarning(ex, "Heidenhain {Host} alarm projection threw", HostName); }
}
private void SetState(HeidenhainConnectionState next, string? error)
{
HeidenhainConnectionState old;
@@ -30,7 +30,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
/// dedup (subscriptions dedup on value AND status).</para>
/// </remarks>
public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDiscovery, IHostConnectivityProbe,
IPerCallHostResolver, ISkippedTagReporter, IDriverDiagnostics, IAsyncDisposable
IPerCallHostResolver, ISkippedTagReporter, IDriverDiagnostics, IAlarmSource, IRediscoverable, IAsyncDisposable
{
/// <summary>Most custom (PLC/DATA) bindings one control may carry (reference limit).</summary>
public const int MaxCustomBindingsPerDevice = 256;
@@ -45,6 +45,18 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
private readonly object _publishLock = new();
private readonly ConcurrentDictionary<string, DataValueSnapshot> _cache = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<long, Subscription> _subscriptions = new();
/// <summary>
/// The <c>ALARM:</c> condition projection (lmxopcua#831). Lives as long as the driver — NOT re-created per
/// initialise — so its told record survives a reconnect and an in-place re-init (re-raising would un-ack).
/// </summary>
private readonly HeidenhainAlarmProjection _alarms;
/// <summary>
/// Last controller identity seen per control (<c>host:port</c>). Driver-lifetime, so a re-initialise does not
/// forget the baseline; an identity that differs on a later session raises <see cref="OnRediscoveryNeeded"/>.
/// </summary>
private readonly ConcurrentDictionary<string, Lsv2Versions> _identities = new(StringComparer.Ordinal);
private HeidenhainDriverOptions _options;
private IReadOnlyDictionary<string, HeidenhainDeviceRuntime> _byRawPath = new Dictionary<string, HeidenhainDeviceRuntime>();
private IReadOnlyList<HeidenhainDeviceRuntime> _devices = [];
@@ -75,6 +87,7 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
_credentials = credentials;
_clientFactory = clientFactory ?? ((h, p, t) => new Lsv2Client(h, p, t));
_time = time ?? TimeProvider.System;
_alarms = new HeidenhainAlarmProjection(this, () => OnAlarmEvent, _logger);
}
/// <inheritdoc />
@@ -89,6 +102,19 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
/// <inheritdoc />
public event EventHandler<HostStatusChangedEventArgs>? OnHostStatusChanged;
/// <inheritdoc />
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
/// <inheritdoc />
/// <remarks>
/// Raised (advisory — the host shows a "re-browse" chip; nothing is re-materialised) when a control reconnects
/// reporting a different identity (<c>R_VR</c>: model, NC/PLC software version or option string) than the
/// previous session — a software update or option install can change what the control serves (selectors,
/// PLC layout). The first session of a control only records the baseline. No extra traffic: the identity is
/// the <c>R_VR</c> every session already reads at connect.
/// </remarks>
public event EventHandler<RediscoveryEventArgs>? OnRediscoveryNeeded;
/// <summary>Parses + validates a config document (the one authority the factory and the driver share).</summary>
/// <param name="driverConfigJson">The config JSON.</param>
/// <returns>The options.</returns>
@@ -138,6 +164,7 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
var devices = _options.Devices ?? [];
_skipped.BeginRebuild(_options.RawTags.Count);
var perDevice = new Dictionary<HeidenhainDeviceOptions, List<HeidenhainTagDefinition>>();
var alarmTags = new Dictionary<string, HeidenhainAlarmTag>(StringComparer.Ordinal);
foreach (var d in devices) perDevice[d] = [];
foreach (var raw in _options.RawTags)
@@ -156,8 +183,8 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
}
var list = perDevice[device];
if (def.Address.Kind != HeidenhainAddressKind.Standard
&& list.Count(t => t.Address.Kind != HeidenhainAddressKind.Standard) >= MaxCustomBindingsPerDevice)
if (def.Address.Kind is HeidenhainAddressKind.Plc or HeidenhainAddressKind.DataPath
&& list.Count(t => t.Address.Kind is HeidenhainAddressKind.Plc or HeidenhainAddressKind.DataPath) >= MaxCustomBindingsPerDevice)
{
_skipped.Skip(raw.RawPath, $"more than {MaxCustomBindingsPerDevice} PLC/DATA bindings on one control");
continue;
@@ -187,17 +214,27 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
var runtime = new HeidenhainDeviceRuntime(
dev, _options, tags,
(role, ct) => _credentials.ResolveAsync(_options, dev, role, ct),
Publish, OnRuntimeState, _clientFactory, _time, _logger);
Publish, OnRuntimeState, _clientFactory, _time, _logger,
(r, status, alarms) => _alarms.OnWalk(r.HostName, status, alarms),
OnIdentity);
runtimes.Add(runtime);
foreach (var t in tags)
{
byPath[t.RawPath] = runtime;
if (t.IsAlarmCondition)
{
// A condition, never a value: it never enters the value cache or a data subscription.
alarmTags[t.RawPath] = new HeidenhainAlarmTag(t.RawPath, runtime.HostName, t.Address.AlarmSelector!, t.Alarm?.Severity);
continue;
}
_cache[t.RawPath] = new DataValueSnapshot(null, HeidenhainStatus.BadWaitingForInitialData, null, now);
}
}
_devices = runtimes;
_byRawPath = byPath;
_alarms.Tags = alarmTags;
}
private static HeidenhainDeviceOptions? Route(IEnumerable<HeidenhainDeviceOptions> devices, string deviceName)
@@ -270,7 +307,7 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
for (var i = 0; i < fullReferences.Count; i++)
result[i] = _cache.TryGetValue(fullReferences[i], out var s)
? s
: new DataValueSnapshot(null, HeidenhainStatus.BadNodeIdUnknown, null, now);
: new DataValueSnapshot(null, Unknown(fullReferences[i]), null, now);
return Task.FromResult<IReadOnlyList<DataValueSnapshot>>(result);
}
@@ -288,7 +325,7 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
var now = _time.GetUtcNow().UtcDateTime;
foreach (var r in sub.References)
{
var snapshot = _cache.TryGetValue(r, out var s) ? s : new DataValueSnapshot(null, HeidenhainStatus.BadNodeIdUnknown, null, now);
var snapshot = _cache.TryGetValue(r, out var s) ? s : new DataValueSnapshot(null, Unknown(r), null, now);
Raise(sub, r, snapshot);
}
}
@@ -297,6 +334,10 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
return Task.FromResult<ISubscriptionHandle>(sub);
}
/// <summary>Status for a reference with no cached value: an <c>ALARM:</c> condition has no value to read.</summary>
private uint Unknown(string reference) =>
_alarms.Tags.ContainsKey(reference) ? HeidenhainStatus.BadNotSupported : HeidenhainStatus.BadNodeIdUnknown;
/// <inheritdoc />
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken)
{
@@ -411,6 +452,60 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
return Task.CompletedTask;
}
// ---- IAlarmSource (lmxopcua#831) ----
/// <inheritdoc />
/// <remarks>
/// <paramref name="sourceNodeIds"/> are the RawPaths of the alarm-bearing raw tags (the host's alarm set).
/// Collapses to ONE live subscription (the owning actor re-subscribes on every Connected entry). Starts the
/// control loops when nothing else had (an alarm-only driver); the first walk follows within
/// <c>Polling.AlarmMs</c>.
/// </remarks>
public Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(IReadOnlyList<string> sourceNodeIds, CancellationToken cancellationToken)
{
var handle = _alarms.Subscribe(sourceNodeIds);
EnsureStarted();
return Task.FromResult(handle);
}
/// <inheritdoc />
public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(handle);
_alarms.Unsubscribe(handle);
return Task.CompletedTask;
}
/// <inheritdoc />
/// <remarks>
/// <b>Local-only.</b> LSV2 has no acknowledge request, and the read-only allowlist (<see cref="Lsv2ReadOnlyPolicy"/>)
/// is deliberately NOT widened for one: nothing is sent to the control. This is the no-op success the host routes
/// a Part 9 Acknowledge / AddComment to, so the ack is applied (and replicated) server-side — the FOCAS and
/// MTConnect posture. The control clears an alarm itself when its cause is reset.
/// </remarks>
public Task AcknowledgeAsync(IReadOnlyList<AlarmAcknowledgeRequest> acknowledgements, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(acknowledgements);
return Task.CompletedTask;
}
/// <summary>The alarm projection (test seam).</summary>
internal HeidenhainAlarmProjection AlarmProjection => _alarms;
private void OnIdentity(HeidenhainDeviceRuntime runtime, Lsv2Versions identity)
{
var previous = _identities.GetValueOrDefault(runtime.HostName);
_identities[runtime.HostName] = identity;
if (previous is null || previous == identity) return;
var reason = $"Heidenhain control {runtime.HostName} reconnected with a different identity " +
$"({Describe(previous)} → {Describe(identity)}); re-browse the device and review its tags.";
_logger.LogWarning("{Reason}", reason);
try { OnRediscoveryNeeded?.Invoke(this, new RediscoveryEventArgs(reason, null)); }
catch (Exception ex) { _logger.LogWarning(ex, "Heidenhain rediscovery handler threw"); }
static string Describe(Lsv2Versions v) => $"{v.Model} NC {v.Nc} PLC {v.Plc} options '{v.Options}'";
}
/// <inheritdoc />
public async ValueTask DisposeAsync() => await ShutdownAsync(CancellationToken.None).ConfigureAwait(false);
@@ -187,9 +187,20 @@ internal sealed class HeidenhainSession : IAsyncDisposable
return result;
}
private static string OutcomeKey(HeidenhainTagDefinition tag) => tag.Address.Kind == HeidenhainAddressKind.Standard
? tag.Address.Catalog!.Feature
: "Custom|" + tag.Address.Text + "|" + tag.DataType;
private static string OutcomeKey(HeidenhainTagDefinition tag) => tag.Address.Kind switch
{
HeidenhainAddressKind.Standard => tag.Address.Catalog!.Feature,
HeidenhainAddressKind.Alarm => HeidenhainCatalog.AlarmsFeature,
_ => "Custom|" + tag.Address.Text + "|" + tag.DataType,
};
/// <summary>True for a PLC/DATA binding (as opposed to a catalog feature or the alarm walk).</summary>
private static bool IsCustom(HeidenhainTagDefinition tag) =>
tag.Address.Kind is HeidenhainAddressKind.Plc or HeidenhainAddressKind.DataPath;
/// <summary>The catalog feature a non-custom tag is acquired through.</summary>
private static string FeatureOf(HeidenhainTagDefinition tag) =>
tag.Address.Kind == HeidenhainAddressKind.Alarm ? HeidenhainCatalog.AlarmsFeature : tag.Address.Catalog!.Feature;
/// <summary>The current capability string for a feature.</summary>
public string Capability(string feature)
@@ -223,8 +234,8 @@ internal sealed class HeidenhainSession : IAsyncDisposable
private async Task<Outcome> AcquireAsync(HeidenhainTagDefinition tag, Dictionary<string, Raw> wire, CancellationToken ct)
{
if (_closed || CommunicationLost) return new Outcome(null, HeidenhainStatus.BadNoCommunication);
var isCustom = tag.Address.Kind != HeidenhainAddressKind.Standard;
var feature = isCustom ? tag.Address.Text : tag.Address.Catalog!.Feature;
var isCustom = IsCustom(tag);
var feature = isCustom ? tag.Address.Text : FeatureOf(tag);
var suppressKey = isCustom ? "Custom|" + tag.Address.Text : feature;
if (_suppressed.TryGetValue(suppressKey, out var suppressedStatus)) return new Outcome(null, suppressedStatus);
try
@@ -251,7 +262,7 @@ internal sealed class HeidenhainSession : IAsyncDisposable
"Overrides" => Lsv2Data.Overrides(await _client.ReadRuntimeAsync(25, ct).ConfigureAwait(false)),
"Axes" => Lsv2Data.Axes(await _client.ReadRuntimeAsync(22, ct).ConfigureAwait(false)),
"Tool" => Lsv2Data.Tool(await _client.ReadRuntimeAsync(51, ct).ConfigureAwait(false)),
"Alarms" => await AlarmsAsync(ct).ConfigureAwait(false),
HeidenhainCatalog.AlarmsFeature => await AlarmsAsync(ct).ConfigureAwait(false),
_ => await TimerAsync(feature, ct).ConfigureAwait(false),
};
}
@@ -419,6 +430,8 @@ internal sealed class HeidenhainSession : IAsyncDisposable
private static object? Leaf(HeidenhainTagDefinition tag, object? value)
{
// An ALARM: condition receives the whole (immutable copy of the) list; the projection evaluates it.
if (tag.IsAlarmCondition) return value is List<Lsv2Alarm> alarms ? alarms.ToArray() : null;
if (tag.Address.Kind != HeidenhainAddressKind.Standard) return value;
var address = tag.Address.Catalog!.Address;
var name = address[(address.IndexOf('/') + 1)..];
@@ -57,7 +57,7 @@ internal static class QuestDbAggregateQueries
private static readonly string EmptyKind = ((byte)HistorianValueKind.Empty).ToString(CultureInfo.InvariantCulture);
/// <summary>
/// Average / Minimum / Maximum / Count / Range (PercentGood / PercentBad and Total are time-weighted, not here).
/// Average / Minimum / Maximum / Count / Range (DurationGood / DurationBad / PercentGood / PercentBad and Total are time-weighted, not here).
/// Family columns: <c>6 avg_value, 7 min_value, 8 max_value, 9 sum_value</c> over the <b>Good</b> numeric samples
/// (DOUBLE, NULL when none — Part 13 / the SDK), then <c>10 unc_min, 11 unc_max</c> over the Uncertain ones (the
/// Part 13 Minimum/Maximum/Range status rule) and <c>12 good_non_numeric_count</c>.
@@ -434,7 +434,7 @@ public sealed class QuestDbHistorianDataSource : IHistorianDataSource
/// <inheritdoc />
public bool SupportsReverseEvents => true;
// The seventeen AggregateFamilies.Served - shared with the other SQL backend.
// The nineteen AggregateFamilies.Served - shared with the other SQL backend.
/// <inheritdoc />
public IReadOnlySet<HistoryAggregateType> SupportedAggregates => AggregateFamilies.Served;
@@ -16,7 +16,8 @@ public enum AggregateFamily
ActualTime,
/// <summary>
/// TimeAverage / TimeAverage2 / Total / Total2 / Interpolative, and the duration-based PercentGood / PercentBad:
/// TimeAverage / TimeAverage2 / Total / Total2 / Interpolative, and the duration-based DurationGood / DurationBad /
/// PercentGood / PercentBad:
/// Part 13 time-weighted, with bounding values.
/// The backend streams the window's samples plus the bounding rows and <see cref="TimeWeightedAggregator"/>
/// evaluates them (identically for every backend).
@@ -38,12 +39,13 @@ public static class AggregateFamilies
HistoryAggregateType.MinimumActualTime or HistoryAggregateType.MaximumActualTime => AggregateFamily.ActualTime,
HistoryAggregateType.TimeAverage or HistoryAggregateType.TimeAverage2 or HistoryAggregateType.Total
or HistoryAggregateType.Total2 or HistoryAggregateType.Interpolative
or HistoryAggregateType.PercentGood or HistoryAggregateType.PercentBad => AggregateFamily.TimeWeighted,
or HistoryAggregateType.PercentGood or HistoryAggregateType.PercentBad
or HistoryAggregateType.DurationGood or HistoryAggregateType.DurationBad => AggregateFamily.TimeWeighted,
_ => null,
};
/// <summary>
/// The seventeen aggregates the SQL backends serve — every member <see cref="FamilyOf"/> assigns a family, derived
/// The nineteen aggregates the SQL backends serve — every member <see cref="FamilyOf"/> assigns a family, derived
/// from it so the set and the dispatch can never disagree. Both <c>SqlServerHistorianDataSource</c> and
/// <c>QuestDbHistorianDataSource</c> return it as <see cref="IHistorianDataSource.SupportedAggregates"/>.
/// </summary>
@@ -4,8 +4,8 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common;
/// <summary>
/// The OPC UA Part 13 time-weighted aggregates (<see cref="AggregateFamily.TimeWeighted"/>): <c>TimeAverage</c>,
/// <c>TimeAverage2</c>, <c>Total</c>, <c>Total2</c>, <c>Interpolative</c> and the duration-based <c>PercentGood</c> /
/// <c>PercentBad</c>, evaluated over a time-ordered stream of stored samples. Both SQL backends fetch the same rows and feed them here, so the two produce identical results
/// <c>TimeAverage2</c>, <c>Total</c>, <c>Total2</c>, <c>Interpolative</c> and the duration-based <c>DurationGood</c> /
/// <c>DurationBad</c> / <c>PercentGood</c> / <c>PercentBad</c>, evaluated over a time-ordered stream of stored samples. Both SQL backends fetch the same rows and feed them here, so the two produce identical results
/// by construction.
/// </summary>
/// <remarks>
@@ -50,6 +50,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common;
/// <c>GetSimpleBound</c>); time before the first sample is Bad; at the end of the data the last region runs to the
/// end of its own interval (Part 13; the SDK gives it 1 ms) and later intervals are <c>BadNoData</c>; an interval
/// ending before the first sample ⇒ <c>BadNoData</c>. Status Good; any value kind.</description></item>
/// <item><term>DurationGood / DurationBad</term><description>The same Good / Bad region time, in milliseconds (an
/// OPC UA <c>Duration</c>, as the SDK reports it) — PercentGood / PercentBad × interval ÷ 100, with the same
/// <c>BadNoData</c>, status and Partial rules (#820).</description></item>
/// <item><term>Interpolative</term><description>The interpolated-bounding signal's value at each interval start —
/// for a reverse read, at <c>End − i·interval</c> (Part 13 anchors a reverse read at its later time), emitted
/// latest first.</description></item>
@@ -78,7 +81,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common;
/// interval the data starts inside in the read direction (forward: the first sample fed lies strictly within it;
/// reverse: the latest sample fed lies strictly within it, nothing after — the SDK's <c>m_startOfData</c>,
/// keyed on the first value it is fed); and, forward, the end-of-data interval of TimeAverage2 / Total2 /
/// PercentGood / PercentBad (the SDK's <c>m_endOfData</c>, which it skips for an extrapolated TimeAverage / Total).
/// PercentGood / PercentBad / DurationGood / DurationBad (the SDK's <c>m_endOfData</c>, which it skips for an extrapolated TimeAverage / Total).
/// The timestamp is the interval's <see cref="BucketPlan.BucketTimestamp"/> (its start forward, its later edge
/// reverse); the value is a <see cref="double"/> (Boolean = 0/1, Int64 as double).
/// </para>
@@ -358,14 +361,22 @@ public sealed class TimeWeightedAggregator
? Calc(_rawArea[i] / _usableTicks[i], status, endOfData)
: Calc(_rawArea[i] / TicksPerSecond, status, endOfData);
}
case HistoryAggregateType.PercentGood or HistoryAggregateType.PercentBad:
case HistoryAggregateType.PercentGood or HistoryAggregateType.PercentBad
or HistoryAggregateType.DurationGood or HistoryAggregateType.DurationBad:
{
// No data in or around the interval (it ends before the first sample — the SDK's out-of-range test — or
// starts after the end of the data) ⇒ BadNoData; otherwise the share of the interval's duration.
// starts after the end of the data) ⇒ BadNoData; otherwise the region time (Duration*, in milliseconds —
// an OPC UA Duration) or its share of the interval's duration (Percent*). Uncertain regions count toward
// neither (Part 13 §5.4.3.31-34, Mantis 0006166).
if (_firstSampleUtc is not { } first || hi < first.Ticks || (_dataEndTicks is { } de2 && lo > de2))
return AggregateEvaluator.NoData(stamp, now);
var ticks = _aggregate == HistoryAggregateType.PercentGood ? _goodRegionTicks[i] : _badRegionTicks[i];
return Calc(100d * ticks / duration, HistorianStatusCodes.Good, endOfData);
var ticks = _aggregate is HistoryAggregateType.PercentGood or HistoryAggregateType.DurationGood
? _goodRegionTicks[i]
: _badRegionTicks[i];
var value = _aggregate is HistoryAggregateType.DurationGood or HistoryAggregateType.DurationBad
? (double)ticks / TimeSpan.TicksPerMillisecond
: 100d * ticks / duration;
return Calc(value, HistorianStatusCodes.Good, endOfData);
}
default:
throw new HistoryAggregateNotSupportedException(_aggregate);
@@ -47,7 +47,7 @@ internal static class SqlAggregateQueries
private const string NonNumericKinds = "4, 5";
/// <summary>
/// Average / Minimum / Maximum / Count / Range (PercentGood / PercentBad and Total are time-weighted, not here).
/// Average / Minimum / Maximum / Count / Range (DurationGood / DurationBad / PercentGood / PercentBad and Total are time-weighted, not here).
/// Family columns: <c>6 AvgValue, 7 MinValue, 8 MaxValue, 9 SumValue</c> over the <b>Good</b> numeric samples (float,
/// NULL when none — Part 13 and the SDK compute these over Good values only), then <c>10 UncMin, 11 UncMax</c>
/// over the Uncertain ones (the Part 13 Minimum/Maximum/Range status rule, <see cref="AggregateEvaluator"/>), and
@@ -359,7 +359,7 @@ public sealed class SqlServerHistorianDataSource : IHistorianDataSource
/// <inheritdoc />
public bool SupportsReverseEvents => true;
// <remarks>The seventeen <see cref="AggregateFamilies.Served"/> — shared with the other SQL backend.</remarks>
// <remarks>The nineteen <see cref="AggregateFamilies.Served"/> — shared with the other SQL backend.</remarks>
/// <inheritdoc />
public IReadOnlySet<HistoryAggregateType> SupportedAggregates => AggregateFamilies.Served;
@@ -463,7 +463,7 @@ public sealed class SqlServerHistorianDataSource : IHistorianDataSource
// bucket start (its later edge on a reverse read), except Minimum/MaximumActualTime (the sample's time; ties ⇒
// earliest) and Start/End. Every aggregate but Average sets the Partial bit on the bucket the tag's earliest
// sample lies strictly inside (forward) or its latest sample lies in (reverse: strictly inside).
// PercentGood / PercentBad are duration-based (time-weighted family, below). Count counts Good samples (value-based status; 0/Good on an empty bucket inside the tag's
// DurationGood / DurationBad / PercentGood / PercentBad are duration-based (time-weighted family, below). Count counts Good samples (value-based status; 0/Good on an empty bucket inside the tag's
// data range), Start/End are the raw first/last sample of any quality, Delta is Uncertain only when the bucket's
// first or last sample is not usable (see <see cref="AggregateEvaluator"/>).
// </para>
@@ -475,7 +475,7 @@ public sealed class SqlServerHistorianDataSource : IHistorianDataSource
// <see cref="TimeWeightedAggregator"/>, which fills every interval (an empty one between bounds gets a value).
// </para>
// </remarks>
// <exception cref="HistoryAggregateNotSupportedException">The aggregate is not one of the seventeen served.</exception>
// <exception cref="HistoryAggregateNotSupportedException">The aggregate is not one of the nineteen served.</exception>
// <exception cref="ArgumentOutOfRangeException">The window holds more than <see cref="MaxProcessedBuckets"/> intervals.</exception>
/// <inheritdoc />
public async Task<HistoryReadResult> ReadProcessedAsync(
@@ -35,6 +35,7 @@ public sealed class OpcUaClientDriverBrowser : IDriverBrowser
private readonly ILogger<OpcUaClientDriverBrowser> _logger;
private readonly ISecretResolver? _secretResolver;
private readonly string? _pkiRootOverride;
/// <summary>Creates a new browser. Logger defaults to NullLogger when not supplied.</summary>
/// <param name="logger">Optional logger; defaults to <see cref="NullLogger{T}"/>.</param>
@@ -49,6 +50,18 @@ public sealed class OpcUaClientDriverBrowser : IDriverBrowser
_secretResolver = secretResolver;
}
/// <summary>
/// Test seam (Gitea #818): a browser whose PKI lives under <paramref name="pkiRoot"/> instead of the shared
/// <c>%LocalAppData%/OtOpcUa/adminui-browse-pki</c>, so an integration test can trust a fixture's public
/// certificate in a throwaway store without touching the operator's browse trust list.
/// </summary>
/// <param name="pkiRoot">Directory holding the <c>own</c>/<c>trusted</c>/<c>issuers</c>/<c>rejected</c> stores.</param>
internal OpcUaClientDriverBrowser(string pkiRoot) : this()
{
ArgumentException.ThrowIfNullOrWhiteSpace(pkiRoot);
_pkiRootOverride = pkiRoot;
}
/// <inheritdoc />
// Sourced from the shared DriverTypeNames set rather than the hand-written literal
// this line used to carry. The value is unchanged; the constant is what
@@ -82,7 +95,7 @@ public sealed class OpcUaClientDriverBrowser : IDriverBrowser
"driver's PKI store instead.",
endpoint);
var app = await BuildBrowseAppConfigurationAsync(cancellationToken).ConfigureAwait(false);
var app = await BuildBrowseAppConfigurationAsync(_pkiRootOverride, cancellationToken).ConfigureAwait(false);
ownedApplication = app;
var appConfig = app.ApplicationConfiguration!;
@@ -101,6 +114,11 @@ public sealed class OpcUaClientDriverBrowser : IDriverBrowser
appConfig,
configuredEndpoint,
updateBeforeConnect: false,
// Gitea #816: the same host-name policy as the deployed driver (the SDK's overload without this
// argument hard-codes false), checked against the configured host the endpoint was rewritten to —
// and, like the driver, never on a None endpoint.
checkDomain: OpcUaEndpointSelection.CheckDomainFor(
endpointDesc, opts.CertificateValidation.EffectiveValidateServerHostName),
sessionName: "OtOpcUa AdminUI Browse",
(uint)opts.SessionTimeout.TotalMilliseconds,
identity,
@@ -143,8 +161,10 @@ public sealed class OpcUaClientDriverBrowser : IDriverBrowser
/// the runtime driver (<c>%LocalAppData%/OtOpcUa/adminui-browse-pki/</c>). Browse
/// trust decisions don't leak into the deployed driver's cert store.
/// </summary>
/// <param name="pkiRootOverride">Test-only PKI root; <c>null</c> = the shared browse PKI.</param>
/// <param name="ct">Cancellation token for the configuration build.</param>
private static async Task<ApplicationInstance> BuildBrowseAppConfigurationAsync(CancellationToken ct)
private static async Task<ApplicationInstance> BuildBrowseAppConfigurationAsync(
string? pkiRootOverride, CancellationToken ct)
{
// The ITelemetryContext overload is the non-obsolete ctor; an empty builder keeps SDK
// internals off any logging provider.
@@ -154,7 +174,7 @@ public sealed class OpcUaClientDriverBrowser : IDriverBrowser
ApplicationType = ApplicationType.Client,
};
var pkiRoot = Path.Combine(
var pkiRoot = pkiRootOverride ?? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"OtOpcUa", "adminui-browse-pki");
@@ -19,5 +19,6 @@
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Browser.Tests"/>
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Browser.IntegrationTests"/>
</ItemGroup>
</Project>
@@ -231,6 +231,38 @@ public sealed record OpcUaCertificateValidationOptions
/// operator-managed CRL set. <c>null</c>/empty (default) = <c>%LocalAppData%/OtOpcUa/pki/issuers</c>.
/// </summary>
public string? IssuerStorePath { get; init; }
/// <summary>
/// The value an unset <see cref="ValidateServerHostName"/> resolves to. <c>false</c> keeps the behaviour every
/// deployment had before Gitea #816 (the SDK never checked the host name for this driver family).
/// </summary>
public const bool DefaultValidateServerHostName = false;
/// <summary>
/// Gitea #816 — whether the server certificate must list the host the operator CONFIGURED (the endpoint URL's
/// host, which the shared <see cref="OpcUaEndpointUrlRewriter"/> keeps in place of the server-advertised one)
/// among its DNS / IP subject-alternative names. A mismatch refuses the session with
/// <c>BadCertificateHostNameInvalid</c>.
/// <list type="bullet">
/// <item><c>null</c> (default) = <see cref="DefaultValidateServerHostName"/> (off).</item>
/// <item><c>true</c> = validate. Worth it when trust comes from a CA (a trusted issuer vouches for every
/// certificate it signed, so only the host check ties the certificate to THIS server); adds little when the
/// server's own self-signed certificate is pinned in the trusted-peer store.</item>
/// <item><c>false</c> = explicit opt-out — the NAT / port-publish / IP-addressed case, where the server's
/// certificate names its private host and the reachable address is something else.</item>
/// </list>
/// Only applies to Sign / SignAndEncrypt endpoints: the driver and browser never pass the SDK's
/// <c>checkDomain</c> for a <c>None</c> endpoint, because SDK 2.0.1 would otherwise check at channel creation
/// against the GetEndpoints certificate even there. <see cref="OpcUaClientDriverOptions.AutoAcceptCertificates"/>
/// accepts a host-name mismatch like any other certificate error. A zone-qualified IPv6 host
/// (<c>[fe80::1%eth0]</c>) never matches (the SDK compares the host WITH its zone against the certificate's
/// zone-less IP SANs), so a link-local endpoint needs <c>false</c>.
/// </summary>
public bool? ValidateServerHostName { get; init; }
/// <summary><see cref="ValidateServerHostName"/> with the default applied.</summary>
[System.Text.Json.Serialization.JsonIgnore]
public bool EffectiveValidateServerHostName => ValidateServerHostName ?? DefaultValidateServerHostName;
}
/// <summary>OPC UA message security mode.</summary>
@@ -46,6 +46,33 @@ public static class OpcUaEndpointUrlRewriter
return advertisedUrl;
var builder = new UriBuilder(advertised) { Host = configured.DnsSafeHost, Port = port };
// AbsoluteUri, not ToString(): ToString() un-escapes, turning an advertised "/x%20y" into "/x y" (#812).
return builder.Uri.AbsoluteUri;
return RestoreZoneIndex(builder.Uri, configured);
}
/// <summary>
/// Gitea #819 — keep an IPv6 zone index (<c>[fe80::1%eth0]</c>) from the configured host. .NET's <see cref="Uri"/>
/// parses the zone (only <see cref="Uri.DnsSafeHost"/> / <see cref="Uri.IdnHost"/> carry it) but drops it from
/// <see cref="Uri.Host"/>, <see cref="Uri.Authority"/>, <see cref="Uri.AbsoluteUri"/> and <c>ToString()</c>, so
/// any re-serialised URL loses it. The SDK dials <c>new Uri(EndpointUrl).IdnHost</c>, which DOES carry the zone
/// — so the zone is spliced back into the string, verbatim as the operator wrote it (<c>%eth0</c>, <c>%4</c>, or
/// an RFC 6874 <c>%25eth0</c>: not normalised, so the session dials exactly what GetEndpoints just reached).
/// Without it a link-local endpoint is unroutable: the session would dial a zone-less <c>fe80::</c> address.
/// </summary>
/// <param name="rebuilt">The rewritten URL (configured host, zone already lost).</param>
/// <param name="configured">The operator-configured URL.</param>
/// <returns><paramref name="rebuilt"/>'s absolute URI with the configured zone index restored.</returns>
private static string RestoreZoneIndex(Uri rebuilt, Uri configured)
{
var absolute = rebuilt.AbsoluteUri;
if (configured.HostNameType != UriHostNameType.IPv6) return absolute;
var zoned = configured.DnsSafeHost; // "fe80::1%eth0" — the only accessor that keeps it
if (zoned.IndexOf('%') < 0) return absolute;
var bracketed = rebuilt.Host; // "[fe80::1]"
var authorityStart = absolute.IndexOf("://", StringComparison.Ordinal);
if (authorityStart < 0) return absolute;
var hostAt = absolute.IndexOf(bracketed, authorityStart + 3, StringComparison.OrdinalIgnoreCase);
if (hostAt < 0) return absolute;
return absolute[..hostAt] + "[" + zoned + "]" + absolute[(hostAt + bracketed.Length)..];
}
}
@@ -46,6 +46,23 @@ public static class OpcUaEndpointSelection
return match;
}
/// <summary>
/// Gitea #816 — the <c>checkDomain</c> to hand the SDK for <paramref name="selected"/>: the operator's choice, but
/// never on a <see cref="MessageSecurityMode.None"/> endpoint. SDK 2.0.1 checks the host in TWO places — in
/// <c>DefaultSessionFactory.CreateChannelAsync</c>, against the certificate in the GetEndpoints reply, BEFORE any
/// security-mode test (opc-plc sends one even on its None endpoint), and in <c>Session.OpenAsync</c> once the
/// chain is trusted — so passing <c>true</c> on a None session refused it on a certificate the channel never
/// uses. A host-name check on an unauthenticated channel proves nothing.
/// </summary>
/// <param name="selected">The endpoint the session will open on.</param>
/// <param name="validateServerHostName">The configured (effective) host-name policy.</param>
/// <returns>The <c>checkDomain</c> argument.</returns>
public static bool CheckDomainFor(EndpointDescription selected, bool validateServerHostName)
{
ArgumentNullException.ThrowIfNull(selected);
return validateServerHostName && selected.SecurityMode != MessageSecurityMode.None;
}
/// <summary>Convert a driver <see cref="OpcUaSecurityPolicy"/> to the OPC UA policy URI.</summary>
/// <param name="policy">The driver security policy to map.</param>
/// <returns>The corresponding OPC UA security policy URI.</returns>
@@ -1,5 +1,6 @@
using Opc.Ua;
using Opc.Ua.Security.Certificates;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient;
@@ -12,7 +13,6 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient;
/// </summary>
public static class OpcUaUserIdentityFactory
{
private const string SecretPrefix = "secret:";
/// <summary>
/// Build the user-identity token from options whose credential fields are already resolved plaintext
@@ -103,25 +103,34 @@ public static class OpcUaUserIdentityFactory
}
/// <summary>
/// Return a copy of <paramref name="options"/> with any <c>secret:</c>-prefixed
/// <see cref="OpcUaClientDriverOptions.Password"/> / <see cref="OpcUaClientDriverOptions.UserCertificatePassword"/>
/// resolved through <paramref name="resolver"/>. Non-secret / null / empty fields pass through unchanged (the
/// reference-equal original is returned when nothing changed). Fail-closed: an absent secret, or a
/// <c>secret:</c> ref with no resolver available, throws rather than sending the literal as a credential.
/// Return a copy of <paramref name="options"/> with a <c>secret:opcuaclient/…</c> or
/// <c>env:OTOPCUA_OPCUACLIENT_…</c> <see cref="OpcUaClientDriverOptions.Password"/> /
/// <see cref="OpcUaClientDriverOptions.UserCertificatePassword"/> resolved (lmxopcua#815 namespace). Literal /
/// null / empty fields pass through unchanged (the reference-equal original is returned when nothing changed).
/// Fail-closed: a reference outside the namespace (or <c>file:</c>) throws before any read, and an absent
/// secret, an unset variable, or a <c>secret:</c> ref with no resolver available throws rather than sending
/// the reference string as a credential.
/// </summary>
/// <param name="options">The raw options (credential fields may carry <c>secret:</c> refs).</param>
/// <param name="resolver">The shared secret resolver, or null when none is available.</param>
/// <param name="ct">Cancellation token.</param>
/// <param name="environment">Environment reader (tests); null ⇒ the process environment.</param>
/// <param name="legacy">
/// ⚠️ Deprecated #815 compatibility: the RUNNING driver's session open passes its tracker, so a pre-#815
/// out-of-namespace value keeps the old semantics (a case-insensitive <c>secret:</c> resolves, anything else is
/// a literal) with a rate-limited warning. The AdminUI browser passes null (hard-fail).
/// </param>
/// <returns>An options copy whose credential fields carry resolved plaintext.</returns>
public static async Task<OpcUaClientDriverOptions> ResolveSecretRefsAsync(
OpcUaClientDriverOptions options, ISecretResolver? resolver, CancellationToken ct)
OpcUaClientDriverOptions options, ISecretResolver? resolver, CancellationToken ct,
Func<string, string?>? environment = null, LegacyCredentialReferenceTracker? legacy = null)
{
ArgumentNullException.ThrowIfNull(options);
var password = await ResolveFieldAsync(options.Password, nameof(options.Password), resolver, ct)
var password = await ResolveFieldAsync(options.Password, nameof(options.Password), resolver, ct, environment, legacy)
.ConfigureAwait(false);
var certPassword = await ResolveFieldAsync(
options.UserCertificatePassword, nameof(options.UserCertificatePassword), resolver, ct)
options.UserCertificatePassword, nameof(options.UserCertificatePassword), resolver, ct, environment, legacy)
.ConfigureAwait(false);
if (ReferenceEquals(password, options.Password)
@@ -134,24 +143,48 @@ public static class OpcUaUserIdentityFactory
}
private static async Task<string?> ResolveFieldAsync(
string? value, string fieldName, ISecretResolver? resolver, CancellationToken ct)
string? value, string fieldName, ISecretResolver? resolver, CancellationToken ct,
Func<string, string?>? environment, LegacyCredentialReferenceTracker? legacy)
{
if (string.IsNullOrEmpty(value)
|| !value.StartsWith(SecretPrefix, StringComparison.OrdinalIgnoreCase))
// A literal (or blank) passes through verbatim, reference-equal — the author already knows it.
var kind = CredentialReferences.Parse(value, DriverCredentialPolicy.OpcUaClientScope, out _);
if (kind is CredentialReferenceKind.Blank or CredentialReferenceKind.Literal) return value;
if (kind == CredentialReferenceKind.OutOfScope && legacy is not null)
{
return value;
legacy.Report(fieldName);
return await LegacyResolveFieldAsync(value!, fieldName, resolver, ct).ConfigureAwait(false);
}
var name = value[SecretPrefix.Length..];
// lmxopcua#815: the value is sent to the operator-authored endpoint, so only secret:opcuaclient/… and
// env:OTOPCUA_OPCUACLIENT_… resolve; anything else (out of scope, file:) throws BEFORE any store/env read.
return await CredentialReferences.ResolveAsync(
value,
DriverCredentialPolicy.OpcUaClientScope,
$"OpcUaClientDriverOptions.{fieldName}",
CredentialLiteralPolicy.Allowed,
resolver is null ? null : async (name, c) => await resolver.GetAsync(new SecretName(name), c).ConfigureAwait(false),
environment,
ct).ConfigureAwait(false);
}
/// <summary>
/// ⚠️ DEPRECATED (lmxopcua#815 warn-only compatibility; delete in the hard-fail release): the pre-#815 resolver,
/// verbatim — a case-insensitive <c>secret:</c> resolves (fail-closed), anything else passes through as a
/// literal. Reached ONLY for an out-of-namespace value in an already-deployed, running driver.
/// </summary>
private static async Task<string?> LegacyResolveFieldAsync(
string value, string fieldName, ISecretResolver? resolver, CancellationToken ct)
{
if (!value.StartsWith(CredentialReferences.SecretPrefix, StringComparison.OrdinalIgnoreCase)) return value;
var name = value[CredentialReferences.SecretPrefix.Length..];
if (resolver is null)
throw new InvalidOperationException(
$"OpcUaClientDriverOptions.{fieldName}='{value}' references secret '{name}', but no secret store is " +
"available here (fail-closed).");
$"OpcUaClientDriverOptions.{fieldName} references secret '{name}', but no secret store is available here (fail-closed).");
var resolved = await resolver.GetAsync(new SecretName(name), ct).ConfigureAwait(false);
return !string.IsNullOrEmpty(resolved)
? resolved
: throw new InvalidOperationException(
$"OpcUaClientDriverOptions.{fieldName}='{value}' resolves secret '{name}', but it is " +
"absent from the store (fail-closed).");
$"OpcUaClientDriverOptions.{fieldName} resolves secret '{name}', but it is absent from the store (fail-closed).");
}
}
@@ -29,8 +29,16 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient;
/// back on its own recovers in place.
/// </para>
/// </remarks>
public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IAlarmSource, ISkippedTagReporter, IDriverConnectionLossSource, IDisposable, IAsyncDisposable
public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IAlarmSource, ISkippedTagReporter, IDriverConnectionLossSource, IDriverDiagnostics, IDisposable, IAsyncDisposable
{
// ⚠️ lmxopcua#815 warn-only compatibility (deprecated): the session open of this RUNNING driver keeps
// resolving a pre-#815 out-of-namespace credential with the old semantics, warning rate-limited and surfacing
// it on the diagnostics bag. The AdminUI browser never gets a tracker, so it stays hard-fail.
private readonly LegacyCredentialReferenceTracker _legacyCredentials;
/// <inheritdoc />
IReadOnlyDictionary<string, string> IDriverDiagnostics.GetDiagnostics() => _legacyCredentials.Diagnostics;
/// <summary>Authored tags whose TagConfig carried no usable <c>nodeId</c>, so there is no upstream node
/// to dial. This driver's skip path was the quietest of the twelve: <c>NamespaceMap</c>
/// drops such an entry with a bare <c>continue</c> and not even a log line.</summary>
@@ -82,6 +90,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
_diag = new OpcUaClientDiagnostics(driverInstanceId);
_logger = logger ?? NullLogger<OpcUaClientDriver>.Instance;
_secretResolver = secretResolver ?? NullSecretResolver.Instance;
_legacyCredentials = new LegacyCredentialReferenceTracker(
DriverCredentialPolicy.OpcUaClientScope, driverInstanceId, message => _logger.LogWarning("{CredentialCompatWarning}", message));
_sdkTelemetry = logger is null ? SdkTelemetry.Context : SdkTelemetry.ForLogger(logger);
PostRecoveryReconcileDelay = () => _options.Timeout + _options.KeepAliveInterval;
}
@@ -554,7 +564,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// in BuildCertificateIdentity — flow through BuildUserIdentity(resolvedOptions), so a
// single resolve covers both paths.
var resolvedOptions = await OpcUaClientSecretResolution
.ResolveSecretRefsAsync(_options, _secretResolver, cancellationToken).ConfigureAwait(false);
.ResolveSecretRefsAsync(_options, _secretResolver, cancellationToken, _legacyCredentials).ConfigureAwait(false);
var identity = BuildUserIdentity(resolvedOptions);
@@ -581,7 +591,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception ex)
{
attemptErrors.Add($"{url} -> {ex.GetType().Name}: {ex.Message}");
attemptErrors.Add($"{url} -> {ex.GetType().Name}: {ex.Message}{HostNameRefusalHint(ex)}");
}
}
@@ -726,6 +736,14 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private void WriteLifecycleHealth(long generation, Func<DriverHealth, DriverHealth> next) =>
UpdateHealth(generation, next);
/// <summary>
/// Test seam (Gitea #816): when set, the PKI stores live under this directory instead of the shared
/// <c>%LocalAppData%/OtOpcUa/pki</c>, so an integration test can trust a fixture's certificate in a throwaway
/// store with <see cref="OpcUaClientDriverOptions.AutoAcceptCertificates"/> off (auto-accept also accepts a
/// host-name mismatch, which would hide the check under test). Set before <c>InitializeAsync</c>.
/// </summary>
internal string? PkiRootOverride { get; set; }
/// <summary>
/// Build a minimal in-memory <see cref="ApplicationConfiguration"/>. Certificates live
/// under the OS user profile — on Windows that's <c>%LocalAppData%\OtOpcUa\pki</c>
@@ -747,7 +765,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
};
certValidation.Application = app;
var pkiRoot = Path.Combine(
var pkiRoot = PkiRootOverride ?? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"OtOpcUa", "pki");
@@ -1051,10 +1069,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
endpointConfig.OperationTimeout = (int)_options.Timeout.TotalMilliseconds;
var endpoint = new ConfiguredEndpoint(null, selected, endpointConfig);
// Gitea #816: the SDK's 8-argument CreateAsync hard-codes checkDomain:false, so before #816 the server
// certificate's host name was never checked. The check (when enabled) runs against endpoint.EndpointUrl —
// the CONFIGURED host, because SelectMatching rewrote the advertised one — and never on a None endpoint
// (CheckDomainFor; the SDK would otherwise check at channel creation even there).
var session = await new DefaultSessionFactory(_sdkTelemetry).CreateAsync(
appConfig,
endpoint,
false, // updateBeforeConnect
OpcUaEndpointSelection.CheckDomainFor( // checkDomain (#816)
selected, _options.CertificateValidation.EffectiveValidateServerHostName),
_options.SessionName,
(uint)_options.SessionTimeout.TotalMilliseconds,
identity,
@@ -1085,6 +1109,19 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
return OpcUaEndpointSelection.SelectMatching(all.ToList(), endpointUrl, policy, mode);
}
/// <summary>
/// Gitea #816 — the operator-facing remedy appended to a <c>BadCertificateHostNameInvalid</c> connect failure (only
/// reachable with <c>certificateValidation.validateServerHostName</c> on). The SDK's own text names the host it
/// checked but not the knob.
/// </summary>
/// <param name="ex">The per-endpoint connect failure.</param>
/// <returns>The hint, or an empty string for any other failure.</returns>
internal static string HostNameRefusalHint(Exception ex) =>
ex is ServiceResultException sre && sre.StatusCode == StatusCodes.BadCertificateHostNameInvalid
? " (the server certificate does not name the configured endpoint host; add that host to the certificate, " +
"connect by a name it lists, or — behind NAT / a port publish — set certificateValidation.validateServerHostName=false)"
: string.Empty;
/// <summary>Delegates to the shared <see cref="OpcUaEndpointUrlRewriter.Rewrite"/> (Gitea #676 / #806).</summary>
/// <param name="advertisedUrl">The <c>EndpointUrl</c> the server returned from GetEndpoints.</param>
/// <param name="configuredUrl">The URL the driver was configured with (the one GetEndpoints was sent to).</param>
@@ -31,16 +31,18 @@ internal static class OpcUaClientSecretResolution
/// <param name="options">The raw driver options (credential fields may carry <c>secret:</c> refs).</param>
/// <param name="resolver">The shared secret resolver used by the <c>secret:</c> arm.</param>
/// <param name="ct">Cancellation token for the async secret resolution.</param>
/// <param name="legacy">⚠️ #815 warn-only compatibility tracker of the running driver (deprecated); null ⇒ hard-fail.</param>
/// <returns>An options copy whose credential fields carry resolved plaintext.</returns>
/// <exception cref="InvalidOperationException">
/// A <c>secret:</c> ref names a secret that is absent/tombstoned in the store (fail-closed).
/// </exception>
internal static Task<OpcUaClientDriverOptions> ResolveSecretRefsAsync(
OpcUaClientDriverOptions options, ISecretResolver resolver, CancellationToken ct)
OpcUaClientDriverOptions options, ISecretResolver resolver, CancellationToken ct,
Core.Abstractions.LegacyCredentialReferenceTracker? legacy = null)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(resolver);
// One authority, shared with the AdminUI live browse (Driver.OpcUaClient.Session).
return OpcUaUserIdentityFactory.ResolveSecretRefsAsync(options, resolver, ct);
return OpcUaUserIdentityFactory.ResolveSecretRefsAsync(options, resolver, ct, legacy: legacy);
}
}
@@ -28,6 +28,8 @@
<ItemGroup>
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests"/>
<!-- Gitea #816: the host-name tests trust the fixture certificate in a throwaway PKI (PkiRootOverride). -->
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests"/>
<!-- Gitea #656: the native-alarm re-statement end-to-end tests drive this driver into the real DriverHostActor. -->
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Runtime.Tests"/>
<!-- Gitea #670 review M1: the wire test deletes the driver's subscription server-side through its own session. -->