docs: fill missing XML docs and strip tracking IDs from src comments

Clears CommentChecker findings in src/ (3,280 -> 209, the remainder being false
positives like PLC-5/IEEE-754/M0.0) by adding missing summaries/params/returns,
normalising inheritdoc usage, and removing Gitea/review tracking IDs while keeping
the rationale they annotated. Comment-only: comment-stripped sources are identical
to the parent commit.
This commit is contained in:
Joseph Doherty
2026-10-15 06:14:58 -04:00
parent ebcbd81fca
commit 826312befe
430 changed files with 4434 additions and 3923 deletions
@@ -5,7 +5,7 @@ using Microsoft.Extensions.Logging;
namespace ZB.MOM.WW.OtOpcUa.Host;
/// <summary>
/// Down-if-alone recovery watchdog (arch-review #459). The 2-node <c>keep-oldest</c> split-brain
/// Down-if-alone recovery watchdog. The 2-node <c>keep-oldest</c> split-brain
/// resolver downs the <b>lone survivor</b> when the OLDEST node crashes (the survivor is "the side
/// without the oldest" → <c>DownReachable</c>), and <c>run-coordinated-shutdown-when-down = on</c>
/// terminates that node's <see cref="ActorSystem"/>. Recovery is by <b>exit-and-rejoin</b>: the
@@ -8,7 +8,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>
/// Node-level defaults for the AbCip driver (final review I1), bound from <c>Drivers:AbCip</c>. Lets an
/// operator pin the transport an AbCip driver with NO <c>transport</c> key runs on — at upgrade time,
/// without editing (or being able to edit, #576) every driver config. An explicit per-driver
/// without editing (or being able to edit) every driver config. An explicit per-driver
/// <c>transport</c> key still wins. Overridable by environment variable
/// <c>Drivers__AbCip__DefaultTransport</c>.
/// </summary>
@@ -66,7 +66,7 @@ public static class AbCipDriverDefaultsRegistration
/// Binds + validates <c>Drivers:AbCip</c>. Unconditional on every role: BOTH consumers need it — the driver
/// factory (driver role) and the Test Connect probe (admin role, which must probe the stack the driver would
/// run). A bad value fails host start rather than silently falling back. <c>Program.cs</c> must call this
/// (pinned by <c>AbCipDriverDefaultsOptionsTests</c>): without it an operator's pin is silently ignored (#585).
/// (pinned by <c>AbCipDriverDefaultsOptionsTests</c>): without it an operator's pin is silently ignored.
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="configuration">The host configuration.</param>
@@ -12,7 +12,7 @@ using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>
/// Composition of the OPC UA data-plane authentication + authorization seams (#520), extracted from
/// Composition of the OPC UA data-plane authentication + authorization seams, extracted from
/// <c>Program.cs</c> so the role-conditional branches are reachable from a test.
/// </summary>
/// <remarks>
@@ -42,7 +42,7 @@ public static class DataPlaneAuthRegistration
// matched". TryAdd so a test (or a future host) can substitute one before this runs.
services.TryAddSingleton(TimeProvider.System);
// #520 stage 5 — the node-scoped ACL gate. Registered on EVERY node, not just driver ones, because
// the node-scoped ACL gate. Registered on EVERY node, not just driver ones, because
// OtOpcUaServerHostedService takes it as a constructor parameter and the built-in container resolves
// constructors by whether every parameter is registered, not by whether the parameter type is nullable.
// That is the same trap the IOpcUaUserAuthenticator and IDataPlaneAuthoritySource registrations below
@@ -19,6 +19,8 @@ public static class HistorianBackendRegistry
public const string SqlServerBackendName = "SqlServer";
/// <summary>Binds the <c>ServerHistorian:SqlServer</c> section (shared by the registry and the validator).</summary>
/// <param name="configuration">The host configuration.</param>
/// <returns>The bound SQL Server historian options.</returns>
public static SqlServerHistorianOptions BindSqlServer(IConfiguration configuration)
{
var o = new SqlServerHistorianOptions();
@@ -30,6 +32,8 @@ public static class HistorianBackendRegistry
public const string QuestDbBackendName = "QuestDb";
/// <summary>Binds the <c>ServerHistorian:QuestDb</c> section (shared by the registry and the validator).</summary>
/// <param name="configuration">The host configuration.</param>
/// <returns>The bound QuestDB historian options.</returns>
public static QuestDbHistorianOptions BindQuestDb(IConfiguration configuration)
{
var o = new QuestDbHistorianOptions();
@@ -49,10 +53,15 @@ public static class HistorianBackendRegistry
public static IReadOnlyCollection<string> KnownBackends { get; } = Factories.Keys.ToArray();
/// <summary>True when <paramref name="backend"/> names a registered backend.</summary>
/// <param name="backend">The backend name to look up; may be null.</param>
/// <returns><see langword="true"/> when the name is registered.</returns>
public static bool IsKnown(string? backend) =>
!string.IsNullOrWhiteSpace(backend) && Factories.ContainsKey(backend.Trim());
/// <summary>Builds the provider for <c>options.Backend</c>; throws <see cref="OptionsValidationException"/> if unknown.</summary>
/// <param name="options">The server historian options naming the backend.</param>
/// <param name="configuration">The host configuration passed to the backend factory.</param>
/// <returns>The provider for the configured backend.</returns>
public static IHistorianBackendProvider Resolve(ServerHistorianOptions options, IConfiguration configuration)
{
ArgumentNullException.ThrowIfNull(options);
@@ -51,7 +51,7 @@ public sealed class LdapOptionsValidator : OptionsValidatorBase<LdapOptions>
// A non-positive connect/search timeout would leave the shared library unbounded against a hung
// directory, so fail fast. The other four S2 knobs validated here (AuthTimeoutMs,
// MaxConcurrentAuthentications, OutageFailureThreshold, OutageCooldownSeconds) went with
// LdapOpcUaUserAuthenticator in #520 — they guarded an LDAP bind running inline on OPC UA
// LdapOpcUaUserAuthenticator — they guarded an LDAP bind running inline on OPC UA
// session activation, and no remaining LDAP consumer runs on that path.
builder.RequireThat(options.ConnectionTimeoutMs > 0,
"Ldap:ConnectionTimeoutMs must be > 0.");
@@ -19,7 +19,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <c>Program.cs</c> so the wiring is covered by a DI resolution test — <c>Program.cs</c> is
/// top-level statements and cannot be exercised directly, which is exactly how a
/// "registered but never resolvable" defect ships unnoticed. This family has shipped that
/// defect three times (Secrets 0.2.0, Secrets 0.2.2, ScadaBridge #22).
/// defect three times (Secrets 0.2.0, Secrets 0.2.2, ScadaBridge).
/// </para>
/// <para>
/// <b>Driver-role nodes only.</b> Admin-only nodes have no deployed configuration to cache,
@@ -170,7 +170,7 @@ public static class LocalDbSetup
/// <returns><c>true</c> when this node is configured to replicate.</returns>
public static bool ReplicationIsConfigured(IConfiguration configuration)
{
// Defined beside the alarm-historian drain gate's stricter predicate (#603, review R1 m3): every node
// Defined beside the alarm-historian drain gate's stricter predicate: every node
// the gate treats as sharing rows also captures, so the two never disagree in the harmful direction.
return Runtime.LocalDbReplicationPolicy.CapturesChanges(configuration);
}
@@ -17,6 +17,8 @@ internal static class RoleOverlay
/// The overlay filename suffix: the plain (non-cluster) roles, ordinal-sorted and joined with <c>-</c>, or
/// <see langword="null"/> when the node has none.
/// </summary>
/// <param name="gossipedRoles">The roles gossiped for this node.</param>
/// <returns>The suffix, or <see langword="null"/> when the node has no plain roles.</returns>
public static string? Suffix(IReadOnlyList<string> gossipedRoles)
{
var plain = gossipedRoles
@@ -48,7 +48,7 @@ public static class DriverFactoryBootstrap
/// <returns>The same service collection, for chaining.</returns>
public static IServiceCollection AddOtOpcUaDriverFactories(this IServiceCollection services)
{
// Gitea #511: the Primary data-plane verdict the MQTT driver's Sparkplug host claim is gated on.
// The Primary data-plane verdict the MQTT driver's Sparkplug host claim is gated on.
//
// Registered HERE as well as in AddOtOpcUaRuntime, and both sides TryAdd the same concrete
// RedundancyRoleView, so whichever extension runs first creates it and the other resolves the
@@ -71,7 +71,7 @@ public static class DriverFactoryBootstrap
// The Galaxy driver resolves its Gateway.ApiKeySecretRef secret: arm through the
// shared ISecretResolver (registered unconditionally by AddZbSecrets on every node).
var secretResolver = sp.GetRequiredService<ISecretResolver>();
// Gitea #511: the MQTT driver's Sparkplug primary-host claim is Primary-gated, and unlike
// The MQTT driver's Sparkplug primary-host claim is Primary-gated, and unlike
// every other gated operation it is a STANDING assertion on the driver's own connection —
// there is no inbound message for DriverHostActor to intercept — so the verdict has to
// reach the driver itself. Registered unconditionally on driver-role nodes by
@@ -111,7 +111,7 @@ public static class DriverFactoryBootstrap
});
// The tracker's operator-facing reader: a periodic DPS publisher that mirrors each snapshot to the
// AdminUI resilience panel (R2-10 — closes the "tracker fed by everything, read by nothing" gap).
// AdminUI resilience panel (closes the "tracker fed by everything, read by nothing" gap).
// Lives on driver nodes exactly where the tracker exists. The lazy Func<ActorSystem> is idempotent
// with the one Program.cs registers for the alarm-command router.
services.TryAddSingleton<Func<Akka.Actor.ActorSystem>>(sp => () => sp.GetRequiredService<Akka.Actor.ActorSystem>());
@@ -58,13 +58,11 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac
_runTimeout = runTimeout ?? TimeSpan.FromSeconds(2);
}
// Value-only overload. Every dependency reaches the script stamped Good with an
// evaluation-time timestamp — bare values carry nothing better. The runtime calls the snapshot
// overload instead; this one remains for callers that genuinely hold only
// values.
/// <inheritdoc />
/// <remarks>
/// <b>Value-only overload.</b> Every dependency reaches the script stamped <c>Good</c> with an
/// evaluation-time timestamp — bare values carry nothing better. The runtime calls the snapshot
/// overload instead (archreview 02/S14); this one remains for callers that genuinely hold only
/// values.
/// </remarks>
public VirtualTagEvalResult Evaluate(string virtualTagId, string expression, IReadOnlyDictionary<string, object?> dependencies)
{
ArgumentNullException.ThrowIfNull(dependencies);
@@ -76,15 +74,13 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac
return Evaluate(virtualTagId, expression, snapshots);
}
// Overrides the interface's default (which projects to values and loses the status codes): the
// snapshots pass through as the script's read cache, so
// ctx.GetTag(path).StatusCode and .SourceTimestampUtc are the input's own rather
// than a fabricated Good stamped at evaluation time. The virtual-tag
// actor holds evaluation entirely while any input is Bad, so what a script observes here is Good
// or Uncertain.
/// <inheritdoc />
/// <remarks>
/// Overrides the interface's default (which projects to values and loses the status codes): the
/// snapshots pass <b>through</b> as the script's read cache, so
/// <c>ctx.GetTag(path).StatusCode</c> and <c>.SourceTimestampUtc</c> are the input's own rather
/// than a fabricated <c>Good</c> stamped at evaluation time (archreview 02/S14). The virtual-tag
/// actor holds evaluation entirely while any input is Bad, so what a script observes here is Good
/// or Uncertain.
/// </remarks>
public VirtualTagEvalResult Evaluate(
string virtualTagId, string expression, IReadOnlyDictionary<string, DataValueSnapshot> dependencies)
{
@@ -148,7 +148,7 @@ public static class TelemetryProtoMapNode
}
}
// Gitea #541. The field's own presence carries "driver cannot report skips" vs "reports none",
// The field's own presence carries "driver cannot report skips" vs "reports none",
// so leaving it unset is meaningful — do not replace this with an always-set empty message.
if (e.SkippedTags is { } skipped)
{
@@ -164,7 +164,7 @@ public static class TelemetryProtoMapNode
msg.SkippedTags = payload;
}
// Gitea #640. Presence flag first - an empty map cannot say whether the driver has the capability.
// Presence flag first - an empty map cannot say whether the driver has the capability.
if (e.Diagnostics is not null)
{
msg.HasDiagnostics = true;
@@ -99,7 +99,10 @@ public sealed class LocalDbReplicationHealthCheck : IHealthCheck
_degradedThreshold = degradedThreshold;
}
/// <inheritdoc />
/// <summary>Reports LocalDb replication health: Healthy when absent or in sync, otherwise Degraded per the peer state.</summary>
/// <param name="context">The health check context.</param>
/// <param name="cancellationToken">Cancels the check.</param>
/// <returns>The replication health result.</returns>
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken cancellationToken = default)
{
@@ -9,7 +9,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Logging;
/// reproduced it via handle contention on one path, where <c>RollingFileSink</c> logs the
/// lock-out to SelfLog and quietly falls through to the next name in sequence.
///
/// ⚠️ It is NOT, however, what Gitea #561 turned out to be. That investigation concluded from
/// ⚠️ It is NOT, however, what the reported 0-byte production log turned out to be. That investigation concluded from
/// <c>Get-ChildItem</c> that production's log was 0 bytes for six weeks; opening the file showed
/// 4.66 MB of correct output. See <see cref="MeasureFamilyBytes"/> for the Windows metadata
/// behaviour behind the false reading — the same trap this class must not fall into, since a
@@ -89,6 +89,7 @@ public static class LogPipelineDiagnostics
/// </summary>
/// <param name="configuration">The host configuration carrying <c>Serilog:WriteTo</c>.</param>
/// <param name="emitMarker">Emits one event through the live pipeline (synchronous sinks flush before returning).</param>
/// <returns>A warning describing the silent sink, or <see langword="null"/> when the check passes.</returns>
public static string? CheckFileSinkGrowth(IConfiguration configuration, Action emitMarker)
{
try
@@ -137,6 +138,7 @@ public static class LogPipelineDiagnostics
/// useless when the file sink is the broken part, but it reaches the console sink and any
/// OTel export.
/// </summary>
/// <param name="warning">The warning text to write.</param>
public static void ReportFailure(string warning) => SelfLog.WriteLine("{0}", warning);
/// <summary>
@@ -153,7 +155,7 @@ public static class LogPipelineDiagnostics
/// size-at-open — typically 0, with <c>LastWriteTime == CreationTime</c> — for the entire life
/// of the handle. Measuring that way makes this check declare every healthy sink silent at
/// boot: instrumentation that manufactures the exact failure it exists to detect. It also
/// produced the false 0-byte reading that made Gitea #561 look like a six-week production
/// produced the false 0-byte reading that made that report look like a six-week production
/// logging outage when the file in fact held 4.66 MB of correct output.
///
/// <see cref="FileShare.ReadWrite"/> is required to open the file at all while the sink holds
@@ -6,7 +6,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
/// <summary>
/// Derives the interim server-wide role set for an authenticated principal from its
/// <see cref="NodeAcl"/> grants (#520, stage 2).
/// <see cref="NodeAcl"/> grants.
/// </summary>
/// <remarks>
/// <para>
@@ -9,7 +9,7 @@ using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
/// <summary>
/// Production <see cref="IOpcUaUserAuthenticator"/> for the machine-to-machine data plane (#520):
/// Production <see cref="IOpcUaUserAuthenticator"/> for the machine-to-machine data plane:
/// the client presents the static username <c>apikey</c> with an
/// <c>otua_&lt;keyId&gt;_&lt;secret&gt;</c> credential as the password. Replaces the LDAP adapter.
/// </summary>
@@ -156,12 +156,10 @@ public sealed class ApiKeyOpcUaUserAuthenticator : IOpcUaUserAuthenticator
}
/// <inheritdoc />
/// <remarks>
/// Resolves the <c>anonymous</c> principal's grants through the same mapper a key's principal
/// goes through, so anonymous is authorized by ordinary ACL rows rather than by a special case.
/// Whether anonymous may connect at all is the host's decision
/// (<c>OpcUa:AllowAnonymous</c>) and is settled before this is called.
/// </remarks>
// Resolves the <c>anonymous</c> principal's grants through the same mapper a key's principal
// goes through, so anonymous is authorized by ordinary ACL rows rather than by a special case.
// Whether anonymous may connect at all is the host's decision
// (<c>OpcUa:AllowAnonymous</c>) and is settled before this is called.
public async Task<OpcUaUserAuthResult> AuthenticateAnonymousAsync(CancellationToken ct)
{
IReadOnlyList<NodeAcl> grants;
@@ -171,9 +169,9 @@ public sealed class ApiKeyOpcUaUserAuthenticator : IOpcUaUserAuthenticator
}
catch (Exception ex)
{
// Deny rather than admit-with-no-roles. Admitting would be the pre-#520 behaviour, and doing
// Deny rather than admit-with-no-roles. Admitting would be the previous behaviour, and doing
// it precisely when we could not read what anonymous is allowed to do is the wrong default:
// once reads are gated (stage 6) a no-roles admission stops being harmless.
// once reads are gated a no-roles admission stops being harmless.
_log.LogError(ex, "ApiKeyAuth: key store threw resolving anonymous grants");
return OpcUaUserAuthResult.Deny("Anonymous access is unavailable.");
}
@@ -8,7 +8,7 @@ using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
/// <summary>
/// <see cref="IApiKeyStore"/> served from the deployment artifact (#520, stage 4). This is the key
/// <see cref="IApiKeyStore"/> served from the deployment artifact. This is the key
/// source for a <b>driver-only</b> node, which has had no ConfigDb since per-cluster mesh Phase 4 and
/// until now denied every UserName token.
/// </summary>
@@ -32,7 +32,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
/// keys.
/// </para>
/// <para>
/// <b>Returns a principal's FULL grant set</b> (#520 stage 5). It used to narrow to the
/// <b>Returns a principal's FULL grant set</b>. It used to narrow to the
/// <c>Cluster</c>-scoped rows, because those were the only ones that could confer an interim role.
/// The narrowing was always redundant — <see cref="ApiKeyInterimRoleMapper"/> applies exactly the
/// same filter itself — and it became a trap once scope was enforced: a caller reasonably reading
@@ -95,14 +95,12 @@ public sealed class BoundedApiKeyStore : IApiKeyStore
/// <remarks>Same reason as <see cref="Inner"/>: the shared-clock invariant is only pinnable by reference.</remarks>
public TimeProvider Clock => _time;
// Keyed by apiKeyId alone. utcNow is deliberately not part
// of the key — it changes on every call, so including it would defeat the cache entirely — but a
// cached hit IS re-checked against it before being served, so the TTL can never resurrect a key
// that has expired by the clock in the meantime. The TTL therefore bounds how stale an
// Enabled revocation may be, and nothing else.
/// <inheritdoc />
/// <remarks>
/// Keyed by <paramref name="apiKeyId"/> alone. <paramref name="utcNow"/> is deliberately not part
/// of the key — it changes on every call, so including it would defeat the cache entirely — but a
/// cached hit IS re-checked against it before being served, so the TTL can never resurrect a key
/// that has expired by the clock in the meantime. The TTL therefore bounds how stale an
/// <c>Enabled</c> revocation may be, and nothing else.
/// </remarks>
public async Task<ApiKeyLookup?> FindAsync(string apiKeyId, DateTime utcNow, CancellationToken ct)
{
var ttl = Ttl;
@@ -123,8 +121,8 @@ public sealed class BoundedApiKeyStore : IApiKeyStore
return fresh;
}
// Keyed by principal — the anonymous activation path, which runs on every unauthenticated connect.
/// <inheritdoc />
/// <remarks>Keyed by principal — the anonymous activation path, which runs on every unauthenticated connect.</remarks>
public async Task<IReadOnlyList<NodeAcl>> FindGrantsAsync(string principal, CancellationToken ct)
{
var ttl = Ttl;
@@ -209,7 +207,7 @@ public sealed class BoundedApiKeyStore : IApiKeyStore
/// <c>CancellationTokenSource(TimeSpan, TimeProvider)</c> linked into the inner call, which
/// bounds the call only if the callee chooses to observe the token.
/// <c>Microsoft.Data.SqlClient</c> does not, while a connect or login is in flight on a
/// black-holed socket: the 2026-08-20 R3-05 gate paused the SQL container and watched a keyed
/// black-holed socket: a 2026-08-20 live gate paused the SQL container and watched a keyed
/// activation hang <b>42.9 s</b> past its 2000 ms bound (the Warning below fired only at
/// unpause), stalling an unrelated already-open subscription for <b>57 s</b> behind the
/// <c>SessionManager</c> lock — the exact hazard the bound exists to prevent. So the inner call
@@ -7,12 +7,12 @@ using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
/// <summary>
/// <see cref="IApiKeyStore"/> reading the config database directly (#520, stage 2). Usable on a node
/// <see cref="IApiKeyStore"/> reading the config database directly. Usable on a node
/// that has a ConfigDb — i.e. one carrying the <c>admin</c> role, including a fused admin+driver node.
/// </summary>
/// <remarks>
/// <b>A driver-only node has no ConfigDb since per-cluster mesh Phase 4</b>, so this store cannot be
/// registered there; that node uses <see cref="ArtifactApiKeyStore"/> instead (#520 stage 4).
/// registered there; that node uses <see cref="ArtifactApiKeyStore"/> instead.
/// <para>
/// Reading per activation is what makes revocation prompt here, which is why this store is
/// preferred wherever a ConfigDb exists — including on a fused admin+driver node. ⚠️ It reaches a
@@ -72,7 +72,7 @@ public sealed class ConfigDbApiKeyStore : IApiKeyStore
/// <remarks>
/// <para>
/// This is the same derivation <see cref="Cluster.ClusterRoleInfo"/> performs for
/// <c>IClusterRoleInfo.ClusterId</c> — literally so as of Gitea #532, which collapsed four
/// <c>IClusterRoleInfo.ClusterId</c> — literally so now that the shared derivation collapsed four
/// open-coded copies into <see cref="RoleParser.ClusterIdFromRoles"/>. The copies had drifted:
/// three classified the cluster role case-sensitively and one did not, and only one applied
/// the <c>OTOPCUA_ROLES</c> fallback. On a node that hit either gap this method returned
@@ -127,7 +127,7 @@ public sealed class ConfigDbApiKeyStore : IApiKeyStore
/// <summary>Loads a principal's grants, confined to this node's cluster.</summary>
/// <remarks>
/// <b>The full grant set, not just the <c>Cluster</c>-scoped rows</b> (#520 stage 5). The old
/// <b>The full grant set, not just the <c>Cluster</c>-scoped rows</b>. The old
/// narrowing existed because only cluster-scoped rows could confer an interim role, but
/// <see cref="ApiKeyInterimRoleMapper"/> applies that same filter itself, so it was redundant even
/// then — and once scope is enforced it becomes a trap, silently truncating what
@@ -3,7 +3,7 @@ using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
/// <summary>
/// Source of API keys and their ACL grants for OPC UA session activation (#520).
/// Source of API keys and their ACL grants for OPC UA session activation.
/// </summary>
/// <remarks>
/// A seam rather than a direct ConfigDb read because the two sources differ by node role. A fused
@@ -65,7 +65,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
/// node, the same source the address-space sink + node-write gateway come from), or the configured
/// HistorianGateway read client when <c>AddServerHistorian</c> enabled it. Wired onto the node manager in
/// <see cref="StartAsync"/>.</param>
/// <param name="dataPlaneAuthority">#520 stage 4 — the node's data-plane authorization inputs (its
/// <param name="dataPlaneAuthority">The node's data-plane authorization inputs (its
/// cluster, the current auth generation, and the ACL grants), refreshed from every applied deployment
/// artifact. Wired onto the node manager in <see cref="StartAsync"/> so the stage 5/6 enforcement seams
/// have a cluster identity to build a <c>NodeScope</c> with. Resolves to the empty source on a node with
@@ -81,10 +81,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
/// <param name="actorRegistry">The Akka.Hosting actor registry, used to resolve the local
/// <c>DriverHostActor</c> ref (<c>DriverHostActorKey</c>) the inbound node-write router Asks. Resolved
/// in <see cref="StartAsync"/> after the runtime actors have been registered.</param>
/// <param name="dataPlaneAuthorizer">#520 stage 5 — the node-scoped ACL gate. Nullable, and null means
/// <param name="dataPlaneAuthorizer">The node-scoped ACL gate. Nullable, and null means
/// "not wired" rather than "deny": an unregistered gate must not lock a node out of writes to protect a
/// feature that is off by default. Once wired AND enabled, every unresolvable case inside it denies.</param>
/// <param name="aclOptions">#520 / arch-review 03/S19 — the <c>Security:Acl</c> options, read for
/// <param name="aclOptions">The <c>Security:Acl</c> options, read for
/// <see cref="AclOptions.RevalidationIntervalSeconds"/>. Required, not optional: the built-in DI
/// container does not fall back to a default for an unregistered service, the same trap the
/// <c>IOpcUaUserAuthenticator</c> and <c>IDataPlaneAuthoritySource</c> parameters carry comments
@@ -92,7 +92,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
/// <param name="time">The shared clock — the one instance the authorizer and the API-key store bound
/// also read. Its <c>CreateTimer</c> arms the revalidation tick.</param>
/// <param name="loggerFactory">The logger factory for creating loggers.</param>
/// <param name="primaryRoleSource">Gitea #597 — the data-plane Primary verdict <c>DriverHostActor</c>
/// <param name="primaryRoleSource">The data-plane Primary verdict <c>DriverHostActor</c>
/// publishes on every redundancy snapshot (the same one its native-ack route and device-write gates apply).
/// Wired onto the node manager so a native-condition Acknowledge on a non-Primary node is refused rather than
/// applied and then reverted. Optional: a node with no driver role registers none, and null means "allow" —
@@ -100,7 +100,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
/// <param name="historianUpdater">The selected historian backend's optional HistoryUpdate capability.
/// Optional: when unregistered it resolves to <see cref="HistorianUpdaterHolder.None"/> and HistoryUpdate is
/// reported unsupported on every node.</param>
/// <param name="historyUpdateRoleView">Gitea #674 — the HistoryUpdate verdict <c>DriverHostActor</c> publishes (the
/// <param name="historyUpdateRoleView">The HistoryUpdate verdict <c>DriverHostActor</c> publishes (the
/// data-plane Primary verdict, closed until this node's first redundancy snapshot). Optional: registered on every
/// driver-role node; an admin-only node has none and wires no HistoryUpdate Primary gate (allow).</param>
public OtOpcUaServerHostedService(
@@ -253,7 +253,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
}
});
// Gitea #597: a native ack is accepted only on the Primary. The verdict is the one DriverHostActor
// A native ack is accepted only on the Primary. The verdict is the one DriverHostActor
// publishes and gates the route above on, so a Secondary refuses (BadInvalidState) instead of applying an
// ack the driver will never see and then reverting it. A volatile property read — safe under the SDK Lock.
if (_primaryRoleSource is { } primaryRoleSource)
@@ -291,12 +291,12 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
// The node manager's HistoryRead overrides block-bridge to whatever source is set here.
_server.SetHistorianDataSource(_historianDataSource);
// #520 stage 4 — hand the node manager the node's data-plane authorization inputs. It exists because
// Hand the node manager the node's data-plane authorization inputs. It exists because
// the node manager had NO cluster identity, and NodeScope.ClusterId is required while the evaluator
// fails closed on a mismatch — every scope it could have built would have been denied.
_server.SetDataPlaneAuthority(_dataPlaneAuthority);
// #520 stage 5 — hand it the node-scoped ACL gate. Still behaviour-neutral unless
// Hand it the node-scoped ACL gate. Still behaviour-neutral unless
// Security:Acl:Enabled is set: the gate reports itself disabled and every seam keeps its
// server-wide role check.
_server.SetDataPlaneAuthorizer(_dataPlaneAuthorizer);
@@ -317,10 +317,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
// section is absent; NodeManager is non-null here (guarded above).
_server.NodeManager.MaxTieClusterOverfetch = _serverHistorianOptions.MaxTieClusterOverfetch;
// Gitea #691: the ReturnBounds kill switch (default on).
// The ReturnBounds kill switch (default on).
_server.NodeManager.HonorReturnBounds = HonorReturnBounds;
// Gitea #694: the opt-in HistoryReadEvents horizon (default off = exact to each read's own window).
// The opt-in HistoryReadEvents horizon (default off = exact to each read's own window).
_server.NodeManager.EventReadHorizon = EventReadHorizon;
// Propagate the S3 HistoryRead concurrency bounds (arch-review 03/S3): bounded per-node fan-out
@@ -330,7 +330,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_server.NodeManager.MaxConcurrentHistoryReadBatches = _serverHistorianOptions.MaxConcurrentHistoryReadBatches;
_server.NodeManager.HistoryReadDeadline = _serverHistorianOptions.HistoryReadDeadline;
// Gitea #674: HistoryUpdate is Primary-only (BadInvalidState elsewhere, and closed until this node's first
// HistoryUpdate is Primary-only (BadInvalidState elsewhere, and closed until this node's first
// redundancy snapshot) and refuses a SourceTimestamp beyond now + HistoryUpdateMaxFutureSkew (BadOutOfRange),
// judged against the host clock.
var historyUpdate = BuildHistoryUpdatePosture();
@@ -379,19 +379,19 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
}
/// <summary>
/// Gitea #691 — the <c>ServerHistorian:HonorReturnBounds</c> kill switch <c>StartAsync</c> applies to the node manager
/// The <c>ServerHistorian:HonorReturnBounds</c> kill switch <c>StartAsync</c> applies to the node manager
/// (default <c>true</c> when the section or key is absent). Exposed so the wiring is testable without booting the SDK.
/// </summary>
internal bool HonorReturnBounds => _serverHistorianOptions.HonorReturnBounds;
/// <summary>
/// Gitea #694 — the <c>ServerHistorian:EventReadHorizon</c> <c>StartAsync</c> applies to the node manager (default
/// The <c>ServerHistorian:EventReadHorizon</c> <c>StartAsync</c> applies to the node manager (default
/// <see cref="TimeSpan.Zero"/> = none). Exposed so the wiring is testable without booting the SDK.
/// </summary>
internal TimeSpan EventReadHorizon => _serverHistorianOptions.EventReadHorizon;
/// <summary>
/// Gitea #674 — what <c>StartAsync</c> wires onto the node manager for HistoryUpdate: the Primary gate (read from
/// What <c>StartAsync</c> wires onto the node manager for HistoryUpdate: the Primary gate (read from
/// the <see cref="IHistoryUpdateRoleView"/> on every call; null when none is registered, i.e. allow), the
/// future-timestamp bound from <c>ServerHistorian:HistoryUpdateMaxFutureSkew</c>, and the host clock it is judged
/// against. Separate from <c>StartAsync</c> so the wiring is testable without booting the SDK.
@@ -406,7 +406,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
return new HistoryUpdatePosture(gate, _serverHistorianOptions.HistoryUpdateMaxFutureSkew, _time);
}
/// <summary>Gitea #674 — the HistoryUpdate settings <see cref="BuildHistoryUpdatePosture"/> produces.</summary>
/// <summary>The HistoryUpdate settings <see cref="BuildHistoryUpdatePosture"/> produces.</summary>
/// <param name="PrimaryGate">The node manager's HistoryUpdate Primary gate; null allows.</param>
/// <param name="MaxFutureSkew">The future-timestamp bound; non-positive disables it.</param>
/// <param name="Clock">The clock the bound is judged against.</param>
+16 -16
View File
@@ -57,7 +57,7 @@ using ZB.MOM.WW.Secrets.DependencyInjection;
using ZB.MOM.WW.Secrets.Replicator.AkkaDotNet;
using ZB.MOM.WW.Secrets.Sqlite;
// #618 — the composition root runs inside one try/catch (not re-indented, to keep the diff reviewable)
// the composition root runs inside one try/catch (not re-indented, to keep the diff reviewable)
// so ANY failure to start — an unknown role, a ValidateOnStart rejection, a hosted service that
// throws from StartAsync — is logged Fatal, flushed, and ends the process with a NON-ZERO exit code.
// Left as an unhandled exception the host could stay up as a zombie under a supervisor/container
@@ -68,7 +68,7 @@ try
var builder = WebApplication.CreateBuilder(args);
// The SINGLE role authority: Cluster:Roles first, OTOPCUA_ROLES as the fallback (archreview
// 01/S-12 = 03/C5, R3-04). Resolved off builder.Configuration BEFORE the per-role overlay is
// 01/S-12 = 03/C5). Resolved off builder.Configuration BEFORE the per-role overlay is
// added, because the overlay's FILENAME depends on the answer — which is why a role overlay may
// not itself set Cluster:Roles (AkkaClusterOptionsValidator fails start if one ever does).
// EffectiveRoles drives the entire conditional wiring below — see ZB.MOM.WW.OtOpcUa.Cluster.
@@ -91,7 +91,7 @@ builder.Host.UseWindowsService(options => options.ServiceName = "OtOpcUaHost");
// Per-role appsettings overlay: appsettings.{role}.json (single role) or appsettings.admin-driver.json
// (both). Optional — base appsettings.json carries enough to boot if these don't exist. Built from the
// PLAIN roles only (#678.6): a cluster-{ClusterId} role in the name pointed at a file that never exists.
// PLAIN roles only: a cluster-{ClusterId} role in the name pointed at a file that never exists.
var roleSuffix = RoleOverlay.Suffix(roles);
if (roleSuffix is not null)
{
@@ -142,7 +142,7 @@ await using (var secretsProvider = new ServiceCollection()
// untouched. UseWindowsService already roots the content root at the base dir, so this only affects sinks.
Directory.SetCurrentDirectory(AppContext.BaseDirectory);
// #561 — Serilog SelfLog to logs/serilog-selflog.txt + stderr, enabled before the first logger
// Serilog SelfLog to logs/serilog-selflog.txt + stderr, enabled before the first logger
// builds. Serilog isolates per-sink failures, so a file sink whose writes fail leaves a 0-byte
// log and a healthy process with no signal anywhere; SelfLog is the only channel that sees the
// swallowed exception. Placed after the CWD anchor above so the relative path lands in the
@@ -159,14 +159,14 @@ builder.AddZbSerilog(o => o.ServiceName = "otopcua");
// ConfigDb is admin-only now (per-cluster mesh Phase 4). Only the admin role owns a ConfigDb
// connection string; a driver-only node holds none at all and gets its deployed configuration from
// central over the Phase-3 fetch-and-cache path (ConfigSource:Mode=FetchAndCache). Registering it
// central over the fetch-and-cache path (ConfigSource:Mode=FetchAndCache). Registering it
// unconditionally would throw on a driver-only node, since AddOtOpcUaConfigDb requires the string.
// A fused admin+driver node keeps ConfigDb via its admin role — byte-for-byte unaffected.
// #520 — bound unconditionally: a driver node needs the pepper to VERIFY keys, an admin node needs it
// bound unconditionally: a driver node needs the pepper to VERIFY keys, an admin node needs it
// to MINT them, and getting this wrong on either side is a silent authentication failure rather than a
// startup error.
builder.Services.Configure<ApiKeyOptions>(builder.Configuration.GetSection(ApiKeyOptions.SectionName));
// #520 stage 5 — Security:Acl:Enabled. Default false; see AclOptions for why the flip must be a config
// Security:Acl:Enabled. Default false; see AclOptions for why the flip must be a config
// change rather than a redeploy, and what it swaps rather than adds.
builder.Services.Configure<AclOptions>(builder.Configuration.GetSection(AclOptions.SectionName));
@@ -327,7 +327,7 @@ if (hasDriver)
builder.Services.AddSingleton<IHistorianValueWriter>(sp => sp.GetRequiredService<IHistorianBackendProvider>().CreateValueWriter(sp));
}
// Historian retention (#667). Only a backend that manages retention in-process returns a purger
// Historian retention. Only a backend that manages retention in-process returns a purger
// (SqlServer with RetentionDays set); otherwise the service is inert. Primary-gated via IHistorizationRoleView.
if (serverHistorianOptions.Enabled)
builder.Services.AddHostedService(sp => new HistorianRetentionService(
@@ -402,11 +402,11 @@ if (hasDriver)
builder.Services.TryAddScoped<ILdapGroupRoleMappingService, NullLdapGroupRoleMappingService>();
builder.Services.TryAddScoped<IGroupRoleMapper<string>, OtOpcUaGroupRoleMapper>();
// #520 stage 2 — the OPC UA DATA PLANE is machine-to-machine, so its identity is an API key
// the OPC UA DATA PLANE is machine-to-machine, so its identity is an API key
// (static username "apikey", the otua_ credential as the password), not an LDAP user. The LDAP
// registrations above are deliberately retained: they back ADMINUI LOGIN, which keeps LDAP.
// Only IOpcUaUserAuthenticator moves.
// #520 stage 4 — the node's data-plane authorization inputs (keys + ACL grants + cluster + auth
// the node's data-plane authorization inputs (keys + ACL grants + cluster + auth
// generation), refreshed by OpcUaPublishActor from every applied artifact. Registered on any
// driver-role node because that is what serves an OPC UA data plane; the two interfaces resolve to
// the SAME instance, since the writer and the readers must see one snapshot.
@@ -416,7 +416,7 @@ if (hasDriver)
builder.Services.AddSingleton<IDataPlaneAuthoritySource>(sp => sp.GetRequiredService<DataPlaneAuthorityState>());
builder.Services.AddSingleton<IDataPlaneAuthoritySink>(sp => sp.GetRequiredService<DataPlaneAuthorityState>());
// #520 stage 5 — the tries the ACL gate evaluates against are taken FROM the authority state, not
// the tries the ACL gate evaluates against are taken FROM the authority state, not
// registered independently. The state builds the trie inside the same Apply() call that installs
// the snapshot, so resolving any other cache here would hand the evaluator a permanently empty
// one — and an empty trie denies everything, which looks exactly like "the ACLs are working" until
@@ -437,7 +437,7 @@ if (hasDriver)
builder.Services.AddSingleton<PermissionTrieCache>();
}
// #520 + arch-review 03/S18 — the node-scoped ACL gate, the shared clock and the role-appropriate
// The node-scoped ACL gate, the shared clock and the role-appropriate
// API-key store + user authenticator, all in one extension so the role-conditional branches are
// reachable from a test (Program.cs's top-level statements are not). See DataPlaneAuthRegistration.
builder.Services.AddOtOpcUaDataPlaneAuth(hasAdmin, hasDriver);
@@ -501,7 +501,7 @@ builder.Services.AddHostedService(sp => new ClusterBootstrapCoordinator(
sp.GetRequiredService<IOptions<AkkaClusterOptions>>(),
sp.GetRequiredService<ILogger<ClusterBootstrapCoordinator>>()));
// Down-if-alone recovery watchdog (#459). Registered AFTER AddAkka so it starts after Akka's own
// Down-if-alone recovery watchdog. Registered AFTER AddAkka so it starts after Akka's own
// hosted service has built the ActorSystem; it resolves the system lazily (never at construction) so
// it can't race startup. On an unexpected SBR self-down it stops the host so the service supervisor
// (sc.exe failure / docker restart: unless-stopped) restarts this node — the 2-node keep-oldest
@@ -748,14 +748,14 @@ Log.Information(
"OtOpcUa.Host starting with roles=[{Roles}] (admin={HasAdmin}, driver={HasDriver}) source={Source}",
string.Join(",", roles), hasAdmin, hasDriver, effectiveRoles.Source);
// R3-04 choice 5: Cluster:Roles and OTOPCUA_ROLES set to different normalized role sets is almost
// Cluster:Roles and OTOPCUA_ROLES set to different normalized role sets is almost
// certainly not what the operator intended (Cluster:Roles still wins outright — this is
// observability, not a behaviour change). Logged here rather than inside the static factory because
// Serilog is not configured yet when EffectiveRoles.Resolve runs at the top of this file.
if (effectiveRoles.DisagreementWarning is not null)
Log.Warning("{Warning}", effectiveRoles.DisagreementWarning);
// #561 — startup growth self-check: the banner above went through the live pipeline; verify each
// startup growth self-check: the banner above went through the live pipeline; verify each
// configured file sink physically grew. A sink whose writes silently fail (the wonder-app-vd03
// 0-byte-log incident) is reported at boot — through SelfLog + stderr, which don't depend on the
// broken sink, and through the normal logger for the console sink's benefit.
@@ -770,7 +770,7 @@ await app.RunAsync();
}
// HostAbortedException is how design-time tooling (EF `dotnet ef … --startup-project`, OpenAPI generators —
// HostFactoryResolver) stops Program once it has the built host. It is not a failure: letting it reach the
// Fatal + Environment.Exit(1) below would kill the tool's own process (#618, review R1 m5).
// Fatal + Environment.Exit(1) below would kill the tool's own process.
catch (Exception ex) when (ex is not HostAbortedException)
{
// Log.Logger is still the silent bootstrap logger when the failure happened before AddZbSerilog